import { B as TSerializedCryptoKeyData_X25519_Raw, I as TSerializedCryptoKeyData_Ed25519_Raw, K as TTypeAndId, b as StorageAdapter, t as ClientCryptoKeyLink } from "./index-LpxnCt_F-DNsGOYe-.cjs"; import { C as JSONSerializableValue, E as NiceErrorDomain, T as NiceError, p as INiceErrorIdMetadata } from "./index-BAgdJKZy-COfXA16I.cjs"; import * as v from "valibot"; //#region ../connect-core/build/ReliableLog-DAdK1U4U.d.mts //#region src/wire/Carrier/Carrier.types.d.ts /** * Carrier shapes — the only transport-specific surface a new protocol must implement. The secure * session (handshake + frame crypto + codec) and the protocol routing on top of it are carrier-agnostic; * a carrier just moves frames. Two shapes capture every carrier: * * - {@link IDuplexCarrier} — a persistent, push-capable byte stream (WebSocket, WebRTC `RTCDataChannel`, * Bluetooth GATT, an in-memory pipe). Either side can send at any time, so it supports server→client * pushes (the return path + broadcast). * - {@link IExchangeCarrier} — a request → single-correlated-reply carrier with no unsolicited push * (HTTP, and anything request/response-shaped). The reply rides the response to its own request. * * Frames are `string` (text — handshake control messages and JSON frames) or binary * (`Uint8Array`/`ArrayBuffer` — the optimized binary wire / encrypted frames). */ type TFrame$1 = string | Uint8Array | ArrayBuffer; /** * A bidirectional, push-capable byte stream. Reduces every duplex carrier to "open, send bytes, receive * bytes, close" — a WebSocket, a WebRTC data channel, a Bluetooth characteristic, or an in-memory pipe * all satisfy this, so the identical secure session runs over each. */ interface IDuplexCarrier { /** Resolves once the carrier is open and ready to send; rejects if it closes/errors before opening. */ readonly ready: Promise; /** Whether the carrier is currently open (a synchronous guard before `send`). */ isOpen(): boolean; /** Write one frame to the peer. */ send(frame: TFrame$1): void; /** * Register the carrier's handlers. Called exactly once by the session after `ready`. `onMessage` * receives every inbound frame; `onClose` fires when the carrier goes away. */ attach(handlers: { onMessage: (frame: TFrame$1) => void; onClose: () => void; onError?: (error: unknown) => void; }): void; /** * Close the carrier deliberately (a teardown). Close-notification *timing* is owned by the * session layer, not the carrier: a deliberate local close notifies the session's `onClose` * immediately (the auto-redial must not wait), while the carrier's own eventual platform close * event — which a real WebSocket can deliver seconds late against a dead peer — is deduped * confirmation. A carrier therefore need only make a best effort to fire its `onClose`; it may * lag or (on `send`-into-the-void half-open sockets) never arrive. */ close(): void; /** Optional human-readable endpoint for the devtools route chip. */ readonly label?: string; } /** * A request → single-correlated-reply carrier with no unsolicited push (HTTP). One `exchange` sends a * frame and resolves with exactly the one reply frame for it; the carrier itself correlates them (the * HTTP transaction), so no correlation id is needed on the wire. */ interface IExchangeCarrier { /** Send one frame, await the single correlated reply frame. */ exchange(frame: TFrame$1, opts?: { signal?: AbortSignal; }): Promise; /** Optional human-readable endpoint for the devtools route chip. */ readonly label?: string; } type TCarrier = IDuplexCarrier | IExchangeCarrier; //#endregion //#region src/wire/RuntimeCoordinate.d.ts interface IRuntimeCoordinateSpecifics { /** * A unique and persistent client ID (should stay the same between runtime instance reloads). * * **This id keys the server's trust-on-first-use verify-key pin** (`envId::perId`): the first * verify key a server sees for it is pinned, and a different key is rejected forever after * (`identity_pin_mismatch`). So the connection's crypto-identity `storage` must persist **at * least as long as this id does** — a persistent id read from localStorage paired with a * memory-backed identity store bricks the client on its second load ({@link * RuntimeCoordinate.withPersistentId}). */ perId?: string; /** * A unique instance (or "memory-only") ID (unique for each instance of an action runtime, which should generally * not persist between reloads, depending on the architecture). * * **Reliable-delivery epoch contract:** reliable streams are keyed by the *full* coordinate string * (`envId`/`perId`/`insId`), and a receiver dedups any `seq` at or below its retained high-water. A * fresh boot restarts its outbox at seq 0 — so a reloaded client presenting the *same* full coordinate * would have its first frames silently swallowed as duplicates of the previous session. A fresh-per-boot * `insId` is what makes that structurally impossible: `ActionRuntime` **generates a random one on * first coordinate use when unset**. Only set `insId` yourself if it is genuinely unique per process boot. */ insId?: string; } interface IRuntimeCoordinate extends IRuntimeCoordinateSpecifics { /** * A static runtime environment identifier (e.g. "web_app_v1", "backend_analytics") */ envId: string; } type TRuntimeCoordinateEnvId = `envId[${string}]`; type TRuntimeCoordinateStringId = `${TRuntimeCoordinateEnvId}perId[${string | "_"}]:insId[${string | "_"}]`; interface IRuntimeFullCoordinates extends Required {} declare class RuntimeCoordinate implements IRuntimeCoordinate { readonly envId: string; readonly perId?: string; readonly insId?: string; /** Readable alias for {@link perId}; the serialized own field remains `perId`. */ get persistentId(): string | undefined; /** Readable alias for {@link insId}; the serialized own field remains `insId`. */ get instanceId(): string | undefined; static get unknown(): RuntimeCoordinate; static env(envId: string): RuntimeCoordinate; /** * Env + persistent id — but not *merely* a routing name: on a secure connection this id * keys the server's trust-on-first-use verify-key pin (see {@link IRuntimeCoordinateSpecifics.perId}). * Pair it only with a crypto-identity `storage` that persists at least as long as the id itself, * or every reload presents a new key for a pinned id and is rejected (`identity_pin_mismatch`). */ withPersistentId(perId: string): RuntimeCoordinate; /** * Derive a **per-connection** identity: same env and persistent id, with `connectionId` folded into * the per-boot `insId`. For a runtime that opens *several duplex links to the same peer* — a store * socket and a jobs socket on one backend — where one identity for both is a silent misroute: an * acceptor binds a connection by the full coordinate string, so two links presenting the same one * are indistinguishable and the peer's return path picks whichever bound first. * * Folding rather than replacing is the point: the runtime's `insId` stays the per-boot epoch * reliable delivery needs (see {@link IRuntimeCoordinateSpecifics.insId}), so a per-connection id may * safely be a *stable* label (`"jobs"`) — it discriminates connections without pinning the epoch. * Reached from `connectChannel`'s `connectionId` option; rarely called directly. */ withConnectionId(connectionId: string): RuntimeCoordinate; constructor({ envId, perId, insId }: IRuntimeCoordinate); specify(specifics: IRuntimeCoordinateSpecifics): RuntimeCoordinate; specifyIfUnset(specifics: IRuntimeCoordinateSpecifics): RuntimeCoordinate; toJsonObject(): IRuntimeCoordinate; isExactlySame(other: IRuntimeCoordinate): boolean; isSameFor(other: IRuntimeCoordinate): { id: boolean; perId: boolean; insId: boolean; }; similarityLevel(other: IRuntimeCoordinate): number; get stringId(): TRuntimeCoordinateStringId; /** * Takes the "Runtime Coordinate" and generates a list of full coordinate IDs representing the runtime * with decreasing levels of specificity. * * The first full coordinate ID is the most specific (including instance ID), while the last ID is * the least specific (only environment ID). * * Example output for a RuntimeCoordinate with envId "web_app", perId "user123", and insId "instance456": * [ * "envId[web_app]perId[user123]:insId[instance456]", * "envId[web_app]perId[user123]:insId[_]", * "envId[web_app]perId[_]:insId[_]" * ] * * @returns a list of "full" runtime coordinate IDs with decreasing accuracy for targeting a runtime. */ toStringIds(): TRuntimeCoordinateStringId[]; } //#endregion //#region src/wire/crypto/actionHandshake.d.ts /** * Capability advertised by both peers in the handshake (`hello.caps` / `welcome.caps`) when they understand * the reliable-delivery wire (the 7-slot reliability frame). It lets a `.reliable()` sender detect a peer * that predates reliable support and warn + degrade to best-effort, instead of emitting frames the peer * can't interpret. Non-signed and optional, exactly like `channels` — an old peer simply omits it. */ declare const CAP_RELIABLE = "reliable"; /** * Capability (E3) advertised when a peer understands **keyed** reliable streams (the length-8 `streamKey` * frame + the `k` field on `rack`/`rsync` control frames). Lets a keyed `.reliable()` sender detect a peer * that predates per-key streams and warn (a keyed frame is a distinct length such a peer drops wholesale). * Non-signed and optional, layered on {@link CAP_RELIABLE}. */ declare const CAP_RELIABLE_STREAMKEY = "reliable-streamkey"; /** How much the channel protects after the handshake — chosen by the consumer (perf vs security). */ declare enum ESecurityLevel { /** No handshake; identity is self-asserted (fastest, dev / trusted networks). */ none = "none", /** Handshake authenticates identity (sign/verify + key pin); frames stay plaintext over TLS. */ authenticated = "authenticated", /** Authenticated handshake + every frame AES-GCM encrypted with the derived shared key. */ encrypted = "encrypted" } declare enum EHandshakeMessageType { hello = "hello", welcome = "welcome", prove = "prove", accept = "accept", reject = "reject" } declare const vHsHello: v.ObjectSchema<{ readonly t: v.LiteralSchema; readonly protocol: v.StringSchema; readonly securityLevel: v.PicklistSchema<[ESecurityLevel.none, ESecurityLevel.authenticated, ESecurityLevel.encrypted], undefined>; readonly dictionaryVersion: v.StringSchema; readonly client: v.ObjectSchema<{ readonly envId: v.StringSchema; readonly perId: v.OptionalSchema, undefined>; readonly insId: v.OptionalSchema, undefined>; }, undefined>; readonly clientNonce: v.StringSchema; readonly verifyPublicKey: v.CustomSchema<`ed25519::raw_base64::${string}`, undefined>; readonly exchangePublicKey: v.OptionalSchema, undefined>; /** * The channel tags this connection carries (`channel.tags`). A multi-channel acceptor composes the * codec + dictionary version for exactly this subset; omitted by a plain single-channel client. Not part * of the signed challenge — tampering would compose a different `dictionaryVersion` and fail the check. */ readonly channels: v.OptionalSchema, undefined>, undefined>; /** * Optional capability tags this client understands (e.g. {@link CAP_RELIABLE}). Not part of the signed * challenge — purely a feature advertisement, so a peer that omits it is treated as not supporting them. */ readonly caps: v.OptionalSchema, undefined>, undefined>; }, undefined>; declare const vHsWelcome: v.ObjectSchema<{ readonly t: v.LiteralSchema; readonly securityLevel: v.PicklistSchema<[ESecurityLevel.none, ESecurityLevel.authenticated, ESecurityLevel.encrypted], undefined>; readonly dictionaryVersion: v.StringSchema; readonly server: v.ObjectSchema<{ readonly envId: v.StringSchema; readonly perId: v.OptionalSchema, undefined>; readonly insId: v.OptionalSchema, undefined>; }, undefined>; readonly serverNonce: v.StringSchema; readonly verifyPublicKey: v.CustomSchema<`ed25519::raw_base64::${string}`, undefined>; readonly exchangePublicKey: v.OptionalSchema, undefined>; /** Optional capability tags this server understands (e.g. {@link CAP_RELIABLE}); see {@link vHsHello.caps}. */ readonly caps: v.OptionalSchema, undefined>, undefined>; }, undefined>; declare const vHsProve: v.ObjectSchema<{ readonly t: v.LiteralSchema; readonly signatureBase64: v.StringSchema; }, undefined>; declare const vHsAccept: v.ObjectSchema<{ readonly t: v.LiteralSchema; readonly signatureBase64: v.OptionalSchema, undefined>; }, undefined>; declare const vHsReject: v.ObjectSchema<{ readonly t: v.LiteralSchema; readonly reason: v.StringSchema; /** * Optional machine-readable reject id (e.g. {@link HANDSHAKE_REJECT_ID_PIN_MISMATCH}) so the * dialing side can *branch* on the cause instead of parsing the English `reason` (Inteleport * feedback §3). Additive + optional: an old peer neither sends nor reads it (unknown keys are * stripped on decode), so the frame stays wire-compatible in both directions. */ readonly id: v.OptionalSchema, undefined>; /** The unsupported generation observed by the rejecting peer, when the tag was well formed. */ readonly observedProtocolVersion: v.OptionalSchema, undefined>; /** The generations the rejecting peer can actually speak, newest first. */ readonly supportedProtocolVersions: v.OptionalSchema, undefined>, undefined>; }, undefined>; declare const vHandshakeMessage: v.VariantSchema<"t", [v.ObjectSchema<{ readonly t: v.LiteralSchema; readonly protocol: v.StringSchema; readonly securityLevel: v.PicklistSchema<[ESecurityLevel.none, ESecurityLevel.authenticated, ESecurityLevel.encrypted], undefined>; readonly dictionaryVersion: v.StringSchema; readonly client: v.ObjectSchema<{ readonly envId: v.StringSchema; readonly perId: v.OptionalSchema, undefined>; readonly insId: v.OptionalSchema, undefined>; }, undefined>; readonly clientNonce: v.StringSchema; readonly verifyPublicKey: v.CustomSchema<`ed25519::raw_base64::${string}`, undefined>; readonly exchangePublicKey: v.OptionalSchema, undefined>; /** * The channel tags this connection carries (`channel.tags`). A multi-channel acceptor composes the * codec + dictionary version for exactly this subset; omitted by a plain single-channel client. Not part * of the signed challenge — tampering would compose a different `dictionaryVersion` and fail the check. */ readonly channels: v.OptionalSchema, undefined>, undefined>; /** * Optional capability tags this client understands (e.g. {@link CAP_RELIABLE}). Not part of the signed * challenge — purely a feature advertisement, so a peer that omits it is treated as not supporting them. */ readonly caps: v.OptionalSchema, undefined>, undefined>; }, undefined>, v.ObjectSchema<{ readonly t: v.LiteralSchema; readonly securityLevel: v.PicklistSchema<[ESecurityLevel.none, ESecurityLevel.authenticated, ESecurityLevel.encrypted], undefined>; readonly dictionaryVersion: v.StringSchema; readonly server: v.ObjectSchema<{ readonly envId: v.StringSchema; readonly perId: v.OptionalSchema, undefined>; readonly insId: v.OptionalSchema, undefined>; }, undefined>; readonly serverNonce: v.StringSchema; readonly verifyPublicKey: v.CustomSchema<`ed25519::raw_base64::${string}`, undefined>; readonly exchangePublicKey: v.OptionalSchema, undefined>; /** Optional capability tags this server understands (e.g. {@link CAP_RELIABLE}); see {@link vHsHello.caps}. */ readonly caps: v.OptionalSchema, undefined>, undefined>; }, undefined>, v.ObjectSchema<{ readonly t: v.LiteralSchema; readonly signatureBase64: v.StringSchema; }, undefined>, v.ObjectSchema<{ readonly t: v.LiteralSchema; readonly signatureBase64: v.OptionalSchema, undefined>; }, undefined>, v.ObjectSchema<{ readonly t: v.LiteralSchema; readonly reason: v.StringSchema; /** * Optional machine-readable reject id (e.g. {@link HANDSHAKE_REJECT_ID_PIN_MISMATCH}) so the * dialing side can *branch* on the cause instead of parsing the English `reason` (Inteleport * feedback §3). Additive + optional: an old peer neither sends nor reads it (unknown keys are * stripped on decode), so the frame stays wire-compatible in both directions. */ readonly id: v.OptionalSchema, undefined>; /** The unsupported generation observed by the rejecting peer, when the tag was well formed. */ readonly observedProtocolVersion: v.OptionalSchema, undefined>; /** The generations the rejecting peer can actually speak, newest first. */ readonly supportedProtocolVersions: v.OptionalSchema, undefined>, undefined>; }, undefined>], undefined>; type THsHello = v.InferOutput; type THsWelcome = v.InferOutput; type THsProve = v.InferOutput; type THsAccept = v.InferOutput; type THsReject = v.InferOutput; type THandshakeMessage = v.InferOutput; /** Serialize a handshake message for the wire (handshake frames are JSON — they aren't the hot path). */ declare function encodeHandshakeMessage(message: THandshakeMessage): string; /** Parse + structurally validate an incoming handshake frame; `undefined` if it isn't one. */ declare function decodeHandshakeMessage(raw: string): THandshakeMessage | undefined; /** Stable link id for a runtime coordinate — the key both the crypto link and the connection use. */ declare function runtimeLinkId(coordinate: IRuntimeCoordinate): TTypeAndId; /** * Everything needed to re-derive the shared AES-GCM key for an `encrypted` link after a restart — * the remote's public keys + the HKDF salt/info used at handshake time. The local (server) key pair is * recovered from its own persisted `ClientCryptoKeyLink` storage, so re-linking with this material * yields the identical shared key without a fresh handshake. */ interface IHandshakeEncryptionKeyMaterial { verifyPublicKey: TSerializedCryptoKeyData_Ed25519_Raw; exchangePublicKey: TSerializedCryptoKeyData_X25519_Raw; saltString: string; infoString: string; bindVerifyKeysIntoDerivation: boolean; } /** Outcome of a completed handshake — what the transport/handler needs to wire the channel. */ interface IHandshakeResult { /** The crypto-link id (and connection-registry key) for the authenticated remote. */ linkedClientId: TTypeAndId; /** The remote's authenticated coordinate. */ remote: IRuntimeCoordinate; securityLevel: ESecurityLevel; /** For the `encrypted` level: material to restore the shared key after eviction (persist it). */ encryptionKeyMaterial?: IHandshakeEncryptionKeyMaterial; /** Capability tags the remote advertised (`welcome.caps` for a client). Empty/absent = an old peer. */ remoteCaps?: readonly string[]; } interface IClientVerifyKeyResolveInput { client: IRuntimeCoordinate; verifyPublicKey: TSerializedCryptoKeyData_Ed25519_Raw; } /** * The machine-readable reject id an untrusted verify key produces: the presented key differs from * the one pinned for this client identity (trust-on-first-use). Carried on the reject frame's `id` * and surfaced to the dialing side as `err_wire_connect` id `identity_pin_mismatch`, so an app can * branch on it (`err.hasId("identity_pin_mismatch")`) — the obvious recovery being "this identity * is unusable with this key: clear the client's identity storage / mint a new persistent id". */ declare const HANDSHAKE_REJECT_ID_PIN_MISMATCH = "identity_pin_mismatch"; /** Machine-readable rejection for peers with no common first-party wire generation. */ declare const HANDSHAKE_REJECT_ID_PROTOCOL_VERSION_MISMATCH = "protocol_version_mismatch"; interface IClientVerifyKeyResolver { /** * Decide whether a presented verify key is trusted for a client identity. The signature is already * verified by the time this runs, so this is purely the identity-pinning decision. Swap in a * persistent / pre-provisioned implementation without touching the protocol. An untrusted result * may carry a machine-readable `rejectId` (e.g. {@link HANDSHAKE_REJECT_ID_PIN_MISMATCH}) beside * the human `reason`; it rides the reject frame so the dialing side can branch on the cause. */ resolve(input: IClientVerifyKeyResolveInput): Promise<{ trusted: boolean; reason?: string; rejectId?: string; }>; } /** * In-memory trust-on-first-use resolver: trusts (and pins) the first verify key seen for a client * identity, then rejects a different key for that identity. The default; replace with a storage-backed * resolver for cross-restart pinning (see Step 5). */ declare function createInMemoryTofuVerifyKeyResolver(): IClientVerifyKeyResolver; interface IStorageTofuVerifyKeyResolverOptions { /** `document` preserves the legacy `pins` map; `per_identity` avoids whole-map rewrite growth. */ layout?: "document" | "per_identity"; } /** * Storage-backed trust-on-first-use resolver: pins survive process restarts / Durable Object eviction * (e.g. back it with `createDurableObjectStorageAdapter`). Same policy as the in-memory variant — trust * + pin the first verify key per client identity, reject a different one thereafter. * * Fail-closed by construction: a thrown storage read (`getJson`) or first-pin write (`updateJsonWithDef`) * propagates out of `resolve`, which makes `onProve` reject the handshake — a storage error can never be * mistaken for "first use" and silently trusted. (A genuine `undefined`/absent read is the only path to * a fresh pin; the underlying adapters never coerce a thrown read to `undefined`.) Keep it that way: do * not wrap the storage calls in a `try/catch` that swallows the error. * * On an *eventually-consistent* store a stale "absent" read re-pins the **same** verify key the client * just presented (it is signature-verified before this runs), so the worst case is a harmless re-write, * never a weakened trust decision. Cross-isolate-strong pinning still wants a strongly-consistent store. * * Switching an existing host from `document` to `per_identity` is safe: on each identity's next * contact the legacy pin is honored and migrated to its per-identity record. The reverse switch is * NOT migrated — pins recorded per-identity are invisible to the `document` layout. */ declare function createStorageTofuVerifyKeyResolver(storageAdapter: StorageAdapter, options?: IStorageTofuVerifyKeyResolverOptions): IClientVerifyKeyResolver; interface IClientHandshakeConfig { link: ClientCryptoKeyLink; localCoordinate: IRuntimeCoordinate; dictionaryVersion: string; securityLevel: ESecurityLevel; /** Expected peer identity. Matches envId plus perId when explicitly supplied; ignores insId. */ expectedPeer?: IRuntimeCoordinate; /** Channel tags advertised to a multi-channel acceptor (`channel.tags`); omit for a single-channel peer. */ channelTags?: readonly string[]; /** * Additional capability tags to advertise beyond the built-ins (e.g. frame-protocol tags like * `proto:realm` from a {@link WireProtocolMux}). Additive: absent = byte-identical hello. */ extraCaps?: readonly string[]; } declare function createClientHandshake(config: IClientHandshakeConfig): { createHello(): Promise; onWelcome(welcome: THsWelcome): Promise; onAccept(accept: THsAccept): Promise; }; /** * Resolve the dictionary version a connection should use from its `hello`. A multi-channel acceptor reads * `hello.channels` (the advertised tags), composes the matching channel set, and returns its * `dictionaryVersion` — or `null` when a tag is unknown (the handshake then rejects). A single-channel * acceptor passes a plain string instead. */ type TServerDictionaryVersionResolver = (hello: THsHello) => string | null; interface IServerHandshakeConfig { link: ClientCryptoKeyLink; localCoordinate: IRuntimeCoordinate; /** A fixed version (single channel), or a resolver that composes it from `hello.channels` (multi-channel). */ dictionaryVersion: string | TServerDictionaryVersionResolver; /** * The level(s) this server accepts. A single level is strict (the client must match). An array is a * negotiable allowed set — the server adopts whichever level the client requests, as long as it's in * the set (lets one backend serve `authenticated` and `encrypted` clients at once). `none` in the set * is handled by the transport/handler (a `none` client never reaches the handshake). */ securityLevel: ESecurityLevel | readonly ESecurityLevel[]; /** Trust decision for a client's verify key. Defaults to in-memory TOFU. */ verifyKeyResolver?: IClientVerifyKeyResolver; /** * Additional capability tags to advertise beyond the built-ins (e.g. frame-protocol tags like * `proto:realm` from a {@link WireProtocolMux}). Additive: absent = byte-identical welcome. */ extraCaps?: readonly string[]; } /** * The server handshake's in-flight state between `onHello` and `onProve` — everything `onProve` needs * to verify the client's proof and settle the result. Fully serializable (all JSON / serialized-key * strings), so a stateless server can {@link IServerHandshake.exportPending} it after `hello`, carry it * across requests (e.g. sealed into a continuation token), and {@link IServerHandshake.restorePending} * it on a *different* instance before `prove` — no in-memory handshake to co-locate. The `serverNonce` * is already folded into `challenge`, so it need not be carried separately. */ interface IServerHandshakePending { client: IRuntimeCoordinate; linkedClientId: TTypeAndId; challenge: string; clientVerifyKey: TSerializedCryptoKeyData_Ed25519_Raw; negotiatedLevel: ESecurityLevel; keyMaterial?: IHandshakeEncryptionKeyMaterial; /** The client's advertised `hello.caps` — persisted so a hibernation-restored session keeps them. */ remoteCaps?: readonly string[]; } interface IServerHandshake { onHello(hello: THsHello): Promise; onProve(prove: THsProve): Promise; getResult(): IHandshakeResult | undefined; /** The serializable in-flight state after `onHello` (else `undefined`). See {@link IServerHandshakePending}. */ exportPending(): IServerHandshakePending | undefined; /** * Restore exported `pending` onto a *fresh* handshake instance so `onProve` can run without the * `onHello` that produced it (the stateless / cross-instance path). Re-links the client's verify key * — `onHello`'s `linkClient` was in-memory only and won't exist on this instance — so the signature * check in `onProve` succeeds. Build the instance with the same `config` (identity link + coordinate). */ restorePending(pending: IServerHandshakePending): Promise; } declare function createServerHandshake(config: IServerHandshakeConfig): IServerHandshake; //#endregion //#region src/wire/Mux/WireProtocolMux.d.ts /** * The frame-protocol multiplex seam (realm protocol design §3 / M1). One secure connection carries several * protocols: frames with a reserved prefix byte (`0x01`–`0x0F`) dispatch to the registered * protocol; everything else falls through to the host transport's legacy sniffing * (handshake / control / action — byte-identical, pinned by the byte-compat goldens). * * The mux itself knows nothing about realms or actions. The **host transport** (today: * nice-action's connector link session + acceptor handler) owns it and calls: * - `dispatchIncoming(frame)` first on every decrypted/plain inbound frame — `true` = consumed; * - `localCaps()` when building its handshake hello/welcome caps; * - `setRemoteCaps(caps)` when the peer's handshake arrives; * - `attach(send)` once the connection can carry frames (post-handshake), `detach()` on close. * * Protocols (realm's client/server engines) register via {@link registerProtocol} and speak only * through their {@link IWireProtocolPort}. */ /** What a registered protocol receives to talk on the shared connection. */ interface IWireProtocolPort { /** Send one protocol payload (prefix added here; encrypted by the host when secure). */ send(payload: Uint8Array): void; /** Whether the connection is attached and the peer advertised this protocol. */ isOpen(): boolean; } /** A protocol registration (realm protocol design §3.2). */ interface IWireFrameProtocol { /** Stable id — advertised in handshake caps as `proto:`. */ readonly id: string; /** Reserved prefix byte from {@link WIRE_PROTOCOL_PREFIX}. */ readonly prefixByte: number; /** One inbound protocol payload (prefix already stripped). */ onFrame(payload: Uint8Array, port: IWireProtocolPort): void; /** Connection (re)established for this protocol — peer advertised it, frames may flow. */ onAttach?(port: IWireProtocolPort): void; /** Connection lost — the protocol handles its own resume on the next attach. */ onDetach?(): void; } declare class WireProtocolMux { private readonly _byPrefix; private _send; private _remoteProtocolIds; private _attached; /** Register a protocol (before or after attach; late registrants get an immediate attach). */ registerProtocol(protocol: IWireFrameProtocol): IWireProtocolPort; /** The `proto:` caps to advertise in this side's handshake. */ localCaps(): string[]; /** Record the peer's advertised protocol ids (from its handshake caps). */ setRemoteProtocolIds(ids: ReadonlySet): void; /** Connection ready: give protocols their send path and fire attach for negotiated ones. */ attach(send: (frame: Uint8Array) => void): void; /** Connection lost: notify protocols; sends now throw until the next attach. */ detach(): void; /** * The registered protocol id a frame belongs to, by its prefix byte — `undefined` for a legacy * (unprefixed) frame or an unregistered prefix. Attribution only (the wire-tap lane label); * dispatch stays with {@link dispatchIncoming}. */ protocolIdFor(frame: TFrame$1): string | undefined; /** * Offer one inbound (already-decrypted) frame. Returns `true` when consumed as a protocol * frame — including an unknown/unregistered prefix, which is dropped (a prefixed frame is * *never* a legacy frame, so falling through would mis-decode it). */ dispatchIncoming(frame: TFrame$1): boolean; private _canSpeak; } //#endregion //#region src/wire/Connect/Connect.types.d.ts /** * The wire Connect layer — the connection surface. These are the boundary contracts that * `WireClient` and `WireAcceptor` implement and that protocol modules (`connect-core/action`'s lane, * `connect-core/realm`, any future module) program against. * * This layer never names an action or a realm. Where a protocol module needs to influence a * connection (dial parameters, handshake payload), it does so through an opaque slot defined here — * `TDialContext`, the lane handshake config, the binding's `lane` slot. */ /** * * DIALING — carrier sources over an opaque dial context * */ /** * The opaque, consumer-supplied context threaded from `connect(dialContext)` / a per-dispatch * dial into a carrier source's `open`/`getCacheKey`/`getRouteInfo`. Wire never inspects it — the * protocol module maps its domain concept onto it (nice-action passes the action being * dispatched; a realm-only client passes e.g. `{ gameId }`). Defaults to `undefined` for * carriers whose dial config is static. */ type TDialContext = unknown; /** The two runtime coordinates a connection runs between — this side and the peer being dialed. */ interface IWireClientPair { localClient: RuntimeCoordinate; externalClient: RuntimeCoordinate; } /** Everything a carrier source gets per open: the client pair plus the opaque dial context. */ interface IWireDialParams extends IWireClientPair { dialContext: TDial; } /** * Serializable, display-only description of how traffic was routed through a carrier. Stored on * route items and shown in the devtools external-handler chips. Keep this free of sensitive data * (e.g. auth headers) — route items travel over the wire. */ interface IWireRouteInfo { /** Free-form carrier kind for the devtools chip — e.g. "ws", "webrtc", "http". */ carrierLabel: string; /** Short label for chips, e.g. "POST /resolve_action" or "ws host/resolve_action/ws". */ summary?: string; url?: string; method?: string; detail?: Record; } /** * A reusable opener for an {@link IDuplexCarrier} plus per-dial metadata, parameterized over the * opaque {@link TDialContext}. Built by the carrier factories (`wsCarrier`, `rtcCarrier`, * `inMemoryCarrier`) and handed to a `WireClient`'s transports — adding a new carrier is "write * one of these", nothing else. */ interface IWireDuplexCarrierSource { /** Run this carrier plainly when used by a high-level client. Defaults to secure. */ readonly secure?: boolean; /** Open (or reuse) the carrier for one dial. */ open: (params: IWireDialParams) => IDuplexCarrier; /** Keys identifying a reusable carrier, so one carrier is shared across dials to the same peer. */ getCacheKey?: (params: IWireDialParams) => string[]; /** Devtools route info for traffic routed over this carrier. */ getRouteInfo?: (params: IWireDialParams) => IWireRouteInfo; /** Short carrier-kind label for the devtools chip (e.g. `"ws"`, `"webrtc"`, `"memory"`). */ readonly carrierLabel: string; } /** * The exchange-shape counterpart to {@link IWireDuplexCarrierSource}: a reusable opener for an * {@link IExchangeCarrier} (request/reply, e.g. HTTP). The `shape` tag lets a generic factory * pick the duplex vs exchange transport. Exchange connections are lane-only — prefixed protocols * need a duplex carrier (enforced with `protocol_on_exchange_only`). */ interface IWireExchangeCarrierSource { /** Run this carrier plainly when used by a high-level client. Defaults to secure. */ readonly secure?: boolean; /** Discriminant so a generic factory can tell an exchange source from a duplex one. */ readonly shape: "exchange"; /** Open (or reuse) the carrier for one dial. */ open: (params: IWireDialParams) => IExchangeCarrier; /** Keys identifying a reusable carrier, so one carrier is shared across dials to the same peer. */ getCacheKey?: (params: IWireDialParams) => string[]; /** Devtools route info for traffic routed over this carrier. */ getRouteInfo?: (params: IWireDialParams) => IWireRouteInfo; /** Short carrier-kind label for the devtools chip (e.g. `"http"`). */ readonly carrierLabel: string; } type TWireCarrierSource = IWireDuplexCarrierSource | IWireExchangeCarrierSource; /** * * FRAME RELIABILITY — the neutral envelope shapes * */ /** * Transport-level reliability metadata for one frame — the envelope carrier for the opt-in * `.reliable()` tier. It rides a dedicated optional envelope slot, never a user payload schema, * so a best-effort frame is byte-for-byte unchanged (see the codecs' length-discriminated slot). * The *shape* is protocol-neutral (it is just stream integers); the semantics — when to stamp, * how to ack, what a stream is — belong to the lane protocol that uses it. * * `streamId` is a *local* identity only — a reliable stream is keyed * `(peerCoordinate + route [+ streamKey])`, and both ends already know the peer (the connection) * and the route (the envelope's route slot), so the id is reconstructed on each side and **never * travels on the wire**. Only the integer(s) below do: a request carries its `seq`; a reply (or * standalone ack) carries the cumulative `ack`. The optional `streamKey` *does* ride the wire * (an app can't reconstruct another peer's chosen key) — as an added discriminator only, never * the full id. */ interface IFrameReliability { /** Local stream identity `(peer + route [+ streamKey])`; reconstructed each side, not transmitted. */ streamId: string; /** Monotonic per-stream sequence number stamped on an outgoing reliable request. */ seq?: number; /** Cumulative contiguous high-water this side has received, returned on a reply / standalone ack. */ ack?: number; /** * App-chosen key scoping several independent ordered streams of the *same* route between the same * peers (e.g. one per room id). Rides the wire so the receiver keys the same stream; absent = the * single default stream (byte-identical to before the tier existed). */ streamKey?: string; } /** * The reliability data actually carried on the wire (the `streamId` of {@link IFrameReliability} * is never transmitted — see the codec). A request frame carries `seq`; a reply / standalone ack * carries `ack`; a keyed stream also carries its `streamKey`. This is what a decoder surfaces * off an incoming frame. */ interface IFrameReliabilityWire { seq?: number; ack?: number; streamKey?: string; } /** * * SECURITY — the client-side secure-channel core * */ /** * The protocol-neutral core of a connector's secure-channel config: the level it requests, its * crypto identity, and its coordinate. This is what `WireClient` consumes; nice-action's * `ISecureClientConfig` extends it with the lane-supplied handshake payload (`dictionaryVersion`, * `channelTags`) carried by {@link IWireLaneProtocol}. */ interface IWireSecureClientConfig { /** The level this client requests; the peer must allow it. */ securityLevel: ESecurityLevel; /** This client's crypto identity (verify + exchange key pairs, optionally persisted). */ link: ClientCryptoKeyLink; /** This client's runtime coordinate — its authenticated identity to the peer. */ localCoordinate: IRuntimeCoordinate; /** * Expected identity of the peer. Secure handshakes require the advertised server to match its * `envId`, and its `perId` too when this expectation supplies one. `insId` is deliberately ignored. * Low-level transports may omit this; high-level clients always provide it. */ expectedPeer?: IRuntimeCoordinate; } /** * * PROTOCOLS — prefixed modules + the one lane * */ /** * A wire protocol module — {@link IWireFrameProtocol} grown up for registration-at-construction * on `WireClient`/`WireAcceptor`. Everything the mux contract promises still holds (prefix byte, * `onFrame` with the prefix stripped, attach/detach lifecycle); the additions are negotiated-caps * participation and the acceptor-side security gate. */ interface IWireProtocol extends IWireFrameProtocol { /** * Extra handshake caps this protocol contributes beyond its automatic `proto:` — e.g. a * protocol-level feature flag the peer can discover before frames flow. */ caps?(): readonly string[]; /** * Acceptor-side security gate: by default a `WireAcceptor` dispatches protocol frames only on * connections at the authenticated level or above. A protocol that genuinely works on plain * (dev/trusted-network) connections opts in here. */ allowPlain?: boolean; } /** What the lane protocol receives to talk on the connection — raw frames, no prefix added. */ interface IWireLanePort { /** Send one lane frame verbatim (encrypted by the host when secure). */ send(frame: TFrame$1): void; /** Whether the connection is attached and ready to carry lane frames. */ isOpen(): boolean; } /** * The handshake payload the lane supplies. Wire treats both fields as opaque strings but * emits them under their **byte-frozen wire names** — `dictionaryVersion` is signed into the * handshake challenge and can never be renamed; `channels` rides the hello for the acceptor's * codec selection. A lane-less connection advertises neither; handshake, auth, and encryption * are otherwise identical. */ interface IWireLaneHandshakeConfig { dictionaryVersion: string; channels?: readonly string[]; } /** * The lane's frame surface — what both plain and secure connections drive: the one consumer of * every frame that is *not* a prefixed protocol frame. nice-action's envelopes, control frames, * and JSON text are the only production lane. */ interface IWireLaneEndpoint { /** Stable id — advertised in handshake caps as `proto:` like any protocol. */ readonly id: string; /** * One inbound lane frame (anything the prefix registry didn't claim), already decrypted. May * be async — the session awaits it when flushing buffered frames, so frame order holds. */ onLaneFrame(frame: TFrame$1, port: IWireLanePort): void | Promise; /** * Connection established with the negotiated handshake outcome — frames may flow. Secure * connections only (a plain connection negotiates nothing, so this never fires there). */ onAttach?(port: IWireLanePort, negotiated: { remoteCaps: readonly string[]; }): void; /** Connection lost — the lane handles its own resume on the next attach. */ onDetach?(): void; /** * Extra handshake caps this lane advertises. NOTE: the lane's existing `reliable`/ * `reliable-streamkey` caps stay baked into the handshake state machines as byte-frozen * defaults (every v1 peer emits them) — this hook is for *additional* caps only; a v2 * handshake may generalize the defaults out. */ caps?(): readonly string[]; } /** * The one unprefixed-lane owner per **secure** connection: {@link IWireLaneEndpoint} plus the * handshake payload the lane supplies. A plain connection runs no handshake, so plain sessions * take the bare endpoint. */ interface IWireLaneProtocol extends IWireLaneEndpoint { /** * The handshake payload this side of the lane supplies. On a connector the config is fixed; on * an acceptor it is derived from the peer's advertised `channels` (a multi-channel acceptor * selects/composes the matching codec + dictionary version). */ handshakeConfig(remoteChannels?: readonly string[]): IWireLaneHandshakeConfig; } /** * * CONNECTION STATUS — the `WireClient` lifecycle model * */ declare enum EWireConnectionStatus { /** Built, never dialed — `connect()` not yet called. */ idle = "idle", /** Dialing + handshaking the transport chain for the first time. */ connecting = "connecting", /** Handshake complete on the active transport; protocols may speak. */ ready = "ready", /** A previously-ready connection dropped; the client is re-establishing it. */ reconnecting = "reconnecting", /** The transport chain is exhausted (see `err_wire_connect`) — terminal until `connect()` is called again. */ failed = "failed", /** Deliberately closed via `close()` — terminal. */ closed = "closed" } interface IWireConnectionStatus_Base { status: S; } interface IWireConnectionStatus_Connecting extends IWireConnectionStatus_Base { timeStarted: number; } interface IWireConnectionStatus_Ready extends IWireConnectionStatus_Base { timeReady: number; } interface IWireConnectionStatus_Reconnecting extends IWireConnectionStatus_Base { timeDisconnected: number; /** 1-based attempt counter since the drop, for backoff display. */ attempt: number; } interface IWireConnectionStatus_Failed extends IWireConnectionStatus_Base { /** The chain-exhaustion error (an `err_wire_connect` NiceError at runtime). */ error: Error; timeFailed: number; } type TWireConnectionStatus = IWireConnectionStatus_Base | IWireConnectionStatus_Connecting | IWireConnectionStatus_Ready | IWireConnectionStatus_Reconnecting | IWireConnectionStatus_Failed | IWireConnectionStatus_Base; /** * A transport link-state event — the observation surface for the `WireClient`-owned * reconnection. `reconnect` heals a dropped link silently (correct, but * invisible); these events are how an app renders truthful reconnect UX ("retrying in 8 s, * attempt 4" — and a "retry now" button via `await client.reconnectLink()`) and how telemetry * counts link flakiness. Subscribe via a `WireClient`'s `addLinkEventListener` (surfaced to * consumers as `connectChannel`'s `onLinkEvent`, and to a realm as the connection adapter's * `subscribeLinkEvents`). * * - `link_down` — the duplex link dropped, emitted **at the moment of close** for any real outage * (network, server close, `debug.dropLink`). It does NOT wait for the redial to start, and its * timing is independent of how long the underlying carrier takes to deliver its own close * callback (a real WebSocket's `onclose` can lag by seconds). An **app-initiated teardown** * (`releaseLink()` / `clearTransportCache()` / `dispose()`) is not an outage and emits nothing. * - `redial_scheduled` — keep-alive scheduled attempt N in `delayMs` (backoff + jitter). Not * emitted when the redial loop is off (`reconnect: false`), suppressed (teardown / * `debug.dropLink` window), or parked. A suppression window suppresses only this — never the * `link_down` above. * - `link_up` — a link established. `downForMs` measures the **full outage** from the preceding * `link_down` (at close), not the redial duration; `undefined` on the first-ever establishment * (nothing was down). * * A healthy heal emits `link_down` → `redial_scheduled` → `link_up` and **no realm diagnostic** — * sync-layer health (`onDiagnostic`) stays silent unless sync was actually lost; the realm * forwards only `link_redialed` (with `downForMs`) into its diagnostic stream. */ type TLinkEvent = { type: "link_down"; reason?: string; } | { type: "redial_scheduled"; attempt: number; delayMs: number; } | { type: "link_up"; downForMs?: number; }; /** * * BINDINGS — the persisted per-connection identity * */ /** * A connection's restorable identity — what an acceptor persists (e.g. into a hibernatable * WebSocket's attachment) so a binding survives transport eviction. Two deliberate design points: * * - **`v`** — the schema is versioned from day one, so the *next* shape change migrates instead of * silently invalidating persisted attachments. A rehydrate with an unknown `v` rejects with * `binding_version_mismatch` (= treat the socket as fresh). * - **`lane`** — the lane protocol's private slot: wire persists it opaquely and hands it back on * rehydrate (action stores its `encoding` + `channelTags` here); wire never reads them. */ interface IWireConnectionBinding { v: 1; /** Full client coordinate — first-class, with an exported reader. */ client: IRuntimeCoordinate; /** * Secure-session state (set once a connection's handshake completes). Persisted alongside the * binding so an authenticated/encrypted connection resumes after eviction without * re-handshaking — `keyMaterial` lets the server re-derive the shared key from its own * persisted identity. */ secure?: { securityLevel: ESecurityLevel; linkedClientId: TTypeAndId; keyMaterial?: IHandshakeEncryptionKeyMaterial; }; /** * The protocol ids the client advertised in its handshake (`proto:` caps) — persisted so a * hibernation-resumed connection re-attaches its protocols without re-negotiating. */ protocols?: readonly string[]; /** The lane protocol's opaque persisted state — wire round-trips it, never reads it. */ lane?: unknown; } /** * Persistence hook fired whenever a connection's binding is (re)established or changes — the * host stores it wherever survives eviction (a Durable Object: * `(ws, binding) => ws.serializeAttachment(binding)`), then replays via * {@link IWireAcceptor.rehydrate} on wake. */ type TWireOnConnectionBound = (connection: TConn, binding: IWireConnectionBinding) => void; /** * * THE SURFACES — the `WireClient` and `WireAcceptor` instance contracts * */ /** One transport in a `WireClient`'s preference-ordered chain. */ interface IWireClientTransport { carrier: TWireCarrierSource; /** Run this transport plain even when the client has a secure config (mirrors `connectChannel`). */ secure?: boolean; } /** * The connector backbone's instance surface. Owns everything between "carrier config" and * "protocols may speak": dial + fallback, handshake, secure session, reconnection, transport * cache, mux + protocol lifecycle, pre-ready buffering. */ interface IWireClient { /** This client's identity — protocol modules default their client refs from it. */ readonly coordinate: RuntimeCoordinate; readonly status: TWireConnectionStatus; /** * Establish the connection: idempotent — concurrent/repeat calls share one attempt; resolves * when the preferred transport's handshake completes; rejects with `connect_exhausted` when the * chain is spent. Callable again after `failed`. */ connect(dialContext?: TDial): Promise; /** Deliberately close the connection and release the underlying socket — terminal. */ close(): void; /** Subscribe to status transitions; returns the unsubscribe. Fires on every transition. */ onStatusChange(listener: (status: TWireConnectionStatus) => void): () => void; } /** * The acceptor backbone's instance surface. Owns handshake accept + session-per-connection, * security levels, binding persistence + rehydrate, the protocol registry with un-gated lifecycle * fan-out, and keepalive. The lane (action serving, codecs, reliable inbox) composes on top. */ interface IWireAcceptor { /** One inbound frame from the host transport (a ws message handler, a DO `webSocketMessage`). */ receive(connection: TConn, frame: TFrame$1): void; /** The host observed the connection close/error — detach protocols, drop sessions. */ drop(connection: TConn): void; /** Replay a persisted binding onto a resumed connection (hibernation wake). */ rehydrate(connection: TConn, binding: IWireConnectionBinding): void; /** Install the binding persistence hook (see {@link TWireOnConnectionBound}). */ setOnConnectionBound(onConnectionBound: TWireOnConnectionBound): void; } //#endregion //#region src/wire/tap/wireTap.d.ts /** Well-known lanes; mux-carried protocol frames report their protocol id (e.g. `"realm"`). */ type TWireTapLane = "handshake" | "keepalive" | "action" | "http" | (string & {}); interface IWireTapEvent { dir: "in" | "out"; /** Bytes as sent to / received from the carrier (UTF-8 length for text frames). */ bytes: number; lane: TWireTapLane; /** Connection identity, when the host distinguishes links (server side / multi-link). */ linkId?: string; } type TWireTapFn = (event: IWireTapEvent) => void; /** * Wrap a tap so every event it receives is attributed to `linkId` unless the emitter already named * one. This is how the **connector** side gets per-link attribution: an acceptor knows many peers * and tags each frame with the bound client as it emits, whereas a connector has exactly one peer * for the whole connection — so stamping once at the seam beats threading an id through the pipe, * the session, the keepalive and the exchange carrier. * * Both ends therefore answer the same question with `linkId`: *who is on the other end of this * frame*. A client's core can then split its traffic per backend it dials, exactly as a server's * splits per client it serves. */ declare function withLinkIdTap(tap: TWireTapFn, linkId: string): TWireTapFn; /** * Wrap an exchange (HTTP) carrier so every request/reply pair is reported to the * tap under the `"http"` lane — the exchange path's equivalent of the duplex * session's pipe/dispatch taps. Envelope bytes as handed to the carrier (the * HTTP layer's own headers are outside the library's sight and not counted). */ declare function withExchangeTap(carrier: IExchangeCarrier, tap: TWireTapFn, linkId?: string): IExchangeCarrier; /** The transmitted size of one frame: `byteLength` for binary, UTF-8 length for strings. */ declare function wireFrameByteSize(frame: unknown): number; //#endregion //#region src/wire/SecureSession/acceptorSecureSession.d.ts /** What the handshake authenticated — the handler binds this identity + persists it for resumption. */ interface IAcceptorAuthResult { /** The peer's *authenticated* coordinate — the only identity inbound frames are bound to. */ client: RuntimeCoordinate; securityLevel: ESecurityLevel; linkedClientId: TTypeAndId; /** Present at the `encrypted` level — persist it so an evicted connection re-derives its key. */ keyMaterial?: IHandshakeEncryptionKeyMaterial; /** The channel tags the client advertised in its `hello` — the handler selects the matching codec. */ channelTags?: readonly string[]; /** The capability tags the client advertised in its `hello` (e.g. `proto:realm` frame protocols). */ remoteCaps?: readonly string[]; } /** The persisted secure state replayed to resume an authenticated connection after eviction. */ interface IAcceptorSecureResumeState { securityLevel: ESecurityLevel; linkedClientId: TTypeAndId; keyMaterial?: IHandshakeEncryptionKeyMaterial; } interface IAcceptorSecureSessionConfig { /** This acceptor's crypto identity (verify + exchange key pairs, optionally persisted). */ link: ClientCryptoKeyLink; /** This acceptor's coordinate — its identity to clients during the handshake. */ localCoordinate: IRuntimeCoordinate; /** Wire dictionary version — a fixed string (single channel), or a resolver composing it from the * `hello.channels` tags (multi-channel). The handshake rejects on a mismatch / unknown channel. */ dictionaryVersion: string | TServerDictionaryVersionResolver; /** Accepted level(s) — a single level is strict, an array is a negotiable allowed set. */ securityLevel: ESecurityLevel | readonly ESecurityLevel[]; /** Trust decision for a client's verify key (defaults to in-memory TOFU inside the handshake). */ verifyKeyResolver?: IClientVerifyKeyResolver; /** Additional capability tags to advertise in the `welcome` (e.g. `proto:realm` frame protocols). */ extraCaps?: readonly string[]; /** Whether a plain (`none`) client may be served on this endpoint (i.e. `none` is in the set). */ noneAllowed: boolean; /** * Raw frame writer to this one connection. `tapLane` is opaque metadata forwarded from the * caller (or from the crypto pipe) so the acceptor's wire tap can label the encrypted frame it * eventually writes; a bare handshake write passes none. */ send: (frame: TFrame$1, tapLane?: string) => void; /** Close this connection; called right after a handshake reject so a refused peer cannot hold it. */ close?: () => void; /** The acceptor's wire tap, used here only for the handshake frames the session consumes itself. */ tap?: TWireTapFn; /** Called once the handshake authenticates the peer — the handler binds identity + persists it. */ onAuthenticated: (auth: IAcceptorAuthResult) => void; /** * Route a frame from a `none`-negotiated connection through the handler's plain (self-asserted) * path. `wireBytes` is the frame's size as the carrier delivered it (see {@link receive}). */ routePlain: (frame: TFrame$1, wireBytes?: number) => void; /** Route a decrypted, ready-to-decode action frame from an authenticated connection. */ routeAction: (bytes: TFrame$1, wireBytes?: number) => void; } /** * The acceptor (accept-in) counterpart to the connector's `establishLinkSession`: one connection's * secure session — the server-side handshake driving, the ordered frame crypto, and the per-connection * phase (undecided → plain | authenticated). The crypto itself (ordered encrypt-send / decrypt) lives in * the shared {@link createFrameCryptoPipe}, the same primitive the connector uses — so the secure logic * lives once for both link roles. * * The handler owns one of these per accepted connection and feeds it inbound frames via {@link receive}; * identity binding, persistence, codec, and return routing stay in the handler (driven through the * config callbacks). Inbound processing is serialized per connection because the handshake and decryption * are async — this keeps handshake ordering and frame order intact. */ declare class AcceptorSecureSession { private readonly config; private _handshake?; /** The ordered encrypt-send / decrypt pipe — present only for an `encrypted` connection. */ private _pipe?; private _authed; private _plain; private _handshakeStarted; private _handshakeFailed; /** The channel tags the client advertised in its `hello`, captured for the handler's codec selection. */ private _helloChannels?; /** Serializes inbound processing (handshake + decryption are async). */ private _inboundChain; constructor(config: IAcceptorSecureSessionConfig); /** * Feed one inbound frame. Serialized per connection; routes back through the config callbacks. * `wireBytes` is the frame's size as the carrier delivered it (pre-decryption) — measured by the * acceptor and carried through here because only the decrypted frame reveals its lane. */ receive(frame: TFrame$1, wireBytes?: number): void; private _receive; /** A refused handshake ends this connection: later frames are ignored and the socket closes. */ private _refuse; private _complete; /** * Restore an already-authenticated session after eviction — no handshake. For an `encrypted` * connection the shared key is re-derived asynchronously (the acceptor re-links the client off its own * persisted identity); the pipe's crypto IS that promise, so the connection's first in/out frame * naturally waits for the key before encrypt/decrypt — no separate gate. */ rehydrate(state: IAcceptorSecureResumeState): void; /** * Send an outbound frame: through the encrypt pipe when encrypted, otherwise raw. `tapLane` rides * both branches — an `authenticated` (unencrypted) connection has no pipe but its frames are just * as much action/protocol traffic, and must not be mislabelled. */ send(frame: TFrame$1, tapLane?: string): void; private _buildPipe; } //#endregion //#region src/wire/Connect/WireAcceptor.d.ts /** * An acceptor-side wire protocol (the server half of {@link IWireProtocol}): a protocol module * riding an acceptor's connections beside the lane. The connection-scoped twin of the client * mux's `IWireFrameProtocol` — `onFrame` receives the originating connection because one acceptor * serves many peers. Register at construction (`protocols`) or via * {@link WireAcceptor.registerProtocol}; the acceptor dispatches reserved-prefix frames * (`0x01`–`0x0F`) here per connection, advertises `proto:` in its handshake welcome, and fires * attach/detach around the connection lifecycle (including hibernation resume). `send` writes one * protocol payload back to that connection — prefixed here, encrypted by the secure session. */ interface IWireAcceptorProtocol { readonly id: string; readonly prefixByte: number; onFrame(connection: TConn, payload: Uint8Array, send: (payload: Uint8Array) => void, context?: IWireAcceptorProtocolContext): void; onAttach?(connection: TConn, send: (payload: Uint8Array) => void, context?: IWireAcceptorProtocolContext): void; onDetach?(connection: TConn, context?: IWireAcceptorProtocolContext): void; /** * Security gate opt-in: by default the acceptor drops protocol frames — and skips * lifecycle hooks — on connections at the `none` level, where the peer identity is * self-asserted. A protocol that genuinely works on plain (dev/trusted-network) connections * opts in here. */ allowPlain?: boolean; } /** Trusted connection facts supplied by `WireAcceptor` to protocol hooks. */ interface IWireAcceptorProtocolContext { /** Bound peer identity; undefined before authentication or plain-lane binding. */ client: RuntimeCoordinate | undefined; /** Negotiated security level; `none` for plain or not-yet-authenticated connections. */ level: ESecurityLevel; } /** * Server-side secure-channel config — the acceptor twin of `IWireSecureClientConfig`. When set, * each connection negotiates a level from {@link securityLevel}: an `authenticated`/`encrypted` * client must complete the handshake (and is then bound to its *authenticated* coordinate) before * any lane or protocol frame is accepted. A `none` client (only when `none` is in the allowed * set) is accepted as-is with a self-asserted identity. */ interface IWireAcceptorSecurity { /** * Accepted level(s). A single level is strict; an array is a negotiable allowed set — the server * adopts whichever level each client requests (e.g. `[none, authenticated, encrypted]` serves * all three over one endpoint). */ securityLevel: ESecurityLevel | readonly ESecurityLevel[]; /** This server's crypto identity (verify + exchange key pairs, optionally persisted). */ link: ClientCryptoKeyLink; /** This server's coordinate — its identity to clients during the handshake. */ localCoordinate: IRuntimeCoordinate; /** Trust decision for a client's verify key (defaults to in-memory TOFU inside the handshake). */ verifyKeyResolver?: IClientVerifyKeyResolver; } /** * The lane protocol's acceptor-side hooks (E5, transitional until Phase 5 formalizes * `IWireLaneProtocol` on both sides): the one consumer of every frame the prefix registry doesn't * claim, plus the owner of the binding's opaque {@link IWireConnectionBinding.lane} slot. Action's * `ChannelAcceptor` is the only production implementation. */ interface IWireAcceptorLane { /** * The lane's handshake version payload (E5, formalized at the connection design) — a fixed string, or a * resolver composing it from the peer's hello (a multi-channel lane). Wire treats it opaquely * but signs it into the challenge under its byte-frozen wire name; the handshake rejects on a * mismatch. Required when the acceptor has a security config (the handshake cannot run * without it); irrelevant on a plain acceptor. */ dictionaryVersion?: string | TServerDictionaryVersionResolver; /** * One inbound lane frame (anything unprefixed), already decrypted, with the connection's * negotiated security level. On a plain connection the level is `none` and the frame's identity * is self-asserted — the lane binds it via {@link WireAcceptor.bindPlainConnection}. */ onFrame(connection: TConn, frame: TFrame$1, level: ESecurityLevel): void; /** * The connection's handshake completed — fired after the identity is bound but before protocols * attach and the binding persists, so the lane can capture its negotiated facts (encoding, * channel tags) in time for {@link bindingState}. */ onAuthenticated?(connection: TConn, auth: IAcceptorAuthResult): void; /** The lane's opaque slot persisted on the connection's binding — read at every persist. */ bindingState?(connection: TConn): unknown; /** Restore the lane slot from a rehydrated binding (fired before protocols re-attach). */ restoreBindingState?(connection: TConn, lane: unknown): void; /** * The connection is being dropped — fired with its bound client (if any) before the acceptor * fans protocol `onDetach` and forgets the identity, so lane cleanup keyed by the client * (reliable-stream latches, codecs) still resolves it. */ onDrop?(connection: TConn, client: RuntimeCoordinate | undefined): void; } interface IWireAcceptorOptions { /** Write a raw frame to a specific live connection (e.g. `(ws, frame) => ws.send(frame)`). */ send: (connection: TConn, frame: TFrame$1) => void; /** * Close a live connection (e.g. `(ws) => ws.close(1008)`). Used after a handshake reject so a * refused peer cannot keep the socket open; without it the socket stays open until the peer leaves. */ close?: (connection: TConn) => void; /** * Enable the authenticated (optionally encrypted) handshake. When omitted, connections are * trusted as-is (identity self-asserted) — fine for dev / trusted networks. */ security?: IWireAcceptorSecurity; /** The lane protocol's hooks — the consumer of every unprefixed frame (E5). */ lane: IWireAcceptorLane; /** Protocol modules registered at construction (the A.2-safe path). */ protocols?: readonly IWireAcceptorProtocol[]; /** Binding persistence hook (see {@link TWireOnConnectionBound}). */ onConnectionBound?: TWireOnConnectionBound; /** * The server-side wire-observation seam — the acceptor's mirror of the connector's * `connectChannel({ wireTap })`. Every frame that actually crosses a carrier is reported with its * TRUE wire byte size (measured post-encryption on the way out, pre-decryption on the way in: * exactly what the platform bills) and its lane (`handshake`, `keepalive`, `action`, or a * protocol id such as `realm`), tagged with the connection's bound client as `linkId`. * Sizes only, never payload contents. With no tap the cost is one null check per frame. */ tap?: TWireTapFn; } /** * The acceptor backbone: everything between "an inbound frame arrived on a * connection" and "a protocol module (or the lane) may handle it" — handshake accept + * secure-session-per-connection, security levels, the client-identity registry, the protocol * registry with prefix dispatch, the **security gate** (the connection contract: protocol traffic requires an * authenticated connection unless the protocol opts into `allowPlain`), the **un-gated lifecycle * fan-out** (the connection contract: attach/detach fire for every registered protocol the gate admits, not * just the caps-advertised ones — both hooks are idempotent by contract, so a missing cap is a * non-event instead of a silent liveness hole), the versioned {@link IWireConnectionBinding} * persistence + {@link rehydrate} (hibernation), and the wire keepalive. * * The lane (action serving, codecs, reliability) composes on top through * {@link IWireAcceptorLane}; nothing here names an action or a realm. */ declare class WireAcceptor implements IWireAcceptor { private readonly _send; private readonly _close?; private readonly _tap?; private readonly _security?; private readonly _lane; /** Normalized accepted levels; whether `none` (plain) is allowed; whether any level needs a handshake. */ private readonly _allowedLevels; private readonly _noneAllowed; private readonly _handshakeMode; private _onConnectionBound?; private _disposed; private readonly _connByClient; private readonly _clientByConn; private readonly _levelByConn; private readonly _sessionByConn; /** The last persisted (or rehydrated) binding per connection — re-persists merge through it. */ private readonly _bindingByConn; /** Registered protocols by prefix byte. */ private readonly _protocols; /** Per-connection protocol ids the client advertised (persisted informationally on the binding). */ private readonly _protoIdsByConn; /** Protocols already warned for gated (plain-connection) frame drops — one warning per id. */ private readonly _gateWarned; constructor(options: IWireAcceptorOptions); /** Feed one inbound frame from a connection: keepalive, then handshake/session, then dispatch. */ receive(connection: TConn, frame: TFrame$1): void; private _receivePlain; /** Route a decrypted frame from an authenticated connection: protocols first, then the lane. */ private _routeAuthed; /** * The lane a *plaintext* frame belongs to: a reserved-prefix frame names its protocol * (`realm`, …); everything else is the action lane. Mirrors the connector's * `mux.protocolIdFor(frame) ?? "protocol"` / `"action"` split so both ends label alike. */ private _laneFor; /** A connection's bound client, so a multi-client server attributes traffic per link. */ private _linkId; private _tapIn; /** The one outbound write: measured post-encryption, exactly as the carrier transmits it. */ private _writeTapped; /** * Register a protocol module. Prefer registration at construction (`protocols`) — this method * exists for composition layers that assemble the acceptor before its protocols (it is safe * until the first connection's handshake, which snapshots the advertised caps). */ registerProtocol(protocol: IWireAcceptorProtocol): void; /** The `proto:` caps to advertise in this acceptor's handshake welcome. */ private _protocolCaps; /** Per-connection protocol send: prefix here, encrypt via the secure session when present. */ protocolSendFor(connection: TConn, protocol: IWireAcceptorProtocol): (payload: Uint8Array) => void; /** * Whether a protocol may speak on a connection — the security gate (A.6). Protocol traffic and * lifecycle require an authenticated peer: on a `none`-level connection the binding identity is * self-asserted, so `allowPlain` is the explicit opt-in for dev/trusted-network setups. */ private _gateAdmits; /** * Protocol frame dispatch: a reserved-prefix frame belongs to a registered protocol and never * falls through to the lane — an unknown prefix is consumed-and-dropped (negotiation should * prevent it; mis-decoding it would be worse), and so is a frame the security gate blocks. */ private _dispatchProtocolFrame; /** * Fire `onAttach` for **every registered protocol the gate admits** (fresh handshake or * rehydrate) — deliberately not filtered by the client's advertised caps (A.2.3): the hooks are * idempotent by contract, so an empty/missing caps list degrades to a no-op on the peer instead * of a silently missed wake resume. The advertised ids are still recorded (and persisted on the * binding) as the negotiation facts. */ private _attachProtocols; /** * The secure session for a connection (built lazily on its first secure-mode frame). The * session owns all crypto/handshake/chain state; the acceptor keeps only the registries. */ private _sessionFor; /** Bind + persist a connection's authenticated identity once its handshake completes. */ private _onAuthenticated; /** Install (or replace) the binding persistence hook after construction. */ setOnConnectionBound(onConnectionBound: TWireOnConnectionBound): void; /** * Plain-path identity binding: bind the connection to a self-asserted client coordinate (the * lane decoded it off an inbound frame) and persist a fresh binding when the identity is new. * Secure mode never calls this — the handshake binds the authenticated coordinate instead. While * another live connection holds that coordinate through a handshake, pushes and * `connectionForClient` keep resolving to it; the plain claim takes over only once it drops. */ bindPlainConnection(connection: TConn, client: RuntimeCoordinate): void; /** * Restore a connection→client binding without an inbound frame — for transports that resume * after eviction. Pair it with `onConnectionBound`: persist the binding there, then replay each * live connection here when the channel comes back (e.g. a Durable Object iterating * `ctx.getWebSockets()` as it wakes from hibernation). A binding of an unknown schema version * is ignored with a warning — the socket is simply treated as fresh (its client re-handshakes). */ rehydrate(connection: TConn, binding: IWireConnectionBinding): void; private _persist; private _bind; /** Forget a connection (call on socket close) so stale entries don't misroute later traffic. */ drop(connection: TConn): void; /** Internal detach path used once during terminal disposal after public entry points are closed. */ private _drop; /** Send a raw (already lane/protocol-encoded) frame — through the secure session when present. */ sendTo(connection: TConn, frame: TFrame$1): void; /** Live connection for a client coordinate's stringId, if currently registered. */ connectionForClient(clientStringId: string): TConn | undefined; /** The bound client coordinate for a connection, if any. */ clientForConnection(connection: TConn): RuntimeCoordinate | undefined; /** Whether this acceptor currently holds a live connection bound to the client. */ ownsLiveConnectionFor(clientStringId: string): boolean; /** Whether this acceptor currently tracks `connection`. */ hasConnection(connection: TConn): boolean; /** Every currently-bound connection (mid-handshake sockets are not yet bound). */ connections(): IterableIterator; /** The number of currently-bound connections. */ get connectionCount(): number; /** The connection's negotiated security level (`none` when plain / not yet handshaken). */ levelFor(connection: TConn): ESecurityLevel; private _protocolContext; /** The last persisted (or rehydrated) binding for a connection, if any. */ bindingFor(connection: TConn): IWireConnectionBinding | undefined; /** Quiesce permanently: detach every known connection and ignore late/in-flight traffic. */ dispose(): void; get disposed(): boolean; } declare const createWireAcceptor: (options: IWireAcceptorOptions) => WireAcceptor; //#endregion //#region src/wire/PeerLink/ReliableInbox.d.ts /** * Server-side receive bookkeeping for the `.reliable()` tier — the ordered, dedup half that the * {@link ChannelAcceptor} drives. It is **pure**: given a stream's incoming `seq` it decides what to * dispatch now, buffers out-of-order frames until the gap fills, and reports the cumulative contiguous * high-water to ack. It never touches the network or the runtime — the acceptor owns dispatch + acks — * which keeps it exhaustively unit-testable. * * ## Guarantee * Ordered, at-least-once, dedup-by-seq **within a live inbox** (one server process/session): * - a **new in-order** seq (`contiguous + 1`) is delivered, then any buffered contiguous run drains; * - an **out-of-order** seq (`> contiguous + 1`) is buffered (ordering — head-of-line by design) and the * current high-water is acked, signalling the client to resend the gap; * - a **duplicate** seq (`<= contiguous`) is dropped from dispatch (the handler never sees a retry) and * the current high-water is re-acked, so the client's outbox drains after a reconnect. * * Across a session reset (fresh process / evicted DO) the inbox starts empty at `contiguous = -1`. If a * stream's *first* frame arrives already past seq 0, the client is mid-stream against a receiver that lost * its state: `receive` returns `needsResync` (creating no state) so the acceptor can request a re-sync — * the client renumbers its unacked frames from 0 and resends, and the in-flight tail continues in order * instead of stalling. Frames the old receiver already acked are gone (correctly — they were delivered * before the reset); the persisted tier (Phase 5) persists the high-water to also survive eviction outright. * Reliable handlers must still be idempotent (a reconnect resend can redeliver an in-flight frame). */ interface IReliableInboxResult { /** Payloads to dispatch now, in ascending seq order (the new in-order one + any drained buffered). */ deliver: T[]; /** Cumulative contiguous high-water after processing — the ack to return to the sender. */ ack: number; /** `true` when the seq was already contiguous (a resend): nothing delivered, caller re-acks. */ duplicate: boolean; /** * `true` when the receiver saw a stream **mid-stream with no prior state** (first-ever `seq > 0`) — a * session-tier reset (fresh process / evicted server). Nothing is delivered or buffered; the caller should * ask the sender to re-sync (renumber its unacked frames from 0 and resend) rather than let this land as an * unfillable gap. The persisted receiver never sets it (it resumes its high-water from storage). */ needsResync?: boolean; } /** * The receive-side contract the {@link ChannelAcceptor} drives for a `.reliable()` stream — ordered dedup * + a cumulative high-water to ack. {@link ReliableInbox} implements it in-memory (session tier); the * `persisted` tier's SQL-backed `ReliableLog` implements the *same* shape so the acceptor can swap one for * the other per stream without any other change. See {@link ReliableInbox} for the three-case semantics. */ interface IReliableReceiver { /** Feed one reliable frame's `seq` + `payload`; get what to deliver now, the ack, and whether it was a dup. */ receive(streamId: string, seq: number, payload: T): IReliableInboxResult; /** * The sender abandoned every undelivered frame `<= seq` (an `rskip` control message): advance the * stream's high-water past them and drain anything buffered/stored behind the gap, so the stream * continues instead of waiting forever on frames that will never arrive. Returns what the drain * released (deliver in order) + the new cumulative ack. A backwards/stale skip is a no-op re-ack. */ skipTo(streamId: string, seq: number): IReliableInboxResult; /** The current contiguous high-water for a stream (`-1` if unseen) — used to piggyback an ack on a reply. */ contiguousSeq(streamId: string): number; /** Whether this receiver is tracking a stream (has accepted at least one reliable frame for it). */ hasStream(streamId: string): boolean; /** * Optional — release **all** state for a stream (high-water + buffered/stored frames): the sender * closed it for good (an `rclose`). Purely a reclaim; forgetting an unknown stream is a no-op, and a * later send on the released stream self-heals through the normal mid-stream re-sync path. */ forgetStream?(streamId: string): void; } interface IReliableInboxOptions { /** Max out-of-order frames buffered per stream before further gaps are dropped (resend heals). Default 1024. */ maxPendingPerStream?: number; } declare class ReliableInbox implements IReliableReceiver { private readonly _streams; private readonly _maxPending; constructor(options?: IReliableInboxOptions); private _stream; /** * Feed one reliable frame's `seq` (plus the caller's `payload` to dispatch) and get the decision: * what to deliver now, the ack to return, and whether it was a duplicate. See the class doc for the * three cases. */ receive(streamId: string, seq: number, payload: T): IReliableInboxResult; /** * Sender-abandoned skip (see {@link IReliableReceiver.skipTo}): advance `contiguousSeq` to at least * `seq` — the abandoned frames count as settled — then drain the buffered contiguous run that was * waiting behind the gap. Creates the stream when unseen (the sender is mid-stream; tracking it from the * skip point means the following frames arrive in-order instead of tripping the re-sync detection). */ skipTo(streamId: string, seq: number): IReliableInboxResult; /** The current contiguous high-water for a stream (`-1` if unseen) — used to piggyback an ack on a reply. */ contiguousSeq(streamId: string): number; /** Whether this inbox is tracking a stream (i.e. has seen at least one reliable frame for it). */ hasStream(streamId: string): boolean; /** Forget a stream's state (e.g. when its connection drops). */ forget(streamId: string): void; /** {@link IReliableReceiver.forgetStream} — same as {@link forget} (all session-tier state is in-memory). */ forgetStream(streamId: string): void; } //#endregion //#region src/wire/PeerLink/ReliableLog.d.ts /** * The **durable** tier's receive-side primitive — the persisted counterpart of {@link ReliableInbox}. It * implements the same {@link IReliableReceiver} contract (ordered dedup + a cumulative high-water to ack), * but every frame and the per-stream high-water live in a backing store instead of in-memory maps. Because * the store survives process eviction (a Durable Object waking from hibernation, a redeploy), a *fresh* * `ReliableLog` over the same store resumes each stream's high-water — so a replayed stream dedups instead * of redelivering, and a gap-free prefix can be served to a late joiner. That is the one guarantee the * session tier can't give (see {@link ReliableInbox}: it restarts at `contiguous = -1` on eviction). * * It is deliberately storage-agnostic: the algorithm here (contiguous advance, dedup by high-water) is the * same one {@link ReliableInbox} runs, lifted over an {@link IReliableLogStore} port. A Durable Object backs * that port with synchronous `ctx.storage.sql` (see the cloudflare platform helper); tests back it with an * in-memory map that persists across a simulated eviction. Payloads are (de)serialized through the * `serialize`/`deserialize` pair so the log can reconstruct a buffered out-of-order frame when its gap * fills — even after a wake. * * The store is assumed **synchronous** — true for a Durable Object's SQLite (`sql.exec` returns its cursor * synchronously), which keeps this on the same synchronous receive path as the in-memory inbox. */ /** The storage port a {@link ReliableLog} drives — a tiny synchronous key/value + high-water surface. */ interface IReliableLogStore { /** Store one frame's serialized payload keyed by `(stream, seq)`; a no-op if that pair already exists. */ insertIgnore(streamId: string, seq: number, payload: string): void; /** Whether a frame for `(stream, seq)` is stored. */ has(streamId: string, seq: number): boolean; /** The stored serialized payload for `(stream, seq)`, or `undefined` if absent. */ getPayload(streamId: string, seq: number): string | undefined; /** The persisted contiguous high-water for a stream (`-1` if the stream is unseen). */ getHighWater(streamId: string): number; /** Persist a stream's advanced contiguous high-water. */ setHighWater(streamId: string, seq: number): void; /** * Optional — delete every stored frame of a stream with `seq <= through`. Enables the log's * `keepDelivered` retention (compacting delivered history); a store without it simply keeps everything, * exactly as before the option existed. */ deleteThrough?(streamId: string, through: number): void; /** * Optional — delete **all** state for a stream: every stored frame *and* its high-water row. Enables * `forgetStream` (a sender's `rclose` reclaim); a store without it keeps the stream, exactly as before. */ deleteStream?(streamId: string): void; } interface IReliableLogOptions { /** Serialize a payload for storage (default `JSON.stringify`). */ serialize?: (payload: T) => string; /** Reconstruct a payload from storage (default `JSON.parse`) — used when a buffered gap frame drains. */ deserialize?: (raw: string) => T; /** * Max distance past the high-water an out-of-order frame may be **persisted** at (default 1024 — * mirroring the in-memory inbox's pending cap). A frame further out is not stored (the sender's ordered * resend heals the gap first), bounding what one client can force into storage. `Infinity` disables. */ maxGapWindow?: number; /** * Retention: how many **delivered** frames to keep behind the high-water. Default `false` = keep * everything (the `contiguousPrefix()` replay recipe needs full history). Set a number to compact — * frames `<= highWater - keepDelivered` are deleted as the high-water advances (needs a store with * `deleteThrough`; silently keeps everything otherwise). `0` keeps only undelivered/pending frames. */ keepDelivered?: number | false; } /** One stored frame of a stream, as {@link ReliableLog.contiguousEntries} returns it. */ interface IReliableLogEntry { seq: number; payload: T; } declare class ReliableLog implements IReliableReceiver { private readonly _store; private readonly _serialize; private readonly _deserialize; private readonly _maxGapWindow; private readonly _keepDelivered; constructor(store: IReliableLogStore, options?: IReliableLogOptions); /** Compact delivered history behind the advanced high-water, when retention is configured. */ private _compact; /** * Feed one reliable frame. Same three cases as {@link ReliableInbox}, but the frame is persisted first * (idempotent `insertIgnore`, so a resend is stored once) and the high-water is read from / written to * the store — so the decision is stable across an eviction: * - **duplicate** (`seq <= high-water`): dropped from dispatch, re-ack the persisted high-water; * - **in-order** (`seq === high-water + 1`): deliver it, then drain any persisted contiguous run behind it; * - **gap** (`seq > high-water + 1`): persist the frame and ack the current high-water (client resends the gap). */ receive(streamId: string, seq: number, payload: T): IReliableInboxResult; /** * Sender-abandoned skip (see {@link IReliableReceiver.skipTo}): persist the high-water at least past * `seq`, then drain any *stored* contiguous run that was waiting behind the gap. Stored frames `<= seq` * that were never delivered stay below the high-water (settled-as-abandoned, never drained) — the skip * marks them settled without delivering them, mirroring the in-memory inbox. */ skipTo(streamId: string, seq: number): IReliableInboxResult; contiguousSeq(streamId: string): number; hasStream(streamId: string): boolean; /** * {@link IReliableReceiver.forgetStream}: release the stream's rows + high-water (a sender's `rclose` * reclaim). Needs a store with `deleteStream`; without one the stream is kept, exactly as before. */ forgetStream(streamId: string): void; /** * **Producer-side** append: store `payload` as the next in-order frame of a stream and return its * assigned `seq`. This is the offline/reliable-push recipe's write path — a server appending its own * pushes to a per-client log (carrying the returned `seq` in the push payload so the client can dedup) * — replacing the `log.receive(id, log.contiguousSeq(id) + 1, u)` contortion. In-order by * construction, so it never buffers; if live out-of-order frames were already stored *ahead* of the * high-water, filling the gap drains them (high-water advances past the run), exactly as `receive`. */ append(streamId: string, payload: T): { seq: number; }; /** * The gap-free prefix of a stream — every contiguous payload `0..high-water` in order. This is the * safe-to-replay catch-up a late joiner (or a reconnecting client that lost its own state) can be sent, * and the building block the offline server→client push recipe (Phase 6) is assembled from. */ contiguousPrefix(streamId: string): T[]; /** * {@link contiguousPrefix} with each payload's `seq` attached, optionally only the entries after * `afterSeq`. Pruned or compacted seqs are absent, so the first entry's `seq` says where the stored * history now starts. */ contiguousEntries(streamId: string, afterSeq?: number): IReliableLogEntry[]; /** * Delete a stream's stored frames with `seq <= through` (the replay recipe's prune, once the consumer * confirmed them). Clamped to the high-water, so a too-large `through` never touches undelivered frames. * Returns `false` when the store has no `deleteThrough` and nothing was pruned. */ pruneThrough(streamId: string, through: number): boolean; } /** * An in-memory {@link IReliableLogStore} — used by tests to stand in for a Durable Object's SQL storage. It * persists in its own maps, so building a *new* {@link ReliableLog} over the same store instance models an * eviction (the process-side log is gone, the storage survives). Not for production — a real deployment * backs the port with durable storage (e.g. `ctx.storage.sql`). */ declare function createMemoryReliableLogStore(): IReliableLogStore; //#endregion //#region ../connect-core/build/index-BjOE7ujh.d.mts //#region src/wire/Connect/TransportConnection.d.ts /** * The stateless definition a live {@link TransportConnection} points back at — used for devtools * route info. nice-action's `Transport` definition class satisfies this structurally; wire never * needs the definition's construction side (building connections binds lane resolvers, which is * the protocol module's job). */ interface IWireTransportDefinition { getRouteInfo(input: RP): IWireRouteInfo | undefined; } /** * Live, per-handler transport runtime built from a reusable transport definition. Holds the * connection-scoped state (ordinal, initialized config, sockets / abort sets) that must not be shared * across handlers. Moved from nice-action with the action types * inverted into generics: `RP` (per-dispatch routing params), `RD` (the raw ready-data a definition * yields), and `METHODS` (the finalized send surface subclasses build) are opaque to wire. */ declare abstract class TransportConnection = IWireTransportInitialized, DEF extends IWireTransportDef = IWireTransportDef> { readonly def: DEF; readonly transOrd: number; readonly type: T; readonly initialized: I; /** Backref to the public definition that created this connection (used for devtools route info). */ definition?: IWireTransportDefinition; constructor(def: DEF); /** * Devtools route info for a dispatch routed through this live connection. Defaults to the stateless * {@link definition}'s info; connections override to enrich it from live state (e.g. the actual * resolved socket URL) when the definition couldn't resolve it on its own. */ getRouteInfo(input: RP): IWireRouteInfo | undefined; /** * Build the live send/receive methods from a `ready` readyData, synchronously. This is the plain * (no-handshake) path and the only required per-transport hook. Stream carriers that must await the * carrier opening and/or run a handshake additionally override {@link _needsAsyncBringUp}, * {@link _awaitCarrierReady}, and {@link _finalizeReady}. */ protected abstract _finalizeTransportMethods(inputs: RD): METHODS; /** * Whether a `ready`-status transport still needs asynchronous bring-up before its methods exist — * awaiting the carrier to open and/or running a handshake. Default `false`: a stateless transport * (HTTP) is usable the instant `getTransport` reports `ready`, so it stays a terminal *synchronous* * fallback in the selection manager. Stream carriers (Link/WS) override to `true`. */ protected _needsAsyncBringUp(_readyData: RD): boolean; /** Await the carrier becoming ready to send (e.g. a socket `open`). Default: nothing to await. */ protected _awaitCarrierReady(_readyData: RD): Promise; /** * Finalize during async bring-up — may run a handshake, so it can be async. Defaults to the * synchronous {@link _finalizeTransportMethods}; secure stream carriers override to branch plain/secure. */ protected _finalizeReady(readyData: RD): METHODS | Promise; protected _getCacheKey(input: RP): string | null; getCacheKey(input: RP): string | null; /** * Whether this transport can serve the given dispatch right now. Consulted by the manager before * cache-key resolution and `getTransport`; a `false` result skips this transport (treated as * `unsupported`) and the manager falls through to the next in preference order. Defaults to `true` * when the transport declares no gate. */ isAvailable(input: RP): boolean; getTransport(input: RP): TTransportStatusInfo; protected _processTransportStatus(input: RP): TTransportStatusInfo; /** Await carrier readiness, then finalize (possibly running a handshake) into the live methods. */ private _bringUp; } /** Stamp the wall-clock metadata a definition's raw status output omits. */ declare function addTransportStatusMetadata(transportStatus: TTransportStatusInfo_GetTransport_Output): TTransportStatusInfo; //#endregion //#region src/wire/Connect/transportRuntime.types.d.ts /** * The generic transport-runtime model — the status machine, * definition shapes, and cache types the selection layer (`ConnectionTransportManager`) and the * per-connection base class (`TransportConnection`) run on. Moved from nice-action's * `Transport.types.ts` with the action typing inverted into generics: `RP` (the per-dispatch * routing params — nice-action instantiates it with its action route params) and `METHODS` (the * finalized send surface — nice-action's `sendActionData` family) are opaque here; wire only * relies on the tiny {@link IWireConnectionMethodsBase} lifecycle sliver. */ /** * Carrier-shape class identity: the one carrier-invariant trait the selection layer reasons about — * whether a carrier can push unsolicited frames (`duplex`: WS/WebRTC/BLE/in-memory) or only answers a * request with a single correlated reply (`exchange`: HTTP). The concrete carrier kind ("ws", "webrtc", * "http", …) is a free-form route-info `carrierLabel` for display, not a class tag. */ declare enum ETransportShape { duplex = "duplex", exchange = "exchange" } /** * * TRANSPORT READINESS * */ declare enum ETransportStatus { uninitialized = "uninitialized", unsupported = "unsupported", initializing = "initializing", ready = "ready", failed = "failed" } interface ITransportStatusInfo_Base { status: S; } interface ITransportStatusInfo_Failed extends ITransportStatusInfo_Base { error: NiceError; timeFailed: number; } interface ITransportStatusInfo_Unsupported extends ITransportStatusInfo_Base {} interface ITransportStatusInfo_Ready extends ITransportStatusInfo_Base { readyData: READY; } type TTransportInitializationFinishedInfo = ITransportStatusInfo_Ready | ITransportStatusInfo_Failed | ITransportStatusInfo_Unsupported; interface ITransportStatusInfo_Initializing extends ITransportStatusInfo_Base { timeStarted: number; initializationPromise: Promise>; } type TTransportStatusInfo = ITransportStatusInfo_Base | ITransportStatusInfo_Unsupported | ITransportStatusInfo_Initializing | ITransportStatusInfo_Ready | ITransportStatusInfo_Failed; type TTransportStatusInfo_GetTransport_Output = ITransportStatusInfo_Base | ITransportStatusInfo_Unsupported | Omit, "timeStarted"> | ITransportStatusInfo_Ready | Omit; /** * * TRANSPORT DEFINITIONS * */ /** The initialized (per-connection) half of a transport definition — hooks over opaque `IN`. */ interface IWireTransportInitialized { /** Keys identifying a reusable connection, so one carrier is shared across dispatches to the same peer. */ getCacheKey?: (input: IN) => string[]; /** * Optional availability gate, consulted *before* cache-key resolution and `getTransport`. When it * returns `false`, this transport is treated as `unsupported` for that dispatch and the manager falls * through to the next transport in preference order — without opening the carrier or computing its * cache key. Re-evaluated per dispatch. Omit = always available. */ isAvailable?: (input: IN) => boolean; getTransport: (input: IN) => TTransportStatusInfo_GetTransport_Output; } interface IWireTransportDef> { type: TYPE; initialize: () => INIT; } /** * The lifecycle sliver of a transport's finalized methods that wire's selection layer relies on — * everything else on the methods object (nice-action's send surface) is opaque `METHODS`. */ interface IWireConnectionMethodsBase { addOnDisconnectListener?: (callback: () => void) => void; /** Close a long-lived connection deliberately, so teardown releases the socket (not GC). */ disconnect?: () => void; /** * Called (idempotently) each time selection picks this connection. A link that defers its * frame-protocol mux attaches it here, so a warm-up that loses selection never carries protocols. */ onSelected?: () => void; } /** A selected, ready transport: its finalized methods + the live connection that produced them. */ interface IWireTransportReady { methods: METHODS; transport: CONN; } type TTransportCache = Map | Promise>>; /** The connection type the manager traffics in, spelled once. */ type TWireManagedConnection = TransportConnection; //#endregion //#region src/wire/Carrier/AcceptorCarrier.d.ts /** Neutral lifecycle surface driven by any duplex server transport. */ interface IDuplexConnectionRouter { receive(connection: TConn, frame: TFrame$1): void; drop(connection: TConn): void; } /** Optional persisted attachment access for hibernatable connections. */ interface IAcceptorAttachmentStore { getConnections: () => TConn[]; read: (connection: TConn) => unknown; write: (connection: TConn, value: unknown) => void; } interface IDuplexCarrierLifecycle { receive(connection: TConn, frame: TFrame$1): void; drop(connection: TConn): void; /** @internal Activated by a serving host. */ _activate(router: IDuplexConnectionRouter): void; /** @internal Permanently release lifecycle bookkeeping. */ _dispose?(): void; } type TInboundFrameLimitReason = "frame_bytes" | "message_rate"; interface IInboundFrameLimits { maxFrameBytes?: number; rate?: { maxMessages: number; windowMs: number; }; onExceeded: (connection: TConn, reason: TInboundFrameLimitReason) => void; } /** Build the inert lifecycle slot shared by duplex acceptor carrier factories. */ declare function createDuplexCarrierLifecycle(limits?: IInboundFrameLimits): IDuplexCarrierLifecycle; /** A persistent, push-capable carrier served by a `WireAcceptor`. */ interface IDuplexAcceptorCarrier extends IDuplexCarrierLifecycle { readonly shape: ETransportShape.duplex; secure?: boolean; send: (connection: TConn, frame: TFrame$1) => void; /** Close a live connection; the server uses it to end a connection whose handshake it refused. */ close?: (connection: TConn) => void; upgrade?: (request: Request, url: URL) => Response | Promise; isUpgrade?: (request: Request, url: URL) => boolean; attachmentStore?: IAcceptorAttachmentStore; readonly carrierLabel: string; } interface IWsAcceptorCarrierOptions { secure?: boolean; send: (connection: TConn, frame: TFrame$1) => void; /** Close a live connection (e.g. `(ws) => ws.close(1008)`), used after a refused handshake. */ close?: (connection: TConn) => void; upgrade?: (request: Request, url: URL) => Response | Promise; isUpgrade?: (request: Request, url: URL) => boolean; attachmentStore?: IAcceptorAttachmentStore; carrierLabel?: string; inboundLimits?: IInboundFrameLimits; } /** Build a WebSocket acceptor carrier for `serveWire` or `serveChannel`. */ declare function wsAcceptorCarrier(options: IWsAcceptorCarrierOptions): IDuplexAcceptorCarrier; //#endregion //#region src/wire/Carrier/duplex/inMemory/createInMemoryChannel.d.ts type TFrame = string | ArrayBuffer | Uint8Array; /** The peer (server) end of an in-memory pair — what you feed into an `ChannelAcceptor`. */ interface IInMemoryServerEndpoint { /** Write a frame back to the client end. */ send(frame: TFrame): void; /** Register the inbound handler (frames the client sent). */ onMessage(handler: (frame: TFrame) => void): void; /** Close the pair from this end. */ close(): void; /** Notified when the pair closes (from either end). */ onClose(handler: () => void): void; } interface IInMemoryChannelPair { /** The client end — pass as a {@link IDuplexCarrier} to a `LinkTransport`. */ clientChannel: IDuplexCarrier; /** The server end — wire into an `ChannelAcceptor` (`send` + `receive`). */ serverEndpoint: IInMemoryServerEndpoint; } /** * Two cross-wired in-process byte channels — a loopback carrier with no socket. The client end is a * {@link IDuplexCarrier} you hand to a {@link LinkTransport}; the server end plugs into an * `ChannelAcceptor` (`send: (_, f) => serverEndpoint.send(f)`, and `serverEndpoint.onMessage(f => * handler.receive(conn, f))`). Frames are delivered on a microtask, so each side observes the other * asynchronously — exactly like a real transport — which makes this ideal for tests and for running * two runtimes in one process (or proving a non-WS carrier end to end). */ declare function createInMemoryChannelPair(): IInMemoryChannelPair; //#endregion //#region src/wire/Carrier/duplex/inMemory/inMemoryCarrier.d.ts interface IWireInMemoryCarrier { /** The connector end — pass as a `WireClient`/connector transport's carrier. */ carrier: IWireDuplexCarrierSource; /** The acceptor end — wire into the accepting handler (`send` + `receive`). */ serverEndpoint: IInMemoryServerEndpoint; } /** * A loopback duplex carrier with no socket — two cross-wired in-process ends. Ideal for tests and * for running two runtimes in one process, or proving a non-WS carrier end to end. The dial * context is ignored (the pair is pre-wired), so `TDial` is purely for slot compatibility. */ declare function inMemoryCarrier(options?: { secure?: boolean; }): IWireInMemoryCarrier; //#endregion //#region src/wire/Carrier/duplex/rtc/rtcDataChannelByteChannel.d.ts /** * The slice of the `RTCDataChannel` surface this adapter uses — declared structurally so it accepts the * browser `RTCDataChannel`, React-Native (`react-native-webrtc`), or any node-webrtc shim without a hard * dependency on a specific DOM/RN type. A real `RTCDataChannel` satisfies it as-is. */ interface IRtcDataChannelLike { readyState: string; binaryType: string; label?: string; send(data: string | ArrayBuffer | ArrayBufferView): void; close(): void; addEventListener(type: string, listener: (event: any) => void, options?: unknown): void; } /** * Adapt a WebRTC `RTCDataChannel` to the carrier-agnostic {@link IDuplexCarrier}, so two browsers * (or two mobile apps) linked peer-to-peer — no server in the middle — run the *same* secure session as * a WebSocket. Hand it to `createSecureLinkTransport({ openChannel: () => rtcDataChannelByteChannel(dc) })`. * * The data channel must already be created (its negotiation/signaling is the app's concern); this only * drives bytes over it. Binary frames are requested as `ArrayBuffer` so the binary session codec unpacks * them synchronously; a `Blob` (if the channel hands one back) is normalized to a buffer. */ declare function rtcDataChannelByteChannel(dc: IRtcDataChannelLike): IDuplexCarrier; //#endregion //#region src/wire/Carrier/duplex/rtc/rtcCarrier.d.ts interface IRtcCarrierOptions { secure?: boolean; getCacheKey?: (params: IWireDialParams) => string[]; getRouteInfo?: (params: IWireDialParams) => IWireRouteInfo; } /** * A WebRTC {@link IWireDuplexCarrierSource} over an already-negotiated `RTCDataChannel` (signaling * is the app's concern), generalized over the opaque dial context (E2). Two browsers/apps linked * peer-to-peer run the identical secure session as a WebSocket. */ declare function rtcCarrier(dataChannel: IRtcDataChannelLike, options?: IRtcCarrierOptions): IWireDuplexCarrierSource; //#endregion //#region src/wire/Carrier/duplex/ws/webSocketByteChannel.d.ts /** * Adapt a `WebSocket` to the carrier-agnostic {@link IDuplexCarrier}, so the WebSocket becomes * "just another carrier" under the shared secure session. It owns every WebSocket-specific concern — * awaiting `open`, normalizing `Blob` frames to bytes, suppressing the log on a deliberate `close`, and * buffering any frame that arrives before the session attaches its handler — leaving the session itself * carrier-neutral. */ declare function webSocketByteChannel(ws: WebSocket): IDuplexCarrier; //#endregion //#region src/wire/Carrier/duplex/ws/ws_util.d.ts /** * Send a text or binary frame over a socket. A binary formatter may hand back a `Uint8Array` whose * backing buffer is typed as `ArrayBufferLike` (msgpackr pools buffers / may be `SharedArrayBuffer`), * which `WebSocket.send`'s `BufferSource` parameter rejects — copy it into a fresh `ArrayBuffer`-backed * view so the type (and the bytes) are safe to send. */ declare function sendFrame(ws: WebSocket, data: string | Uint8Array | ArrayBuffer): void; /** Compact a WebSocket URL to `host/pathname` for devtools display, falling back to the raw url. */ declare function shortWs(url: string): string; //#endregion //#region src/wire/Carrier/duplex/ws/wsCarrier.d.ts /** The WebSocket a dial is opened against (derived per dial from the params + dial context). */ interface IWsCarrierRequest { url: string; } interface IWsCarrierOptions { /** Run this carrier plainly when used by a high-level client. Defaults to secure. */ secure?: boolean; /** Override the reuse key (defaults to `[url]`, so one socket is shared per endpoint). */ getCacheKey?: (params: IWireDialParams) => string[]; /** Override the devtools route info for a specific dial. */ getRouteInfo?: (params: IWireDialParams) => IWireRouteInfo; /** * Construct the socket for a dial — the **testability seam**: inject a * controllable/instrumented socket to simulate outage, latency, or drops without touching * globals. Crucially, this gates **every** dial including keep-alive redials — which page-level * `window.WebSocket` patching cannot. Must return a socket in CONNECTING state; the carrier sets * `binaryType` itself. Production dials should not need this. */ createWebSocket?: (url: string) => WebSocket; } /** * A WebSocket {@link IWireDuplexCarrierSource}: opens an `arraybuffer` socket (cached per endpoint) * and adapts it to a carrier — generalized over an opaque dial context (shared connection design, * E2), so the URL can be derived from whatever domain concept the consumer threads through * (nice-action passes the action being dispatched; a realm-only client passes e.g. a game id). * * `createRequest` derives the socket URL per dial (keep it simple with `() => ({ url })`), so * dynamic endpoints need no socket-construction hook for the URL. `createWebSocket` exists for * **testability** — injecting a controllable socket (it is not a URL mechanism). * * `createRequest` may return **`null`** to mean "no valid endpoint right now" — a dynamic-endpoint * carrier whose mutable dial context was torn down (`matchId` cleared) * signals that instead of dialing garbage. The dial throws `dial_unavailable`, which a keep-alive * redial loop parks on (resuming at the next explicit `connect()`/dispatch) — so teardown ordering * stops mattering. */ declare function wsCarrier(request: string | ((params: IWireDialParams) => IWsCarrierRequest | string | null), options?: IWsCarrierOptions): IWireDuplexCarrierSource; //#endregion //#region src/wire/Carrier/exchange/http/httpCarrier.d.ts /** The HTTP request a dial is sent over (the body is supplied by the secure exchange session). */ interface IHttpCarrierRequest { url: string; headers?: Record; } /** The slice of `fetch` the carrier uses — a structural type so callers (and tests) needn't match the * full platform `fetch` (Bun's adds `preconnect`, etc.). The global `fetch` satisfies it. */ type TCarrierFetch = (input: string, init?: RequestInit) => Promise; interface IHttpCarrierOptions { /** Run this carrier plainly when used by a high-level client. Defaults to secure. */ secure?: boolean; /** Override the reuse key (defaults to `[url]`, so one session is shared per endpoint). */ getCacheKey?: (params: IWireDialParams) => string[]; /** Override the devtools route info for a specific dial. */ getRouteInfo?: (params: IWireDialParams) => IWireRouteInfo; /** Override `fetch` (e.g. to route to an in-memory handler in tests). Defaults to global `fetch`. */ fetch?: TCarrierFetch; } /** * An HTTP {@link IWireExchangeCarrierSource}: each `exchange` POSTs one frame body to the endpoint * and resolves with the response body as the single correlated reply — generalized over the opaque * dial context (E2). A secure HTTP transport runs the *same* secure session as a duplex carrier * (handshake → token → encrypted frames), the request/reply correlation provided for free by the * HTTP transaction. * * `createRequest` derives the URL/headers per dial (keep it simple with `() => ({ url })`). The * body is the session's responsibility, so it is never built here. */ declare function httpCarrier(request: string | ((params: IWireDialParams) => IHttpCarrierRequest | string | null), options?: IHttpCarrierOptions): IWireExchangeCarrierSource; //#endregion //#region src/wire/Connect/sanitizeEndpoint.d.ts /** * A destination safe to put in diagnostics. Credentials, query parameters, and fragments can carry * secrets (capability tokens, signed leases), so only the scheme, host, port, and path survive. */ declare function sanitizeEndpoint(raw: string | undefined): string | undefined; //#endregion //#region src/wire/Connect/endpointEvidence.d.ts /** * What a failed dial actually *was* — the typed discriminator a consumer branches on instead of * matching error text (meteor-connect-bridge feedback W3). The values are distinct because each * one implies a different next step for the developer: * * - {@link endpoint_answered_non_protocol} — fix the URL, or the proxy/WAF in front of it. * - {@link endpoint_unreachable} — no response was received: check the network, the server, and * (in a browser) CORS or a refused WebSocket upgrade, which the platform reports the same way. * - {@link handshake_rejected} — it *is* a nice-code backend and it said no (e.g. a pinned * identity): fix the identity or the version, not the address. * - {@link protocol_version_mismatch} — the peer explicitly reported no compatible secure-wire * generation; upgrade or roll back one side, then retry explicitly. */ declare enum EWireConnectFailureKind { endpoint_answered_non_protocol = "endpoint_answered_non_protocol", endpoint_unreachable = "endpoint_unreachable", handshake_rejected = "handshake_rejected", protocol_version_mismatch = "protocol_version_mismatch", peer_identity_mismatch = "peer_identity_mismatch", unknown = "unknown" } /** * A bounded, single-line, control-character-free head of whatever a non-protocol endpoint sent * back — enough to recognize an HTML error page or a proxy banner on sight. Only the *response* is * ever summarized: no request headers, no request body. */ declare function describeNonProtocolBody(raw: unknown): string | undefined; /** * Classify a dial failure. Reads typed ids only — the ids are raised at the layer that still holds * the evidence precisely so this never has to sniff message text. */ declare function classifyConnectFailure(error: unknown): EWireConnectFailureKind; /** The endpoint a failure names, when it carries one — the URL actually dialed, sanitized. */ declare function endpointFromConnectFailure(error: unknown): string | undefined; //#endregion //#region src/wire/Connect/ConnectionTransportManager.d.ts /** * Everything known about why a dial chain came up empty — enough for the thrown error to be * self-locating (feedback W2: *which* endpoint) and branchable (W3: *what kind* of failure) * without anyone parsing a message. */ interface IWireTransportInitializationFailure { /** The most relevant underlying failure, as text for the message. */ cause?: string; /** The endpoint that failed — the URL the carrier actually dialed, when one is known. */ endpoint?: string; /** Answered-wrongly vs unreachable vs rejected — the discriminator consumers branch on. */ kind: EWireConnectFailureKind; /** The underlying error, attached as the origin so the full chain survives. */ origin: unknown; } /** * The selection-failure vocabulary, injected by the consumer so its errors keep their native * domain/ids (nice-action supplies `err_nice_transport` factories — its tests and consumers see * the exact same errors as before the move). */ interface IWireTransportSelectionErrors { /** Transport(s) found but every one reported unsupported/unavailable for this dispatch. */ unsupported(transportShapes: ETransportShape[]): Error; /** No transports produced a candidate at all. */ notFound(input: RP): Error; /** Every candidate failed to initialize; see {@link IWireTransportInitializationFailure}. */ initializationFailed(input: RP, failure: IWireTransportInitializationFailure): Error; } /** * Preference-ordered transport selection over a shared connection cache — moved from nice-action * with the routing params (`RP`), finalized methods * (`METHODS`), and connection type (`CONN`) generic. Behavior is byte-for-byte the pre-move * logic: strict preference order with parallel warm-up, cache adoption guarded against teardown * races, and disconnect-driven eviction. */ declare class ConnectionTransportManager = TWireManagedConnection> { private _cache; private readonly _errors; private _transports; constructor(_cache: TTransportCache, _errors: IWireTransportSelectionErrors); addTransport(transport: CONN): void; /** * The highest-priority transport (first declared). Used to label a dispatch's route *before* the * transport has finished connecting — so a still-connecting dispatch shows its (expected) * destination instead of an "unknown" hop. {@link getReadyTransport} still decides the real winner, * and the caller corrects the hop if a lower-priority transport ends up serving it. */ getPreferredTransport(): CONN | undefined; getReadyTransport(input: RP): Promise>; /** * Close the parallel warm-ups this selection started besides `failed`. Each one's cache slot is * released so a later dispatch re-dials; a warm-up still connecting closes itself when it lands. */ private _abandonWarmUps; /** Attach the sanitized dialed endpoint to a peer-identity mismatch that lacks one. */ private _withDialedEndpoint; } //#endregion //#region src/wire/Connect/connectionBinding.d.ts /** * Readers for the persisted {@link IWireConnectionBinding}: the *only* supported way * for anything outside wire to read identity back off a persisted connection attachment. Before * these existed every consumer hand-rolled `attachment?.binding?.client?.perId` against what was * action's private persistence format — untyped, and silently broken by any shape change. These * readers own the shape knowledge (including the composite `{ app?, binding? }` attachment layout * the serve layer writes) and validate the schema version, so a shape change shows up here, once. */ /** Whether a persisted value is a current-schema (`v: 1`) wire connection binding. */ declare function isWireConnectionBinding(value: unknown): value is IWireConnectionBinding; /** * Read the wire binding out of a persisted connection attachment. Accepts either the bare binding * (a host that persists it directly) or the composite `{ app?, binding? }` slot the serve layer * co-stores app state in. `undefined` for anything else — including bindings of an unknown schema * version (the socket should be treated as fresh, exactly like `WireAcceptor.rehydrate`). */ declare function wireBindingFromAttachment(attachment: unknown): IWireConnectionBinding | undefined; /** * The authenticated client coordinate persisted on a connection's attachment — * `undefined` when the attachment carries no readable binding. This is what a protocol module's * server half (e.g. realm's `resolveClient` default) reads instead of reaching into the raw * attachment shape. */ declare function clientCoordinateFromAttachment(attachment: unknown): RuntimeCoordinate | undefined; /** * The negotiated wire security level persisted on a connection's attachment — the twin of * {@link clientCoordinateFromAttachment}, reading the level a protocol module (e.g. realm's attach * gate) needs to enforce a minimum **after a hibernation wake**, where the socket re-hellos with no * fresh handshake and the persisted binding is the only source of truth. * * Two distinct "absent" cases the caller must handle: * - **`undefined`** — no readable binding at all (a fresh/unbound socket, or an unknown-schema * binding). Read this as "unknown" and fail closed (treat as `none`); it also means * {@link clientCoordinateFromAttachment} yields no identity, so such a socket never attaches. * - **`ESecurityLevel.none`** — a *readable* binding for a genuinely plain (unhandshaked) * connection (no `secure` block). Realm traffic never reaches here on such a connection (the * wire security gate drops protocol frames on `none` links), but the value is reported honestly. */ declare function securityLevelFromAttachment(attachment: unknown): ESecurityLevel | undefined; //#endregion //#region src/wire/Connect/WireClient.d.ts interface IWireClientOptions> { /** * Build the selection manager over the client-owned cache. Injected so the consumer's manager * (nice-action's `ConnectionTransportManager` shim, which carries its error vocabulary) is the * one that runs — wire owns the cache + lifecycle, the consumer owns the failure language. */ createManager: (cache: TTransportCache) => ConnectionTransportManager; /** * The frame-protocol mux riding this client's connections. The client *holds* it (one mux per * client — protocol modules reach it here). Its registered-protocol count is also the auto * keep-alive signal (a protocol-carrying link is kept alive; a lane-only one stays * dispatch-driven). */ mux?: WireProtocolMux; /** The peer this client dials — its `externalClient` in every dial input. */ peer: RuntimeCoordinate; /** * The local runtime coordinate this connection dials out from — its authenticated identity to the * peer, and what `connect()` uses when no override is passed. A protocol module (a realm client) * also defaults its own identity from it. */ localCoordinate?: RuntimeCoordinate; /** * The negotiated wire security level this connection's frame protocols (a realm) ride at. A realm * client reads it and refuses to send below its required minimum. Defaults to * {@link ESecurityLevel.none} (a bare-mux / loopback build). */ securityLevel?: ESecurityLevel; /** * Whether any transport in this client's chain is push-capable (duplex). Computed by the caller * from its transport list. Keep-alive requires it — an exchange-only client can never be redialed * into a live link the peer can push over. */ canPush: boolean; /** * Keep a **protocol-carrying** duplex link alive by auto-redialing it on an unexpected drop, with * exponential backoff + jitter. `undefined` (default) = auto: on when the * mux carries a registered protocol, off otherwise (a lane-only connection keeps dispatch-driven * reconnect). `false` opts out; `true` forces it on for any duplex link. An explicit * `clearTransportCache()`/`dispose()` always stops it. */ /** @deprecated Use `reconnect`. */ keepLinkAlive?: boolean; reconnect?: boolean; /** * Build an **actionless** dial input from the client pair. Wire holds the pair (this client's * coordinate + its peer) but the routing-param shape is the consumer's (`RP`), so the consumer * maps the pair onto it — nice-action's lane returns the pair itself (a valid actionless route * param), a bare-mux build returns the pair too. Used by `connect()`/`reconnectLink()`. */ buildConnectInput: (pair: IWireClientPair) => RP; /** * A last-resort local coordinate when none was configured — nice-action supplies * `() => ActionRuntime.getDefault().coordinate` so its dispatch-driven default holds; a pure wire * client omits it (a configured `localCoordinate` is then required to `connect()`). */ defaultLocalCoordinate?: () => RuntimeCoordinate | undefined; } /** * The dial-out connection: owns the transport cache, preference-ordered selection, the protocol mux, * and the whole **connection lifecycle** — establishment bookkeeping, the keep-alive redial ladder * (backoff + jitter + park), link-state events, and the teardown verbs. A protocol module (a realm * client, via `realmConnection`) rides it structurally through `wireMux` + `localCoordinate` + * `securityLevel` + `requestReconnect` + `addLinkEventListener`; a lane (nice-action's * `ChannelConnector`) composes routing/reliability on top and delegates every lifecycle verb here. * `createWireClient` (the public facade) wraps one of these with the status model + DX. */ declare class WireClient = TWireManagedConnection> { readonly mux?: WireProtocolMux; /** The peer this connection dials — `externalClient` for its dials, and the realm's devtools peer. */ readonly peer: RuntimeCoordinate; /** This connection's local dial identity (see options). */ readonly localCoordinate?: RuntimeCoordinate; /** The negotiated wire security level frame protocols ride at (realm reads it via `realmConnection`). */ readonly securityLevel: ESecurityLevel; /** Whether this connection can carry an unsolicited push (any duplex transport). */ readonly canPush: boolean; private readonly _cache; private readonly _manager; private readonly _buildConnectInput; private readonly _defaultLocalCoordinate?; private readonly _linkEventListeners; /** When the current outage began (the `link_down` instant); `undefined` while up / never dialed. */ private _downSince?; /** * The methods of the *current* link — dedups `link_up` (every dispatch re-runs * `_onLinkEstablished` with the cached connection) and lets a stale connection's late close be * ignored (a slow socket close arriving after the replacement link is already up must not read * as an outage). */ private _currentLinkMethods?; /** * App-initiated teardown latch: `releaseLink()` / `clearTransportCache()` / `dispose()` are * intentional releases, NOT outages — so a **late** carrier close from the released socket must * emit no `link_down`. Set by those teardowns, cleared by the next `_onLinkEstablished` (a fresh * link means we're back). `debug.dropLink` deliberately does NOT set it — a dropped link IS an * outage, and it emits `link_down` at close. */ private _tornDown; /** Explicit opt-out; `undefined` = auto (on for a protocol-carrying duplex link). */ private readonly _reconnectOption?; /** Connections we've hooked a reconnect listener onto (once per connection). */ private readonly _reconnectHooked; private _redialTimer?; private _redialAttempts; /** Set by an explicit teardown so the resulting disconnect doesn't auto-redial; cleared on a fresh establish. */ private _suppressRedial; /** Timer ending a `debug.dropLink` suppression window. */ private _debugResumeTimer?; private _disposed; /** * Chaos/QA surface — stable API, but never for production control flow. * The "simulate airplane mode" button: manual QA and consumer resilience tests use it to force * the outages that page-level interception can't (the keep-alive redial heals straight through * a `window.WebSocket` patch). */ readonly debug: { /** * Force-close the live duplex link — a *real* close (the server observes it), unlike a * browser's offline mode which leaves the socket half-open — and optionally suppress the * keep-alive auto-redial for a window, simulating a sustained outage. * * - `suppressRedialMs` omitted/`0`: drop only — keep-alive (when active) heals on its * ordinary backoff ladder (first rung ~1 s), so a bare `dropLink({})` is a faithful * *fast-blip* simulator: the local close notifies the session immediately, it does NOT wait * for the carrier's platform close event. * - `suppressRedialMs > 0`: no auto-redial until the window ends, then the backoff loop * resumes. A second `dropLink` during a window replaces it; an explicit `connect()` / * dispatch / `reconnectLink()` during the window ends it early (fresh establishment always * re-enables keep-alive); `dispose()` wins over a pending resume. * * `link_down` fires **now, at close** — synchronously, before the socket teardown — so the * observation is truthful regardless of how long the underlying carrier takes to deliver its * own close callback (a real WebSocket's `onclose` can lag the outage by seconds; the * suppression window suppresses only the *redial*, never the *observation of the drop*). The * heal is equally decoupled: a deliberate local close notifies the session's disconnect * fan-out immediately (the auto-redial trigger), and the carrier's eventual platform close is * deduped by the `_downSince` guard — so exactly one `link_down` is emitted, `link_up.downForMs` * measures the full outage, and the redial does not wait out the platform's close lag. * * Resolves once the local teardown ran (in-flight dials are disconnected as they land). */ dropLink: (opts?: { suppressRedialMs?: number; }) => Promise; }; constructor(options: IWireClientOptions); /** Register one live connection, in preference order (first added = preferred). */ addTransport(connection: CONN): void; /** The highest-priority transport (first declared) — see the manager's doc. */ getPreferredTransport(): CONN | undefined; /** * Select (establishing if needed) the transport that should carry this dispatch, and run the * link-establishment bookkeeping as a side effect — so *any* caller (a lane dispatch or this * client's own `connect()`) re-enables keep-alive, resets the backoff ladder, and emits `link_up` * on a genuinely new link, without having to orchestrate it. Idempotent per link * (`_onLinkEstablished` dedups on identity). */ getReadyTransport(input: RP): Promise>; /** * The frame-protocol mux riding this connection's link — protocol modules (a realm client) * register here. Register protocols *before* {@link connect} / the first dispatch so the * handshake advertises them. */ get wireMux(): WireProtocolMux | undefined; /** @deprecated Use {@link peer}. */ get peerClient(): RuntimeCoordinate; /** * The re-dial hook a realm client rides: * `realmConnection(client)` reads it and hands it to the realm engine as the connection * adapter's `requestReconnect`, invoked on an unanswered staleness probe. A bound closure, so it * survives being detached from `this` (the realm stores the reference and calls it later). */ get requestReconnect(): () => void; /** Keep-alive is active for a protocol-carrying duplex link (a realm) unless opted out (Phase 8b). */ private get _shouldReconnect(); /** Called on every fresh link establishment (`connect()` / a redial): re-enable + hook keep-alive. */ private _onLinkEstablished; /** Attach the auto-redial disconnect listener to one connection, once (Phase 8b). */ private _hookKeepAlive; /** Schedule one backoff+jitter re-dial (Phase 8b); idempotent — one attempt pending at a time. */ private _scheduleRedial; private _cancelRedial; private _cancelDebugResume; /** * Establish the connection without dispatching anything: dial the preferred transport, run its * handshake, and attach the mux — so a realm-only (actionless) client can * exist. Idempotent: the connection cache shares one in-flight establishment, so concurrent and * repeat calls coalesce; resolves when the handshake completes, rejects when the transport * chain is exhausted. The carriers receive actionless dial params. * * **A failed dial arms the keep-alive backoff ladder** (when keep-alive is on) rather than leaving * the connection idle: the classic cold start — the app loads before the backend finished booting — * heals on its own instead of needing a page reload. The rejection still propagates, so the caller * still sees the first failure; the retries continue in the background (observe them via * `addLinkEventListener`'s `redial_scheduled` / `link_up`). * * Two rejections park the ladder instead of arming it (no background retry follows): * `dial_unavailable` (no endpoint right now) and `identity_pin_mismatch` (the peer has a * different verify key pinned for this client identity — permanent for this identity+key pair). */ connect(config?: { localCoordinate?: RuntimeCoordinate; }): Promise; /** * Tear down the (possibly half-open) duplex link and immediately re-dial it (the reconnect contract / Phase * 8b). Surfaced to a realm client as the connection adapter's `requestReconnect` (via * {@link requestReconnect}) — the staleness-probe escalation calls it when a probe goes * unanswered. On a successful re-dial the mux re-attaches and every realm re-hellos; a failure * falls into the keep-alive backoff loop when enabled, else the next probe retries. * * **Awaitable** — resolves when the fresh link's handshake completes, rejects when the transport * chain is exhausted (after which the keep-alive backoff continues, when enabled). Bind a * "retry now" button to this instead of waiting out the backoff ladder. */ reconnectLink(): Promise; /** * Stop the keep-alive auto-redial and release the current link — the intention-revealing * teardown counterpart of `reconnect`. Call this when a session is * over (leaving a match, logging out): the link closes and stays closed until the next explicit * `connect()`/dispatch. Not terminal (unlike {@link dispose}) — the client is reusable. */ releaseLink(): void; /** * Drop the connection cache (closing any live socket) without the keep-alive auto-redial — the * app asked for the link to drop; a later explicit `connect()`/dispatch re-enables keep-alive. * (Contrast {@link reconnectLink}, which drops then re-dials.) An app-initiated release is not an * outage, so the released socket's late close stays silent (no spurious `link_down`). */ clearTransportCache(): void; /** * Permanently stop this client (Phase 8b): cancel any pending auto-redial and drop the connection * cache. After this, keep-alive never re-dials again (an explicit, final teardown — distinct from * {@link clearTransportCache}, which an app may use to force a fresh connection). */ dispose(): void; /** * Close any live long-lived connection (e.g. a WebSocket) before dropping it, so a teardown * actually releases the socket instead of leaving it open until GC. HTTP/stateless transports * don't implement `disconnect`, so they're simply forgotten. * * @internal Bare cache drop with no redial suppression. Apps call {@link clearTransportCache} or * {@link releaseLink} instead. */ clearCache(): void; /** * Observe transport link-state: `link_down`, `redial_scheduled` * (attempt + delay — truthful "retrying in N s" UX), `link_up` (with `downForMs`). Returns an * unsubscribe. See {@link TLinkEvent} for the contract (a healthy heal is silent at the realm's * sync layer — this is where it's visible). */ addLinkEventListener(listener: (event: TLinkEvent) => void): () => void; private _emitLinkEvent; } //#endregion //#region src/wire/Connect/duplexLinkSession.d.ts /** * Wire-level link keepalive — the client half of the * acceptor's `"ping"`→`"pong"` answer: after `idleMs` with **no inbound frame**, send a raw * `"ping"`; if nothing (pong or otherwise) arrives within `pongTimeoutMs`, close the carrier * locally — converting a *half-open* socket (browser offline, NAT death: `isOpen()` true, sends * into the void) into the ordinary close → auto-redial path, for every protocol on the link at * once. A busy link never pings; outbound traffic deliberately does NOT count as liveness (sends * "succeed" locally on a half-open socket — that's the failure mode being detected). */ interface IWireHeartbeat { /** Quiet window (no inbound frame) before a ping is sent. */ idleMs: number; /** How long after the ping to wait for ANY inbound frame before declaring the link half-open. */ pongTimeoutMs: number; } /** @deprecated Use `IWireHeartbeat`. */ type IWireLinkKeepalive = IWireHeartbeat; /** * Connector-side (dial-out) duplex session over an {@link IDuplexCarrier} — the wire half of what * used to be nice-action's `establishLinkSession` (shared connection design, Phase 2; lane * protocol formalized at Phase 5). Owns everything between "carrier attached" and "lane frames * flow": the client handshake (with its message pump + timeout), the frame-crypto pipe, pre-ready * frame buffering, the protocol mux bind/detach, and the disconnect-listener fan-out. What it * does NOT own is the lane: every decrypted inbound frame the mux doesn't claim goes to the * {@link IWireLaneEndpoint} verbatim (E5 — the lane's namespace is "everything unprefixed"), the * lane supplies the handshake payload via {@link IWireLaneProtocol.handshakeConfig}, and its * `onDetach` fires when the channel closes (after the disconnect listeners, matching the * pre-split abort ordering). */ interface IWireDuplexSessionContext { channel: IDuplexCarrier; } /** The live session the lane talks through once establishment completes. */ interface IWireDuplexSession { /** Send one lane frame (encrypted + ordered by the pipe at the `encrypted` level). */ send(frame: TFrame$1): void; isOpen(): boolean; /** Deliberately close the underlying carrier (the close handler still runs cleanup). */ close(): void; addOnDisconnectListener(listener: () => void): void; /** The peer's negotiated caps; `undefined` on the plain path (no caps negotiation). */ readonly remoteCaps?: readonly string[]; /** * Attach the mux to this link (idempotent; a closed link never attaches). Only needed when the * session was built with `deferMuxAttach` — until then inbound protocol frames wait in order. */ attachMux?(): void; } /** * Plain path (no handshake): route every inbound frame to the lane; send without crypto. The * lane is the bare {@link IWireLaneEndpoint} — a plain connection negotiates nothing, so there is * no handshake config to supply and no `onAttach` fires. */ declare function establishPlainDuplexSession(ctx: IWireDuplexSessionContext & { lane: IWireLaneEndpoint; /** * Optional frame-protocol mux (Phase 2.5): prefixed inbound frames dispatch to it before the * lane, and it attaches to the (plaintext) send path immediately — a plain connection * negotiates nothing, so the mux's remote ids are **assumed** from its own registrations * rather than learned from a handshake. That is safe by construction: the *peer's* side is the * real filter (the acceptor's A.6 security gate admits only `allowPlain` protocols on a plain * connection, and an unregistered prefix is consumed-and-dropped, never mis-decoded). */ mux?: WireProtocolMux; /** Hold the mux off this link until `session.attachMux()` (e.g. until selection picks it). */ deferMuxAttach?: boolean; heartbeat?: IWireHeartbeat; /** Wire-traffic observation (devtools) — reports every frame's true carrier bytes. */ tap?: TWireTapFn; }): IWireDuplexSession; /** * Secure path: a single message handler feeds the handshake until it completes, then routes lane * frames (decrypting at the `encrypted` level). Frames that race ahead of activation are buffered * and flushed once the handshake lands, so nothing is lost. The lane supplies the handshake * payload (`dictionaryVersion`/`channels`, E5 — emitted under the byte-frozen wire names; the * version is signed into the challenge) and gets `onAttach` with the negotiated caps before any * buffered frame is delivered. */ declare function establishSecureDuplexSession(ctx: IWireDuplexSessionContext & { secure: IWireSecureClientConfig; /** The lane protocol (E5) — handshake payload supplier + unprefixed-frame consumer. */ lane: IWireLaneProtocol; /** * Optional frame-protocol mux: its registered protocols are advertised as `proto:` * handshake caps, prefixed frames dispatch to it before the lane, and it attaches to the * (encrypting) send path once the handshake lands. */ mux?: WireProtocolMux; /** Hold the mux off this link until `session.attachMux()` (e.g. until selection picks it). */ deferMuxAttach?: boolean; /** Half-open detection (8b.3) — armed only after the handshake completes. */ heartbeat?: IWireHeartbeat; /** Wire-traffic observation (devtools) — reports every frame's true carrier bytes. */ tap?: TWireTapFn; }): Promise; //#endregion //#region src/wire/Connect/WireLinkConnection.d.ts /** * Per-dial ready data for a wire duplex link: the opened carrier plus everything the session needs * to bring it up (the secure config when secure, the mux, the lane, keepalive, tap). Assembled by * {@link WireLinkConnection}'s `getTransport` and consumed by its finalize hooks. */ interface IWireLinkReadyData { channel: IDuplexCarrier; /** Present + `securityLevel !== none` ⇒ run the authenticated/encrypted handshake on bring-up. */ secure?: IWireSecureClientConfig; /** The frame-protocol mux riding this link — its protocols advertise as caps and dispatch first. */ mux?: WireProtocolMux; /** The unprefixed-frame lane (E5). Defaults to the trivial {@link lanelessLane} (mux carries all). */ lane: IWireLaneProtocol; heartbeat?: IWireHeartbeat; tap?: TWireTapFn; } type TWireLinkInitialized = IWireTransportInitialized, IWireLinkReadyData>; type TWireLinkDef = IWireTransportDef>; interface IWireLinkConnectionOptions { /** Open (or reuse) the duplex carrier for one dial — from a carrier source's `open`. */ openChannel: (params: IWireDialParams) => IDuplexCarrier; /** Keys identifying a reusable carrier, so one socket is shared across dials to the same peer. */ getCacheKey?: (params: IWireDialParams) => string[]; /** Availability gate — a `false` result skips this transport (the chain falls through). */ isAvailable?: (params: IWireDialParams) => boolean; /** Devtools route info for traffic over this connection. */ getRouteInfo?: (params: IWireDialParams) => IWireRouteInfo | undefined; /** Secure-channel config; when set (and level !== none) the handshake runs on bring-up. */ secure?: IWireSecureClientConfig; /** The frame-protocol mux riding this connection (a realm, devtools). */ mux?: WireProtocolMux; /** The lane protocol; defaults to the trivial {@link lanelessLane} (a mux-only connection). */ lane?: IWireLaneProtocol; /** Wire keepalive (8b.3) resolver — evaluated per dial (the auto-default depends on the mux). */ heartbeat?: () => IWireHeartbeat | undefined; /** Wire-traffic observation (devtools) — threaded into every dial's session (survives redials). */ tap?: TWireTapFn; /** Short label for the devtools chip (defaults to the carrier's own). */ label: string; } /** * A wire-native, action-free live connection over a duplex carrier — the substrate twin of * nice-action's `LinkConnection`. It owns only the *bring-up* (open the carrier, then run the wire * duplex session); the session itself — handshake, frame crypto, mux bind/detach, keepalive — lives * in the shared `establish(Plain|Secure)DuplexSession`. Its lane defaults to the trivial {@link * lanelessLane}, so a realm (or devtools, or anything on the mux) rides it with no unprefixed lane * of its own. This is what `createWireClient` builds and hands to a {@link * import("./WireClient").WireClient}; the exposed methods are the minimal {@link * IWireConnectionMethodsBase} lifecycle sliver (a mux-only connection sends through the mux, not a * lane send surface). */ declare class WireLinkConnection extends TransportConnection, IWireLinkReadyData, IWireConnectionMethodsBase, TWireLinkInitialized, TWireLinkDef> { private readonly options; constructor(options: IWireLinkConnectionOptions); protected _needsAsyncBringUp(): boolean; protected _awaitCarrierReady(data: IWireLinkReadyData): Promise; protected _finalizeReady(data: IWireLinkReadyData): Promise; protected _finalizeTransportMethods(data: IWireLinkReadyData): IWireConnectionMethodsBase; getRouteInfo(params: IWireDialParams): IWireRouteInfo | undefined; } //#endregion //#region src/wire/Connect/createWireClient.d.ts interface ICreateWireClientBaseOptions { /** * This client's runtime coordinate — who it authenticates as to the peer. A protocol riding the * connection (a realm) defaults its own participant identity from it. */ identity: RuntimeCoordinate; /** The peer this client dials — the acceptor's coordinate (the `externalClient` of every dial). */ peer: RuntimeCoordinate; /** * Durable backing for this client's crypto identity, fanned across every *secure* transport. * Required when any carrier is secure (the default), unless `ephemeralIdentity: true`. **Must be durable** — the peer pins this * identity's verify key on first contact (TOFU); a store that forgets across reloads regenerates * the key and is rejected `identity_pin_mismatch` on every later load. Pass `link` to share an * existing identity instead. */ storage?: StorageAdapter; /** The client's crypto identity. Defaults to a fresh {@link ClientCryptoKeyLink} over `storage`. */ link?: ClientCryptoKeyLink; /** * Declare this identity **ephemeral by construction** (the coordinate's persistent id is minted * fresh per session). This permits omitted or non-durable `storage`; supplied `link`/`storage` * still takes precedence. Do NOT set it for an id that survives reloads. */ ephemeralIdentity?: boolean; /** The security level secure transports request; defaults to `authenticated`. */ securityLevel?: ESecurityLevel; /** * The frame-protocol mux this client's connection carries. `createWireClient` creates one per * client by default (reachable as `client.wireMux`); pass one to share it or drive it from tests. * Register protocols on it (or pass {@link protocols}) **before** `connect()` so the handshake * advertises them. */ mux?: WireProtocolMux; /** * Frame protocols riding this connection, registered on the mux at construction (before any * `connect()`) so the handshake always advertises them. A protocol module that manages its own * registration (a realm via `realmConnection(client)`) uses the mux directly instead. */ protocols?: readonly IWireFrameProtocol[]; /** * Keep the link alive by auto-redialing it on an unexpected drop (backoff + jitter). Default: * on when the mux carries a registered protocol (a realm), off otherwise. `false` opts out. */ reconnect?: boolean; /** @deprecated Use `reconnect`. */ keepLinkAlive?: boolean; /** * Wire-level half-open detection (8b.3): after `idleMs` idle the link pings; no answer within * `pongTimeoutMs` closes it locally → the ordinary redial. Default: on whenever * {@link reconnect} is active; `false` disables; a config object tunes/forces it. */ heartbeat?: false | { idleMs?: number; pongTimeoutMs?: number; }; /** @deprecated Use `heartbeat`. */ linkKeepalive?: false | { idleMs?: number; pongTimeoutMs?: number; }; /** * Observe this connection's wire traffic (devtools): every frame that crosses a carrier, with its * true post-encryption byte size and lane. Stamped with `linkId` = {@link peer}'s `stringId`. */ wireTap?: TWireTapFn; /** * Observe transport link-state: `link_down`, `redial_scheduled` * (attempt + delay), `link_up` (with `downForMs`). A drop that {@link reconnect} heals is * silent at a realm's sync layer — this is where transport churn is visible. Post-hoc * subscription: `client.addLinkEventListener`. */ onLinkEvent?: (event: TLinkEvent) => void; } type ICreateWireClientOptions = ICreateWireClientBaseOptions & ({ /** Duplex carriers in preference order. Security is configured on each carrier. */ carriers: readonly IWireDuplexCarrierSource[]; transports?: never; } | { /** @deprecated Pass carrier values directly through `carriers`. */ transports: readonly IWireClientTransport[]; carriers?: never; }); /** The concrete `WireClient` shape `createWireClient` returns — a mux-only duplex link. */ type TWireClientInstance = WireClient; /** * The public way to **open a wire connection** — the dial-out front door of `connect-core/wire`, and * the substrate `connectChannel` (action) is a binding over. It builds a mux-carrying duplex * connection to a peer (one crypto identity fanned across the secure transports, preference-ordered * fallback, the keep-alive redial ladder, link events) and returns a {@link WireClient} — which * structurally satisfies realm's `IRealmWireLink`, so a realm rides it with **no action import**: * * ```ts * const client = createWireClient({ * identity: RuntimeCoordinate.env("web_app").withPersistentId(perId), * peer: RuntimeCoordinate.env("backend"), * storage, * carriers: [wsCarrier(url)], * }); * const realm = connectRealm(myRealm, { avatar: { type: "player" }, connection: realmConnection(client) }); * await client.connect(); * ``` * * The same client is what a devtools window holds (Phase 2.5): action, realm, and devtools are all * protocols/lanes over this one connection substrate. */ declare function createWireClient(options: ICreateWireClientOptions): TWireClientInstance; //#endregion //#region src/wire/Connect/err_wire_connect.d.ts /** * The Connect layer's error domain. Declared with the types * so Phases 2–6 throw against a fixed vocabulary instead of inventing ad-hoc `Error`s per phase; * each id notes the phase that starts raising it. (`protocol_unsupported` is the link-level * error `nice-realm`'s `err_realm` doc already points at as living here.) */ declare const err_wire_connect: NiceErrorDomain<{ domain: string; allDomains: [string, "err_nice"]; schema: { /** Phase 2 — `connect()` rejects: every transport in the preference chain failed. */ connect_exhausted: INiceErrorIdMetadata<{ peerId: string; attempted: readonly string[]; }, JSONSerializableValue>; /** Phase 2 — `connect()` after `close()`; a closed client is terminal, build a new one. */ connect_closed: INiceErrorIdMetadata<{ peerId: string; }, JSONSerializableValue>; /** * Phase 2 — one transport's dial or handshake failed (the chain item detail inside * `connect_exhausted`). `endpoint`/`kind` are the feedback W2/W3 additions: the URL actually * dialed, and the typed class of failure (see `EWireConnectFailureKind`). */ dial_failed: INiceErrorIdMetadata<{ peerId: string; carrierLabel: string; reason: string; endpoint?: string; kind?: EWireConnectFailureKind; }, JSONSerializableValue>; /** * the resilience contract — the carrier has **no valid endpoint right now** (`createRequest` * returned `null`, e.g. a torn-down session's mutable dial context). Not a failure: a policy * signal. The transport selection rethrows it unwrapped, and a keep-alive redial loop PARKS on * it — no dialing garbage, no backoff churn — until the next explicit `connect()`/dispatch. */ dial_unavailable: INiceErrorIdMetadata<{ carrierLabel: string; }, JSONSerializableValue>; conflicting_connect_options: INiceErrorIdMetadata<{ detail: string; }, JSONSerializableValue>; /** * Consumer feedback (meteor-connect-bridge W1/W3) — **something answered, and it is not * nice-wire**. The dominant real-world causes are a wrong URL/port, an intercepting proxy or * WAF, or an endpoint that is simply a different server. Thrown where the evidence still * exists (the carrier holds the HTTP status; the handshake holds the frame), so the data * carries what came back instead of only what we wanted. Branch on it with * `err.hasId("endpoint_answered_non_protocol")` — never on the message text. */ endpoint_answered_non_protocol: INiceErrorIdMetadata<{ /** The layer that judged the response, used as the message's `[marker]` — e.g. "exchange-handshake". */ stage: string; /** What that layer was waiting for — e.g. "a welcome frame". */ expected?: string; /** The endpoint actually dialed. */ url?: string; /** Present when the carrier saw an HTTP response. */ httpStatus?: number; contentType?: string; /** The envelope kind that decoded, when the body *was* a protocol frame of the wrong sort. */ receivedKind?: string; /** Bounded, sanitized head of the body (see `describeNonProtocolBody`). */ bodyPreview?: string; }, JSONSerializableValue>; /** * **No response was received**: DNS/refused/TLS/offline, a socket that errored before it * opened, or a response the platform hid from the caller (a CORS-blocked answer, a refused * WebSocket upgrade, an injected fetch/socket that threw). The sibling of * `endpoint_answered_non_protocol`, which carries the response it did see. */ endpoint_unreachable: INiceErrorIdMetadata<{ /** The endpoint actually dialed. */ url?: string; carrierLabel?: string; /** The platform's own words (`ECONNREFUSED`, RN's "Network request failed", …). */ reason: string; }, JSONSerializableValue>; /** * The peer **is** a nice-code backend and refused the handshake for a reason that carries no * machine-readable id of its own (an older peer, a dictionary/security mismatch, a custom * gate). Typed so `classifyConnectFailure` can report `handshake_rejected` — a third * developer response ("fix the identity/version"), distinct from a wrong URL or a dead host. * `identity_pin_mismatch` stays its own id: it is permanent and the redial loop parks on it. */ handshake_rejected: INiceErrorIdMetadata<{ stage: string; reason: string; }, JSONSerializableValue>; /** * The peer explicitly reported that the secure handshake has no compatible first-party wire * generation. This is terminal for the current builds: transport fallback and automatic * redial park until the application explicitly retries after an upgrade or rollback. */ protocol_version_mismatch: INiceErrorIdMetadata<{ reason: string; observedProtocolVersion?: number; localSupportedProtocolVersions: readonly number[]; remoteSupportedProtocolVersions?: readonly number[]; }, JSONSerializableValue>; /** * A secure endpoint answered as nice-wire but advertised a different runtime identity from the * one the caller selected. This is terminal for the current endpoint selection, so fallback and * automatic redial park until an explicit retry after the route or expectation changes. */ peer_identity_mismatch: INiceErrorIdMetadata<{ expected: { envId: string; perId?: string; }; actual: { envId: string; perId?: string; }; /** Sanitized destination (credentials/query/fragment removed), when known by the carrier. */ endpoint?: string; }, JSONSerializableValue>; /** Phase 3 — a protocol sent on a connection whose peer did not advertise it (or the host never registered it). */ protocol_unsupported: INiceErrorIdMetadata<{ protocolId: string; }, JSONSerializableValue>; /** Phase 6 — a prefixed protocol registered on an exchange-only connection (protocols need duplex; the protocol contract). */ protocol_on_exchange_only: INiceErrorIdMetadata<{ protocolId: string; }, JSONSerializableValue>; /** Phase 4 — the acceptor security gate: protocol frame on a non-authenticated connection without `allowPlain`. */ protocol_security_blocked: INiceErrorIdMetadata<{ protocolId: string; securityLevel: string; }, JSONSerializableValue>; /** Phase 4 — rehydrate saw a binding with an unknown schema version: treat the socket as fresh. */ binding_version_mismatch: INiceErrorIdMetadata<{ found: unknown; expected: number; }, JSONSerializableValue>; /** * Inteleport feedback §3 — the peer rejected the handshake because this client's verify key does * not match the one pinned for its identity (trust-on-first-use, keyed `envId::perId`). Permanent * for this identity+key pair: retrying can never succeed, so the keep-alive redial loop PARKS on * it (like `dial_unavailable`) instead of backing off forever. Note clearing the client's *crypto* * storage alone does NOT recover — a fresh key under the SAME persistent id is exactly what the * pin rejects. Recover by connecting under a new persistent id (and a fresh identity), or by * removing the peer-side pin via the verify-key resolver's storage. Branch on it with * `err.hasId("identity_pin_mismatch")`. */ identity_pin_mismatch: INiceErrorIdMetadata<{ reason: string; }, JSONSerializableValue>; }; }>; //#endregion //#region src/wire/Connect/exchangeEnvelope.d.ts /** * The wire envelope for secure traffic over an `IExchangeCarrier` (HTTP) — re-homed from * nice-action's `exchangeProtocol.ts`. An exchange carrier * only moves one request frame → one reply frame with no unsolicited push, so the handshake and * the per-request token + crypto all ride in this envelope (a JSON string body) rather than on a * persistent channel. The three security levels share it: * * - `none` — no handshake, no token: an `act` envelope carries the plaintext lane wire both ways. * - `authenticated` — a one-time handshake yields a session `t`oken; each later `act` carries it * plus the plaintext wire. * - `encrypted` — same, but the wire is AES-GCM ciphertext, base64 in the `c` field. * * The handshake runs as two `hs` exchanges (hello→welcome, prove→accept). The acceptor keeps * **no** in-flight state between them: the `welcome` reply carries a sealed handshake-continuation * token `hsc` (the acceptor's `pending` state, opaque to the client), which the connector echoes * on the `prove` request. The `accept` reply then carries the (sealed) session `t`oken replayed on * every later `act`. All server-side continuity rides these sealed tokens, so no request needs to * co-locate with another. * * The `w` slot is the **lane's** wire (E5) — opaque JSON to this layer; nice-action's typed view * of the same envelope stays in its `exchangeProtocol.ts`. The field names + literal order are * byte-frozen (pinned end-to-end by the exchange integration suites). */ /** Connector → acceptor request envelope. */ type TWireExchangeRequest = { k: "hs"; m: string; hsc?: string; } | { k: "act"; t?: string; w: unknown; } | { k: "act"; t?: string; c: string; }; /** Acceptor → connector reply envelope. */ type TWireExchangeReply = { k: "hs"; m: string; hsc?: string; t?: string; } | { k: "act"; w: unknown; } | { k: "act"; c: string; } | { k: "err"; message: string; }; declare function encodeExchange(envelope: TWireExchangeRequest | TWireExchangeReply): string; declare function decodeExchangeRequest(raw: string): TWireExchangeRequest | undefined; declare function decodeExchangeReply(raw: string): TWireExchangeReply | undefined; //#endregion //#region src/wire/Connect/exchangeSession.d.ts /** * Connector-side (dial-out) session over an {@link IExchangeCarrier} (HTTP) — the request → * single correlated reply sibling of `establishSecureDuplexSession` (shared connection design, * Phase 6). The secure session is identical in spirit — the same handshake, then per-frame * crypto — but carried by independent exchanges rather than a push channel, so it can deliver no * unsolicited frame: each lane wire's reply rides the response to its own request, and there is * no return path. * * The exchange path is **lane-only**: no protocol mux rides here — prefixed protocols * need a duplex carrier (`err_wire_connect.protocol_on_exchange_only`). Accordingly the lane * contributes only its handshake payload ({@link IWireLaneHandshakeConfig}); there is no frame * callback surface — the lane consumes each reply where it awaited it. * * At `none` there is no handshake or token: an `act` envelope carries the plaintext wire both * ways. At `authenticated`/`encrypted` a one-time handshake (two `hs` exchanges) yields a session * token replayed on every later `act`; at `encrypted` the wire is AES-GCM ciphertext. */ interface IWireExchangeSession { /** Send one lane wire, await its correlated reply, and open it (decrypting when encrypted). */ exchange(wire: unknown, opts?: { signal?: AbortSignal; }): Promise; /** Send one lane wire and ignore the reply body (no unsolicited frame rides an exchange). */ send(wire: unknown, opts?: { signal?: AbortSignal; }): Promise; } /** One exchange's opened reply — the lane maps failures onto its own error vocabulary. */ type TWireExchangeOutcome = /** The reply's lane wire (opaque JSON to this layer). */ { ok: true; wire: unknown; } | /** No decodable reply envelope (or ciphertext on a session without crypto). */ { ok: false; reason: "malformed_reply"; } | /** The acceptor answered with its `err` envelope. */ { ok: false; reason: "peer_error"; message: string; }; /** Plain path (no handshake/token): every wire rides a bare `act` envelope, plaintext both ways. */ declare function establishPlainExchangeSession(carrier: IExchangeCarrier): IWireExchangeSession; /** * Secure path: run the handshake (two exchanges) once at bring-up, then reuse the token + crypto. * The lane supplies the handshake payload (`dictionaryVersion`/`channels`, E5 — emitted under the * byte-frozen wire names; the version is signed into the challenge). */ declare function establishSecureExchangeSession(ctx: { carrier: IExchangeCarrier; secure: IWireSecureClientConfig; lane: IWireLaneHandshakeConfig; }): Promise; //#endregion //#region src/wire/Connect/lanelessLane.d.ts /** * The handshake dictionary version a **lane-less** (mux-only) connection advertises — a connection * that carries no unprefixed lane of its own because every protocol rides the {@link * import("../Mux/WireProtocolMux").WireProtocolMux} (a realm, devtools). It is the neutral * connection's identity in the handshake: the acceptor signs it into the challenge (and folds it * into the encryption HKDF), so both ends must agree on it byte-for-byte. * * Its value is **exactly what an empty `connect-core/action` channel (`defineChannel({})`) derives** * (`deriveDictionaryVersion([])` = the FNV-1a of the empty route list), so a `createWireClient` * connection interoperates with an action-served empty-channel acceptor with **no server change** — * a supported mixed-hosting compose (a realm-only client dialing an action host that also serves an * empty channel). It is pinned by an action-side test (`defineChannel({}).dictionaryVersion === this`), * so a drift in the derivation is caught rather than shipped. * * **Format-finalization verdict (Phase 4): kept as the auto-derived value, deliberately.** Giving it * a "meaningful" string (`"laneless:v1"`) would force `defineChannel({})` to emit a hand-picked * string instead of its derived one — breaking the `dictionaryVersion = f(routes)` invariant for the * empty case just to prettify a value **no consumer ever types** (it is internal handshake plumbing, * signed into the challenge + folded into the HKDF). The `"auto:"` prefix already tells the honest * story: it is auto-derived. Frozen. */ declare const WIRE_LANELESS_DICTIONARY_VERSION = "auto:811c9dc5"; /** * A trivial {@link IWireLaneProtocol} for a **mux-only** connection: the mux carries every protocol * frame (a realm, devtools), so the lane itself sends and receives nothing. It supplies the * {@link WIRE_LANELESS_DICTIONARY_VERSION} + no channels to the handshake, and no-ops the receive * path. A stray *unprefixed* frame is a protocol anomaly (the peer sent lane traffic to a lane-less * connection) — dropped with a one-line warning rather than silently, so the misconfiguration is * visible without being fatal. * * This is the default lane a {@link import("./WireLinkConnection").WireLinkConnection} runs when * `createWireClient` builds a connection with no lane binding — the seam the action lane fills with * its codec (`connect-core/action`'s `finalizeSecureLinkMethods`) and a devtools protocol will leave * empty just like a realm does. */ declare function lanelessLane(): IWireLaneProtocol; /** * The acceptor-side twin of {@link lanelessLane}: an {@link IWireAcceptorLane} for a **mux-only** * server (a realm-only Durable Object). The mux consumes every protocol frame (prefixed), so the * lane carries nothing — it only supplies the handshake version payload (the same * {@link WIRE_LANELESS_DICTIONARY_VERSION} the client's `lanelessLane` advertises, so a * `createWireClient` and a `serveWireDurableObject` handshake agree byte-for-byte) and no-ops the * rest. * * A realm requires a *secure* connection, so the handshake — not the lane — binds identity * (`WireAcceptor` binds the authenticated coordinate on `onAuthenticated`) and the realm protocol * attaches via the un-gated fan-out; the lane's `onFrame` is genuinely never reached on the realm * path. A stray unprefixed frame is a protocol anomaly, dropped with a one-line warning rather than * silently (the mirror of the client side). This is the lane `serveWireDurableObject` installs. */ declare function lanelessAcceptorLane(): IWireAcceptorLane; //#endregion //#region src/wire/Connect/serveWire.d.ts interface IServeWireOptions { identity: RuntimeCoordinate; /** Exactly one duplex carrier. Protocols require a push-capable connection. */ carriers: readonly IDuplexAcceptorCarrier[]; protocols?: readonly IWireAcceptorProtocol[]; storage?: StorageAdapter; link?: ClientCryptoKeyLink; verifyKeyResolver?: IClientVerifyKeyResolver; securityLevel?: ESecurityLevel | readonly ESecurityLevel[]; wireTap?: TWireTapFn; } interface IWireServer { acceptor: WireAcceptor; fetch(request: Request): Promise; receive(connection: TConn, frame: TFrame$1): void; drop(connection: TConn): void; close(): void; } /** * Serve a lane-less wire connection on Bun, Node, or any custom host. The caller owns socket * upgrades and forwards frames through the returned carrier/server lifecycle. No action runtime or * empty action channel is involved. */ declare function serveWire(options: IServeWireOptions): IWireServer; //#endregion //#region src/wire/Connect/WireExchangeAcceptor.d.ts /** * One authenticated `act` request as the lane sees it: the opened (decrypted) lane wire plus the * session facts the acceptor resolved from the ticket. */ interface IWireExchangeLaneRequest { /** The decoded lane wire from the `act` envelope (opaque JSON to wire — E5). */ wire: unknown; /** The handshake-authenticated client coordinate; absent on a plain (`none`, tokenless) request. */ client?: RuntimeCoordinate; securityLevel: ESecurityLevel; /** Whether this session runs the per-frame crypto (the reply rides it when the request did). */ encrypted: boolean; } /** The lane's reply: its result wire, or a message wire answers as the `err` envelope. */ type TWireExchangeLaneReply = { ok: true; wire: unknown; } | { ok: false; message: string; }; /** * The lane's acceptor-side hooks for the exchange path — the request/reply twin of * `IWireAcceptorLane`. The exchange is **lane-only**: no protocol registry rides * here, so the whole surface is the handshake payload plus one request handler. */ interface IWireExchangeAcceptorLane { /** * The lane's handshake version payload (E5) — a fixed string, or a resolver composing it from * the peer's hello `channels` (a multi-channel lane). Wire treats it opaquely but signs it into * the challenge under its byte-frozen wire name; the handshake rejects on a mismatch. */ dictionaryVersion: string | TServerDictionaryVersionResolver; /** * Serve one opened `act` request, returning the lane's reply wire (it rides the same response, * encrypted when the request was). The identity in {@link IWireExchangeLaneRequest.client} is * the handshake-authenticated one — the lane binds it onto its wire, never the self-asserted. */ onExchange(request: IWireExchangeLaneRequest): Promise; } interface IWireExchangeAcceptorOptions { /** The acceptor's crypto identity + accepted level(s) — same shape the duplex acceptor uses. */ security: IWireAcceptorSecurity; /** The lane's hooks — the exchange path's one consumer (lane-only, no protocols). */ lane: IWireExchangeAcceptorLane; /** * How long a minted session ticket stays valid (ms). After it expires the client's next request * is rejected and it must re-handshake. Defaults to 12h — long enough for an ordinary session's * life, since a sealed ticket carries no server state to revoke before then. Keep it shorter for * a more tightly time-boxed session. */ sessionTtlMs?: number; } /** * The exchange (request/reply) acceptor backbone — the HTTP counterpart to `WireAcceptor`'s * duplex sessions, re-homed from nice-action's `ExchangeAcceptor` (shared connection design, * Phase 6). Each POST body is one exchange envelope; the acceptor drives the server handshake * over the two `hs` POSTs, mints a session **token** on accept, and on every later `act` POST * resolves the session by token, decrypts the body (at `encrypted`), hands the opened lane wire * to {@link IWireExchangeAcceptorLane.onExchange}, and returns the (encrypted) reply inline. * * **Stateless.** It holds no in-memory handshakes or sessions: the in-flight handshake `pending` * is sealed into the `hsc` continuation token returned on `welcome` and echoed back on `prove`, * and the live session is sealed into the `t` token replayed on every `act`. Both are sealed * under the acceptor's own persisted identity ({@link createExchangeTicketSealer}), so any * isolate that loaded the same identity can serve any POST — no request needs to co-locate with * another. A tampered, wrong-key, or expired token opens to "no valid session". */ declare class WireExchangeAcceptor { private readonly _security; private readonly _lane; private readonly _allowedLevels; private readonly _noneAllowed; private readonly _sealer; private readonly _sessionTtlMs; constructor(options: IWireExchangeAcceptorOptions); /** Process one POST body (an exchange envelope), returning the reply body to send back. */ handlePost(body: string): Promise; private _makeHandshake; private _handleHandshake; private _handleAction; private _err; } //#endregion //#region src/wire/Connect/wireConnectionParts.d.ts /** The wire-connection facts every dial-out entry point assembles the same way (E2/8b.3). */ interface IWireConnectionPartsOptions { /** The entry point building this connection — `"createWireClient"` / `"connectChannel"` (for the warning). */ callerName: string; /** The peer this connection dials — stamps `wireTap` events with its `stringId`. */ peer: RuntimeCoordinate; /** This client's coordinate — checked for the ephemeral-identity pin trap. */ identity: RuntimeCoordinate; /** A caller-supplied mux to populate + return; a fresh one is created when absent. */ mux?: WireProtocolMux; /** Frame protocols to register on the mux at construction (before the handshake advertises them). */ protocols?: readonly IWireFrameProtocol[]; /** Whether any transport on this connection is secure — gates building the crypto identity. */ anySecure: boolean; /** Durable backing for the crypto identity (required when secure unless `ephemeralIdentity`). */ storage?: StorageAdapter; /** A caller-supplied crypto identity, shared across the secure transports. */ link?: ClientCryptoKeyLink; /** Suppress the ephemeral-identity warning for a deliberately per-session id. */ ephemeralIdentity?: boolean; reconnect?: boolean; heartbeat?: false | { idleMs?: number; pongTimeoutMs?: number; }; /** @deprecated Use `reconnect`. */ keepLinkAlive?: boolean; /** @deprecated Use `heartbeat`. */ linkKeepalive?: false | { idleMs?: number; pongTimeoutMs?: number; }; wireTap?: TWireTapFn; } /** The assembled facts a dial-out entry point threads into its transports. */ interface IWireConnectionParts { /** The connection's mux (caller-supplied or freshly created), with `protocols` registered. */ mux: WireProtocolMux; /** The crypto identity fanned across every secure transport (`undefined` for a fully-plain one). */ link?: ClientCryptoKeyLink; /** * The heartbeat resolver is a thunk because its automatic default mirrors `reconnect` * ("on for a protocol-carrying link") and protocols may register on the mux *after* this runs * (`realmConnection(client)` / `realmConnection(connector)` runs before `connect()`). */ resolveHeartbeat: () => IWireHeartbeat | undefined; /** The per-link-attributed traffic tap (`wireTap` stamped with the peer's `stringId`), or `undefined`. */ wireTap?: TWireTapFn; } /** * Assemble the connection facts a dial-out entry point shares — the one implementation of "how a * wire connection's mux, crypto identity, keepalive, and traffic tap are set up" (first-production * the connection design). `createWireClient` and `connectChannel` both call this; each then builds its own * transports (mux-only `WireLinkConnection`s vs action `Transport`s with the codec lane) around the * shared result, so a fix to any of these lands once. */ declare function assembleWireConnectionParts(options: IWireConnectionPartsOptions): IWireConnectionParts; //#endregion //#region src/wire/Connect/wireSelectionErrors.d.ts /** * The wire-native transport-selection failure vocabulary — what a `createWireClient` connection * throws when its transport chain can't produce a live link, expressed in `err_wire_connect` ids * (the counterpart of nice-action's `err_nice_transport`-flavoured `ConnectionTransportManager` * shim). `dial_unavailable`, `identity_pin_mismatch`, and `protocol_version_mismatch` are rethrown *unwrapped* by the manager * before these ever run, so the keep-alive redial can park on them (see * `ConnectionTransportManager`). */ declare function wireSelectionErrors(peerId: string): IWireTransportSelectionErrors; //#endregion //#region src/wire/codec/controlFrame.d.ts /** * The transport **control channel** — a lightweight frame category that rides the same secure connection * *beside* action frames, carrying connection/transport metadata that has no business going through the * action machinery (no schema, no hydration, no request/response correlation, no per-channel dictionary). * * Reliability acks are the first message type; the same channel is the reusable seam for future metadata * (flow-control/backpressure, presence, an app-level keepalive for carriers without a native ping, …). * * ## Wire shape & why it's byte-safe next to action frames * A control frame is a msgpack **object** (`{ $c: , … }`); the binary action codecs emit fixed-length * msgpack **arrays**. So a control frame never decodes as an action frame (`incoming` requires an array of * the envelope length) and an action frame never decodes as a control frame — best-effort action frames * stay byte-identical. Handshake frames are text JSON with a `t` field, also distinct. * * Keep {@link TControlMessage} a **small, closed, typed registry** of library/transport concerns — it is * deliberately *not* an open user side-channel (that's what actions/pushes are for). */ /** Reliable-delivery ack: cumulative contiguous high-water the sender has for the `domain:id` stream. */ interface IControlMessage_ReliableAck { $c: "rack"; /** The action route the ack is for; the receiver rebuilds `reliableStreamId(peer, domain, id, k)`. */ domain: string; id: string; /** Highest contiguous seq the peer has stored for this stream. */ ack: number; /** Optional streamKey (E3) — set for a keyed stream so the receiver rebuilds the same keyed id. */ k?: string; } /** * Reliable-delivery re-sync request: the receiver has **no state** for a `domain:id` stream whose incoming * `seq` is already past 0 — a session-tier reset (fresh process / evicted server) mid-stream. It asks the * sender to renumber its still-unacked frames from seq 0 and resend, so the stream continues instead of * stalling on an unfillable gap. Session-tier self-heal; the persisted tier resumes from storage and never * sends this. Route-only, like {@link IControlMessage_ReliableAck} (the stream id never rides the wire). */ interface IControlMessage_ReliableResync { $c: "rsync"; domain: string; id: string; /** Optional streamKey (E3) — set for a keyed stream so the sender re-syncs the same keyed stream. */ k?: string; } /** * Reliable-delivery skip notice (sender → receiver): every frame of the `domain:id` stream with * `seq <= seq` that hasn't arrived **will never arrive** — the sender abandoned it (its action aborted or * its delivery deadline expired) and pruned it from its outbox. The receiver advances the stream's * high-water past the abandoned seqs and drains anything it had buffered behind the gap, so the stream * *continues* instead of wedging on an unfillable gap forever. Cumulative like an ack (the sender drops * everything `<= seq` when it abandons a frame, so ordering among *delivered* frames is preserved). * Route-only + optional key, like the other reliable control messages. */ interface IControlMessage_ReliableSkip { $c: "rskip"; domain: string; id: string; /** Highest abandoned seq — the receiver treats all seqs `<= seq` as settled (delivered or abandoned). */ seq: number; /** Optional streamKey (E3) — set for a keyed stream so the receiver skips the same keyed stream. */ k?: string; } /** * Reliable-delivery stream close (sender → receiver): the sender closed the `domain:id [+ k]` stream for * good (`closeReliableStream`) — the receiver should **release its state** for it (in-memory inbox entry * or persisted log rows + high-water) and free the key's slot in the keyed-stream quota. Purely a memory * reclaim: it is safe to lose (the sender's retained `rskip` already settles delivery, and a later send * on a receiver that *did* forget self-heals through the normal `rsync` re-sync), and safe to receive * twice (forgetting an unknown stream is a no-op). */ interface IControlMessage_ReliableClose { $c: "rclose"; domain: string; id: string; /** Optional streamKey (E3) — set for a keyed stream so the receiver releases the same keyed stream. */ k?: string; } type TControlMessage = IControlMessage_ReliableAck | IControlMessage_ReliableResync | IControlMessage_ReliableSkip | IControlMessage_ReliableClose; declare function encodeControlFrame(message: TControlMessage): Uint8Array; /** * Decode a frame as a control message, or `undefined` if it isn't one (a best-effort peek — action frames * short-circuit on the first byte without a full unpack). Only binary frames are considered. */ declare function decodeControlFrame(frame: string | ArrayBuffer | Uint8Array | Blob): TControlMessage | undefined; //#endregion //#region src/wire/crypto/actionFrameCrypto.d.ts /** * Async AES-GCM transform for the `encrypted` security level. It wraps the opaque binary frame a * session codec produces (it does NOT look inside it), encrypting on the way out and decrypting on the * way in with the shared key established by the handshake. * * It is deliberately separate from the (synchronous) session `formatMessage`: WebCrypto is always * Promise-based, so encryption has to happen at the transport's async I/O boundary — the connection * encrypts after `session.outgoing()` and decrypts before `session.incoming()`. The `authenticated` * and `none` levels use no crypto transform at all (frames go out as the session produced them). * * Wire shape of an encrypted frame: `pack([nonceBytes, ciphertextBytes])` — msgpack carries the two * binary fields with a couple of bytes of overhead, no base64 inflation. */ interface IActionFrameCrypto { /** Encrypt one session frame for sending. */ encryptFrame(frame: Uint8Array): Promise; /** Decrypt one received frame back to the session frame. Throws on a non-binary / malformed / * tampered frame — the caller (transport) decides how to react (drop / close). */ decryptFrame(frame: string | ArrayBuffer | Uint8Array): Promise; } interface IActionFrameCryptoConfig { link: ClientCryptoKeyLink; /** * This session's handshake key material. The shared AES-GCM key is derived from it **once** and held * for the life of the connection — it is NOT re-read per frame from the link's per-`linkedClientId` * cache, so a second secure session to the same peer (e.g. a secure HTTP exchange beside a secure * WebSocket, both sharing one DO crypto identity) can't overwrite this connection's key. */ keyMaterial: IHandshakeEncryptionKeyMaterial; } /** * Build the encrypt/decrypt transform for a connection whose handshake settled on the `encrypted` * level. The shared key is derived once from {@link IActionFrameCryptoConfig.keyMaterial} and captured * for this connection alone, decoupling it from the link's shared key cache. */ declare function createActionFrameCrypto({ link, keyMaterial }: IActionFrameCryptoConfig): IActionFrameCrypto; //#endregion //#region src/wire/crypto/frameBytes.d.ts /** Normalize any frame form to bytes (for the AES-GCM layer, which works on `Uint8Array`). */ declare function toFrameBytes(frame: TFrame$1): Uint8Array; //#endregion //#region src/wire/crypto/securityLevelOrder.d.ts /** * A total order over {@link ESecurityLevel}. The enum is **string**-valued (`"none"` / * `"authenticated"` / `"encrypted"`), so `>=` on the values themselves is meaningless — a consumer * comparing "does this connection meet the required level" needs an explicit rank. This is the one * shared rank so every caller (the realm attach gate, the client-side assertion) compares levels * identically; a divergent ad-hoc comparison is exactly how a security floor silently inverts. * * Higher rank = stronger protection: `none` (0) < `authenticated` (1) < `encrypted` (2). */ declare const SECURITY_LEVEL_RANK: Record; /** `true` when `actual` meets or exceeds the `required` level (the "is this connection good enough" test). */ declare function securityLevelMeets(actual: ESecurityLevel, required: ESecurityLevel): boolean; //#endregion //#region src/wire/Mux/protocolFrame.d.ts /** * Frame-protocol prefix bytes (realm protocol design §3.1). A registered protocol frame is * `[prefixByte, ...payload]` with the prefix drawn from the reserved range `0x00`–`0x0F` — * bytes no legacy frame can start with: binary action envelopes are msgpack fixarrays * (`0x96`–`0x98`), control frames are msgpack maps (`0x80`–`0x8f`, `0xde`, `0xdf`), and * handshake frames are text JSON (`{` = `0x7b`). Frames without a reserved prefix fall through * to the legacy sniffing untouched, so old peers stay byte-identical (pinned by the * byte-compat goldens). * * The registry is **closed** — same philosophy as the control-message registry: protocols are * library-level concerns assigned here, never user-claimable ad hoc. */ declare const WIRE_PROTOCOL_PREFIX: { /** `0x00` is reserved/invalid — a zero prefix is treated as a decode error, never dispatched. */ readonly invalid: 0; /** `connect-core/realm` state-sync frames. */ readonly realm: 1; /** * `connect-core/devtools` observation frames. Assigned here so the prefix space has one * authoritative catalogue; `connect-core/devtools-core` (a zero-runtime-dependency package that * cannot import wire) mirrors it structurally as its own `DEVTOOLS_WIRE_PREFIX = 0x02`. */ readonly devtools: 2; }; /** Highest byte of the reserved prefix range (inclusive). */ declare const WIRE_PROTOCOL_PREFIX_MAX = 15; /** * Peek a frame's protocol prefix: the byte when it is a binary frame starting in the reserved * range, else `undefined` (a legacy frame — handshake/control/action — or a text frame). */ declare function peekProtocolPrefix(frame: TFrame$1): number | undefined; /** Wrap a protocol payload with its prefix byte. */ declare function encodeProtocolFrame(prefixByte: number, payload: Uint8Array): Uint8Array; /** Strip the prefix byte off an already-peeked protocol frame. */ declare function protocolFramePayload(frame: TFrame$1): Uint8Array; /** The handshake capability tag advertising a frame protocol (`hello.caps` / `welcome.caps`). */ declare function protocolCap(protocolId: string): string; /** Extract the advertised protocol ids from a peer's handshake caps. */ declare function protocolsFromCaps(caps: readonly string[] | undefined): ReadonlySet; //#endregion //#region src/wire/nice_wire.static.d.ts declare const DEFAULT_TRANSPORT_TIMEOUT = 10000; declare const UNSET_RUNTIME_ENV_ID = "_unset_"; declare const UNSET_RUNTIME_PER_ID = "_0_0_"; //#endregion //#region src/wire/PeerLink/reliableStream.d.ts /** * Local key for a reliable stream — `(peer identity + domain:id route [+ #streamKey])`. It is *never* * serialized whole: each side reconstructs it from the connection (the peer) and the frame's route, so only * the per-frame `seq`/`ack` integers (and the optional `streamKey` discriminator) ride the wire. The * connector keys by its server peer; the acceptor keys by the originating client — the two ids need not * match textually, only be internally consistent per side. An optional `streamKey` (E3) appends `#` so * several independent ordered streams of the same action (e.g. one per room id) stay separate. */ declare function reliableStreamId(peer: RuntimeCoordinate, domain: string, actionId: string, streamKey?: string): string; /** * One-time dev warning that a `.reliable()` frame is going out a transport with **no binary codec**, so its * reliability metadata (the `seq`/`ack` slot) — which rides the binary wire only — is silently dropped and * the frame degrades to best-effort (no ordering, dedup, or resend). The high-level `connectChannel` always * supplies a codec, so this only fires for a hand-rolled transport with none; surfacing it turns an invisible * downgrade into one visible line. Warns once per `domain:id` route (a reliable stream is high-frequency). */ declare function warnReliableWireUnavailableOnce(domain: string, actionId: string): void; /** * One-time dev warning that a `.reliable()` frame is going to a peer whose handshake did **not** advertise * the reliable capability ({@link CAP_RELIABLE}) — an older server that predates reliable delivery. The frame * is still sent (best-effort), but the peer won't apply ordering/dedup/resend, so surface the version skew * instead of silently emitting frames it may not interpret. Warns once per `domain:id` route. */ declare function warnReliablePeerUnsupportedOnce(domain: string, actionId: string): void; /** * One-time dev warning that a keyed (`streamKey`) `.reliable()` frame (E3) is going to a peer whose * handshake did **not** advertise the streamkey capability ({@link CAP_RELIABLE_STREAMKEY}) — a peer that * predates per-key streams. The keyed frame is a distinct length the peer rejects wholesale (it isn't * mis-decoded), so it simply won't be delivered; surface the version skew instead of failing silently. * Warns once per `domain:id` route. */ declare function warnReliableStreamKeyUnsupportedOnce(domain: string, actionId: string): void; /** * One-time dev warning that a **server-initiated push** (`pushToClient` / `broadcast` / an acceptor's * `handleActionRequest`) is sending a `.reliable()`-declared action: reliability engages in the * **connector → acceptor** direction only, so this push is delivered best-effort — no outbox, no seq, no * resend. Surfacing it turns a silent direction downgrade into one visible line. For a push stream that * must all arrive, build the persisted-log recipe (append + replay-on-reconnect); for a single push that * needs confirmation, await `pushToClient(...).waitForResultPayload()` and retry. */ declare function warnReliablePushUnsupportedOnce(domain: string, actionId: string): void; /** * One-time dev warning that a **reply-less** reliable send was abandoned: its delivery deadline expired * (or an aborted newer frame swept it) while unacked. Its caller was already told "success on send" — * that's the reply-less contract — so this is the only place the non-delivery becomes visible: the frame * was dropped, an `rskip` told the receiver to continue past it. Reply-carrying sends don't need this * (their action aborts loudly with `reliable_delivery_abandoned`). Warns once per `domain:id` route. */ declare function warnReliableDeliveryAbandonedOnce(domain: string, actionId: string): void; /** Test-only: clear the warn-once latches so each test observes the first warning. */ declare function _resetReliableDowngradeWarnings(): void; //#endregion //#region src/wire/protocolVersion.d.ts /** * The first-party nice-code wire/action/realm format generation implemented by this build. * * Package releases may change without changing this number. A generation belongs in * {@link WIRE_SUPPORTED_PROTOCOL_VERSIONS} only while this build contains the complete encoder, * decoder, session, and persistence compatibility needed to speak it. */ declare const WIRE_PROTOCOL_VERSION: 1; /** * Protocol generations this build can actually speak, newest first. This release has one codec, * so it advertises only v1; the intended future window is the current and previous generation. */ declare const WIRE_SUPPORTED_PROTOCOL_VERSIONS: readonly [1]; //#endregion //#region src/wire/SecureSession/exchangeTicketSeal.d.ts /** * Seals/opens the small server-only state of a *stateless* secure exchange — the handshake continuation * (`pending`) and the session ticket — into opaque blobs the client round-trips, so the acceptor keeps * **no** in-memory or stored session state. Only a server that holds the same persisted identity can open * a blob (the AES-GCM key is derived from that identity via {@link ClientCryptoKeyLink.deriveLocalSealKey}), * so any isolate sharing the identity is interchangeable. * * Each blob embeds an absolute expiry; {@link IExchangeTicketSealer.open} returns `undefined` for an * expired, tampered, wrong-key, or malformed blob (the caller treats all of these as "no valid session"). * * Wire shape: `base64( pack([nonce, ciphertext]) )`, where the plaintext is `pack({ v, exp })`. */ interface IExchangeTicketSealer { /** Seal `value` into a blob valid for `ttlMs` from now. */ seal(value: unknown, ttlMs: number): Promise; /** Open + validate a blob, or `undefined` if expired / tampered / wrong key / malformed. */ open(blob: string): Promise; } declare function createExchangeTicketSealer(link: ClientCryptoKeyLink, options?: { version?: string; }): IExchangeTicketSealer; //#endregion //#region src/wire/SecureSession/frameCryptoPipe.d.ts /** * Ordered frame crypto over a single channel/connection — the one place the encrypt-on-send / * decrypt-on-receive logic lives, shared by both link roles: * * - the **connector** (one carrier, one crypto) — see `establishLinkSession`; * - the **acceptor** (one per accepted connection, crypto re-derived asynchronously after a hibernation * wake) — see `ChannelAcceptor`. * * Outbound frames go on an ordered chain so async AES-GCM never reorders them, and the chain gates once * on `crypto` — which, when `crypto` is a promise, also gates the first send on the post-wake key * re-derivation. With no `crypto` it's a plaintext passthrough. */ interface IFrameCryptoPipe { /** * Encrypt (if secured) and write `frame`, preserving dispatch order. Dropped if `isOpen` is false. * `tapLane` is opaque metadata carried through to the write — the wire-tap seam uses it to label * the frame's lane (a dropped/failed frame never reaches the write, so it is never tapped). */ send(frame: TFrame$1, tapLane?: string): void; /** Decrypt an inbound frame; resolves `undefined` (frame dropped) if decryption fails. */ decryptIncoming(frame: TFrame$1): Promise; } interface IFrameCryptoPipeConfig { /** Raw frame writer — the carrier's `send`, or the acceptor's per-connection send. */ write: (frame: TFrame$1, tapLane?: string) => void; /** Optional synchronous open-guard; when it returns `false`, sends are dropped (a closed carrier). */ isOpen?: () => boolean; /** * The AES-GCM transform, or a promise of it. `undefined` ⇒ plaintext passthrough. A promise lets the * acceptor gate the connection's first frame on an async key re-derivation after a hibernation wake. */ crypto?: IActionFrameCrypto | Promise; /** Short label for the encrypt/decrypt failure logs (e.g. `"link"`, `"ws-server"`). */ label?: string; } declare function createFrameCryptoPipe(config: IFrameCryptoPipeConfig): IFrameCryptoPipe; //#endregion //#region src/wire/utils/runtimeCoordinateToStringIds.d.ts declare function runtimeCoordinateToStringIds(coordinate: IRuntimeCoordinate): TRuntimeCoordinateStringId[]; //#endregion export { IWireTransportInitialized as $, IReliableLogOptions as $n, TWireCarrierSource as $r, establishSecureExchangeSession as $t, ITransportStatusInfo_Failed as A, AcceptorSecureSession as An, IWireLanePort as Ar, _resetReliableDowngradeWarnings as At, IWireExchangeAcceptorLane as B, IAcceptorSecureSessionConfig as Bn, TCarrier as Br, createWireClient as Bt, IInMemoryChannelPair as C, warnReliableStreamKeyUnsupportedOnce as Cn, IWireConnectionStatus_Reconnecting as Cr, WIRE_PROTOCOL_PREFIX as Ct, IRtcDataChannelLike as D, wireSelectionErrors as Dn, IWireFrameProtocol as Dr, WireClient as Dt, IRtcCarrierOptions as E, wireBindingFromAttachment as En, IWireExchangeCarrierSource as Er, WIRE_SUPPORTED_PROTOCOL_VERSIONS as Et, IWireConnectionMethodsBase as F, EWireConnectionStatus as Fn, IWireSecureClientConfig as Fr, createActionFrameCrypto as Ft, IWireInMemoryCarrier as G, IExchangeCarrier as Gn, THsHello as Gr, encodeControlFrame as Gt, IWireExchangeLaneRequest as H, IClientVerifyKeyResolveInput as Hn, TFrame$1 as Hr, decodeExchangeReply as Ht, IWireConnectionParts as I, HANDSHAKE_REJECT_ID_PIN_MISMATCH as In, IWireTapEvent as Ir, createDuplexCarrierLifecycle as It, IWireLinkReadyData as J, IHandshakeEncryptionKeyMaterial as Jn, THsWelcome as Jr, endpointFromConnectFailure as Jt, IWireLinkConnectionOptions as K, IFrameReliability as Kn, THsProve as Kr, encodeExchange as Kt, IWireConnectionPartsOptions as L, HANDSHAKE_REJECT_ID_PROTOCOL_VERSION_MISMATCH as Ln, ReliableInbox as Lr, createExchangeTicketSealer as Lt, ITransportStatusInfo_Ready as M, CAP_RELIABLE_STREAMKEY as Mn, IWireProtocol as Mr, assembleWireConnectionParts as Mt, ITransportStatusInfo_Unsupported as N, EHandshakeMessageType as Nn, IWireProtocolPort as Nr, classifyConnectFailure as Nt, IServeWireOptions as O, wsAcceptorCarrier as On, IWireLaneEndpoint as Or, WireExchangeAcceptor as Ot, IWireClientOptions as P, ESecurityLevel as Pn, IWireRouteInfo as Pr, clientCoordinateFromAttachment as Pt, IWireTransportInitializationFailure as Q, IReliableLogEntry as Qn, TServerDictionaryVersionResolver as Qr, establishSecureDuplexSession as Qt, IWireDuplexSession as R, IAcceptorAuthResult as Rn, ReliableLog as Rr, createFrameCryptoPipe as Rt, IHttpCarrierRequest as S, warnReliablePushUnsupportedOnce as Sn, IWireConnectionStatus_Ready as Sr, WIRE_LANELESS_DICTIONARY_VERSION as St, IInboundFrameLimits as T, webSocketByteChannel as Tn, IWireDuplexCarrierSource as Tr, WIRE_PROTOCOL_VERSION as Tt, IWireExchangeSession as U, IClientVerifyKeyResolver as Un, THandshakeMessage as Ur, decodeExchangeRequest as Ut, IWireExchangeAcceptorOptions as V, IClientHandshakeConfig as Vn, TDialContext as Vr, decodeControlFrame as Vt, IWireHeartbeat as W, IDuplexCarrier as Wn, THsAccept as Wr, describeNonProtocolBody as Wt, IWireTransportDef as X, IReliableInboxOptions as Xn, TRuntimeCoordinateEnvId as Xr, establishPlainDuplexSession as Xt, IWireServer as Y, IHandshakeResult as Yn, TLinkEvent as Yr, err_wire_connect as Yt, IWireTransportDefinition as Z, IReliableInboxResult as Zn, TRuntimeCoordinateStringId as Zr, establishPlainExchangeSession as Zt, IDuplexConnectionRouter as _, withLinkIdTap as _i, serveWire as _n, IWireClientTransport as _r, TWireExchangeRequest as _t, EWireConnectFailureKind as a, WireProtocolMux as ai, peekProtocolPrefix as an, IServerHandshake as ar, SECURITY_LEVEL_RANK as at, IFrameCryptoPipeConfig as b, warnReliableDeliveryAbandonedOnce as bn, IWireConnectionStatus_Connecting as br, UNSET_RUNTIME_ENV_ID as bt, IActionFrameCryptoConfig as c, createMemoryReliableLogStore as ci, protocolsFromCaps as cn, IStorageTofuVerifyKeyResolverOptions as cr, TInboundFrameLimitReason as ct, IControlMessage_ReliableResync as d, createWireAcceptor as di, rtcDataChannelByteChannel as dn, IWireAcceptorOptions as dr, TTransportStatusInfo as dt, TWireConnectionStatus as ei, httpCarrier as en, IReliableLogStore as er, IWireTransportReady as et, IControlMessage_ReliableSkip as f, decodeHandshakeMessage as fi, runtimeCoordinateToStringIds as fn, IWireAcceptorProtocol as fr, TTransportStatusInfo_GetTransport_Output as ft, IDuplexCarrierLifecycle as g, withExchangeTap as gi, sendFrame as gn, IWireClientPair as gr, TWireExchangeReply as gt, IDuplexAcceptorCarrier as h, wireFrameByteSize as hi, securityLevelMeets as hn, IWireClient as hr, TWireExchangeOutcome as ht, ETransportStatus as i, WireAcceptor as ii, lanelessLane as in, IRuntimeFullCoordinates as ir, IWsCarrierRequest as it, ITransportStatusInfo_Initializing as j, CAP_RELIABLE as jn, IWireLaneProtocol as jr, addTransportStatusMetadata as jt, ITransportStatusInfo_Base as k, wsCarrier as kn, IWireLaneHandshakeConfig as kr, WireLinkConnection as kt, IControlMessage_ReliableAck as l, createServerHandshake as li, reliableStreamId as ln, IWireAcceptor as lr, TTransportCache as lt, ICreateWireClientOptions as m, runtimeLinkId as mi, securityLevelFromAttachment as mn, IWireAcceptorSecurity as mr, TWireExchangeLaneReply as mt, DEFAULT_TRANSPORT_TIMEOUT as n, TWireTapFn as ni, isWireConnectionBinding as nn, IRuntimeCoordinate as nr, IWsAcceptorCarrierOptions as nt, IAcceptorAttachmentStore as o, createClientHandshake as oi, protocolCap as on, IServerHandshakeConfig as or, TCarrierFetch as ot, ICreateWireClientBaseOptions as p, encodeHandshakeMessage as pi, sanitizeEndpoint as pn, IWireAcceptorProtocolContext as pr, TWireClientInstance as pt, IWireLinkKeepalive as q, IFrameReliabilityWire as qn, THsReject as qr, encodeProtocolFrame as qt, ETransportShape as r, TWireTapLane as ri, lanelessAcceptorLane as rn, IRuntimeCoordinateSpecifics as rr, IWsCarrierOptions as rt, IActionFrameCrypto as s, createInMemoryTofuVerifyKeyResolver as si, protocolFramePayload as sn, IServerHandshakePending as sr, TControlMessage as st, ConnectionTransportManager as t, TWireOnConnectionBound as ti, inMemoryCarrier as tn, IReliableReceiver as tr, IWireTransportSelectionErrors as tt, IControlMessage_ReliableClose as u, createStorageTofuVerifyKeyResolver as ui, rtcCarrier as un, IWireAcceptorLane as ur, TTransportInitializationFinishedInfo as ut, IExchangeTicketSealer as v, shortWs as vn, IWireConnectionBinding as vr, TWireManagedConnection as vt, IInMemoryServerEndpoint as w, warnReliableWireUnavailableOnce as wn, IWireDialParams as wr, WIRE_PROTOCOL_PREFIX_MAX as wt, IHttpCarrierOptions as x, warnReliablePeerUnsupportedOnce as xn, IWireConnectionStatus_Failed as xr, UNSET_RUNTIME_PER_ID as xt, IFrameCryptoPipe as y, toFrameBytes as yn, IWireConnectionStatus_Base as yr, TransportConnection as yt, IWireDuplexSessionContext as z, IAcceptorSecureResumeState as zn, RuntimeCoordinate as zr, createInMemoryChannelPair as zt }; //# sourceMappingURL=index-BjOE7ujh-P2AQhaRa.d.cts.map