@kyneta/sse-transport 1.5.1 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js.map +1 -1
- package/dist/express.d.ts.map +1 -1
- package/dist/express.js +8 -1
- package/dist/express.js.map +1 -1
- package/dist/{server-transport-C-yuOKEa.js → server-transport-DX3-TbCZ.js} +2 -3
- package/dist/{server-transport-C-yuOKEa.js.map → server-transport-DX3-TbCZ.js.map} +1 -1
- package/dist/server-transport-DXK7KMx4.d.ts.map +1 -1
- package/dist/server.js +1 -1
- package/dist/types-Bg1SdZ2w.d.ts.map +1 -1
- package/package.json +10 -11
- package/src/server-transport.ts +1 -2
package/dist/client.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.ts","names":[],"sources":["../src/client-transport.ts","../src/client-program.ts"],"mappings":";;;;;AAmFA
|
|
1
|
+
{"version":3,"file":"client.d.ts","names":[],"sources":["../src/client-transport.ts","../src/client-program.ts"],"mappings":";;;;;AAmFA;;;;AAAuC;AAAvC,cAAa,0BAAA;;;;UAKI,gBAAA;EA0BH;EAxBZ,OAAA,aAAoB,MAAA,EAAQ,MAAA;EAwBQ;EArBpC,cAAA,aAA2B,MAAA,EAAQ,MAAA;EAHP;EAM5B,SAAA;IACE,OAAA;IACA,WAAA;IACA,SAAA;IACA,QAAA;EAAA;EAFA;EAMF,SAAA;IACE,WAAA;IACA,SAAA;IACA,QAAA;EAAA;EAAA;EAIF,iBAAA;EAGA;EAAA,SAAA,GAAY,wBAAA;AAAA;AAAwB;AAmBtC;;AAnBsC,KAmB1B,wBAAA,GAA2B,iBAAe,CAAC,cAAA;;AAAc;AAiCrE;;;;;;;;;;;;;;;;;;;;;;;;;cAAa,kBAAA,SAA2B,SAAA;EAAA;cAwB1B,OAAA,EAAS,gBAAA;EAyMU;;;EAR/B,QAAA,CAAA,GAAY,cAAA;EAiBE;;;EAVd,sBAAA,CACE,QAAA,EAAU,oBAAA,CAAmB,cAAA;EAW5B;;;EAHH,YAAA,CACE,SAAA,GAAY,KAAA,EAAO,cAAA,cACnB,OAAA;IAAY,SAAA;EAAA,IACX,OAAA,CAAQ,cAAA;EAST;;;EAFF,aAAA,CACE,MAAA,EAAQ,cAAA,YACR,OAAA;IAAY,SAAA;EAAA,IACX,OAAA,CAAQ,cAAA;EA4EL;;;EAAA,IArEF,WAAA,CAAA;EAAA,UAQM,QAAA,CAAA,GAAY,gBAAA;EA6DhB,OAAA,CAAA,GAAW,OAAA;EAUX,MAAA,CAAA,GAAU,OAAA;AAAA;;;;;;;AAwL0D;;;;ACvpB5E;;;;;;iBDupBgB,eAAA,CAAgB,OAAA,EAAS,gBAAA,GAAmB,gBAAgB;;;KCvpBhE,YAAA;EACN,IAAA;AAAA;EACA,IAAA;AAAA;EACA,IAAA;AAAA;EACA,IAAA;AAAA;EACA,IAAA;AAAA;AAAA,KAMM,eAAA;EACN,IAAA;EAA6B,GAAA;EAAa,OAAA;AAAA;EAC1C,IAAA;AAAA;EACA,IAAA;AAAA;EACA,IAAA;AAAA;EACA,IAAA;EAA+B,OAAA;AAAA;EAC/B,IAAA;AAAA;EACA,IAAA;AAAA;AAAA,UAMW,uBAAA;EACf,GAAA;EACA,SAAA,GAAY,OAAO,CAAC,gBAAA;EDqER;ECnEZ,QAAA;AAAA;ADsFF;;;;AAAqE;AAiCrE;;AAjCA,iBC5EgB,sBAAA,CACd,OAAA,EAAS,uBAAA,GACR,OAAA,CAAQ,YAAA,EAAc,cAAA,EAAgB,eAAA"}
|
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","names":["#fragmentThreshold","#reassembler","#options","#handle","#executeEffect","#setupLifecycleEvents","#doCreateEventSource","#eventSource","#serverChannel","#reconnectTimer","#currentRetryAbortController","#peerId","#handleMessage","#aliasState","#sendTextWithRetry"],"sources":["../src/client-program.ts","../src/client-transport.ts"],"sourcesContent":["// client-program — pure Mealy machine for SSE client connection lifecycle.\n//\n// The client program encodes every state transition and effect as data.\n// The imperative shell (client-transport.ts) interprets effects as I/O.\n// Tests assert on data — no EventSource, no timing, never flaky.\n//\n// Algebra: Program<SseClientMsg, SseClientState, SseClientEffect>\n// Interpreter: client-transport.ts executeClientEffect()\n\nimport type { Program } from \"@kyneta/machine\"\nimport type { ReconnectOptions } from \"@kyneta/transport\"\nimport { computeBackoffDelay, DEFAULT_RECONNECT } from \"@kyneta/transport\"\n\nimport type { DisconnectReason, SseClientState } from \"./types.js\"\n\n// ---------------------------------------------------------------------------\n// Messages\n// ---------------------------------------------------------------------------\n\nexport type SseClientMsg =\n | { type: \"start\" }\n | { type: \"event-source-opened\" }\n | { type: \"event-source-error\" }\n | { type: \"stop\" }\n | { type: \"reconnect-timer-fired\" }\n\n// ---------------------------------------------------------------------------\n// Effects (data — interpreted by the imperative shell)\n// ---------------------------------------------------------------------------\n\nexport type SseClientEffect =\n | { type: \"create-event-source\"; url: string; attempt: number }\n | { type: \"close-event-source\" }\n | { type: \"add-channel-and-establish\" }\n | { type: \"remove-channel\" }\n | { type: \"start-reconnect-timer\"; delayMs: number }\n | { type: \"cancel-reconnect-timer\" }\n | { type: \"abort-pending-posts\" }\n\n// ---------------------------------------------------------------------------\n// Program factory\n// ---------------------------------------------------------------------------\n\nexport interface SseClientProgramOptions {\n url: string\n reconnect?: Partial<ReconnectOptions>\n /** Inject jitter source for deterministic testing. Default: () => Math.random() * 1000 */\n jitterFn?: () => number\n}\n\n/**\n * Create the SSE client connection lifecycle program — a pure Mealy machine.\n *\n * The returned `Program<SseClientMsg, SseClientState, SseClientEffect>`\n * encodes every state transition and effect as inspectable data. The imperative\n * shell interprets `SseClientEffect` as actual I/O.\n */\nexport function createSseClientProgram(\n options: SseClientProgramOptions,\n): Program<SseClientMsg, SseClientState, SseClientEffect> {\n const { url, jitterFn = () => Math.random() * 1000 } = options\n const reconnect: ReconnectOptions = {\n ...DEFAULT_RECONNECT,\n ...options.reconnect,\n }\n\n /**\n * Attempt to transition into reconnecting, or give up and disconnect.\n *\n * Pure — computes the next state and effects from the current attempt\n * count and reconnect configuration. Returns a tuple suitable for\n * spreading into an `update` return.\n */\n function tryReconnect(\n currentAttempt: number,\n reason: DisconnectReason,\n ...extraEffects: SseClientEffect[]\n ): [SseClientState, ...SseClientEffect[]] {\n if (!reconnect.enabled) {\n return [{ status: \"disconnected\", reason }, ...extraEffects]\n }\n\n if (currentAttempt >= reconnect.maxAttempts) {\n return [\n {\n status: \"disconnected\",\n reason: { type: \"max-retries-exceeded\", attempts: currentAttempt },\n },\n ...extraEffects,\n ]\n }\n\n const delay = computeBackoffDelay(\n currentAttempt + 1,\n reconnect.baseDelay,\n reconnect.maxDelay,\n jitterFn(),\n )\n\n return [\n {\n status: \"reconnecting\",\n attempt: currentAttempt + 1,\n nextAttemptMs: delay,\n },\n ...extraEffects,\n { type: \"start-reconnect-timer\", delayMs: delay },\n ]\n }\n\n return {\n init: [{ status: \"disconnected\" }],\n\n update(msg, model): [SseClientState, ...SseClientEffect[]] {\n switch (msg.type) {\n // -----------------------------------------------------------------\n // start\n // -----------------------------------------------------------------\n case \"start\": {\n if (model.status !== \"disconnected\") return [model]\n return [\n { status: \"connecting\", attempt: 1 },\n { type: \"create-event-source\", url, attempt: 1 },\n ]\n }\n\n // -----------------------------------------------------------------\n // event-source-opened\n // -----------------------------------------------------------------\n case \"event-source-opened\": {\n if (model.status !== \"connecting\") return [model]\n return [\n { status: \"connected\" },\n { type: \"add-channel-and-establish\" },\n ]\n }\n\n // -----------------------------------------------------------------\n // event-source-error\n // -----------------------------------------------------------------\n case \"event-source-error\": {\n const reason: DisconnectReason = {\n type: \"error\",\n error: new Error(\"EventSource connection error\"),\n }\n\n if (model.status === \"connecting\") {\n return tryReconnect(model.attempt, reason, {\n type: \"close-event-source\",\n })\n }\n\n if (model.status === \"connected\") {\n return tryReconnect(\n 0,\n reason,\n { type: \"remove-channel\" },\n { type: \"close-event-source\" },\n { type: \"abort-pending-posts\" },\n )\n }\n\n return [model]\n }\n\n // -----------------------------------------------------------------\n // reconnect-timer-fired\n // -----------------------------------------------------------------\n case \"reconnect-timer-fired\": {\n if (model.status !== \"reconnecting\") return [model]\n return [\n { status: \"connecting\", attempt: model.attempt },\n { type: \"create-event-source\", url, attempt: model.attempt },\n ]\n }\n\n // -----------------------------------------------------------------\n // stop\n // -----------------------------------------------------------------\n case \"stop\": {\n if (model.status === \"disconnected\") return [model]\n\n const effects: SseClientEffect[] = [\n { type: \"cancel-reconnect-timer\" },\n ]\n\n if (model.status === \"connecting\") {\n effects.push({ type: \"close-event-source\" })\n }\n\n if (model.status === \"connected\") {\n effects.push(\n { type: \"close-event-source\" },\n { type: \"remove-channel\" },\n { type: \"abort-pending-posts\" },\n )\n }\n\n return [\n { status: \"disconnected\", reason: { type: \"intentional\" } },\n ...effects,\n ]\n }\n }\n },\n }\n}\n","// client-transport — SSE client transport for @kyneta/exchange.\n//\n// Thin imperative shell around the pure client program (client-program.ts).\n// The program produces data effects; this module interprets them as I/O.\n//\n// FC/IS design:\n// - client-program.ts: pure Mealy machine (functional core)\n// - client-transport.ts: effect executor (imperative shell)\n//\n// Uses two HTTP channels:\n// - EventSource (GET) for server→client messages\n// - fetch POST for client→server messages\n//\n// Both directions use the alias-aware text pipeline.\n//\n// Features:\n// - Pure Mealy machine for connection lifecycle (client-program.ts)\n// - Exponential backoff reconnection with jitter\n// - POST retry with exponential backoff\n// - Text-level fragmentation for large payloads\n// - Inbound TextReassembler for fragmented SSE messages\n// - Observable connection state via subscribeToTransitions()\n//\n// The connection handshake:\n// 1. Client creates EventSource, waits for open\n// 2. EventSource.onopen fires → client creates channel + calls establishChannel()\n// 3. Synchronizer exchanges establish messages via POST + SSE\n//\n// On EventSource.onerror, the adapter closes the EventSource immediately and\n// takes over reconnection via the program's backoff logic, rather than\n// letting the browser's built-in EventSource reconnection run.\n\nimport type {\n ObservableHandle,\n StateTransition,\n TransitionListener,\n} from \"@kyneta/machine\"\nimport { createObservableProgram } from \"@kyneta/machine\"\nimport type {\n Channel,\n ChannelMsg,\n GeneratedChannel,\n PeerId,\n TransportFactory,\n} from \"@kyneta/transport\"\nimport { Transport } from \"@kyneta/transport\"\nimport {\n type AliasState,\n applyInboundAliasing,\n applyOutboundAliasing,\n complete,\n createFrameIdCounter,\n decodeTextWires,\n emptyAliasState,\n encodeTextFrame,\n encodeTextWireMessage,\n fragmentTextPayload,\n TEXT_WIRE_VERSION,\n TextReassembler,\n} from \"@kyneta/wire\"\nimport {\n createSseClientProgram,\n type SseClientEffect,\n type SseClientMsg,\n} from \"./client-program.js\"\nimport type {\n DisconnectReason,\n SseClientLifecycleEvents,\n SseClientState,\n} from \"./types.js\"\n\n// Re-export state types for convenience\nexport type { DisconnectReason, SseClientLifecycleEvents, SseClientState }\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\n/**\n * Default fragment threshold in characters.\n * 60K chars provides a safety margin below typical 100KB body-parser limits,\n * accounting for JSON overhead and potential base64 expansion.\n */\nexport const DEFAULT_FRAGMENT_THRESHOLD = 60_000\n\n/**\n * Options for the SSE client adapter.\n */\nexport interface SseClientOptions {\n /** URL for POST requests (client→server). String or function of peerId. */\n postUrl: string | ((peerId: PeerId) => string)\n\n /** URL for SSE EventSource (server→client). String or function of peerId. */\n eventSourceUrl: string | ((peerId: PeerId) => string)\n\n /** Reconnection options for EventSource. */\n reconnect?: {\n enabled?: boolean\n maxAttempts?: number\n baseDelay?: number\n maxDelay?: number\n }\n\n /** POST retry options. */\n postRetry?: {\n maxAttempts?: number\n baseDelay?: number\n maxDelay?: number\n }\n\n /** Fragment threshold in characters. Default: 60000 (60K chars). */\n fragmentThreshold?: number\n\n /** Lifecycle event callbacks. */\n lifecycle?: SseClientLifecycleEvents\n}\n\n/**\n * Default POST retry options.\n */\nconst DEFAULT_POST_RETRY = {\n maxAttempts: 3,\n baseDelay: 1000,\n maxDelay: 10000,\n}\n\n// ---------------------------------------------------------------------------\n// State transition type alias\n// ---------------------------------------------------------------------------\n\n/**\n * State transition event for SSE client states.\n */\nexport type SseClientStateTransition = StateTransition<SseClientState>\n\n// ---------------------------------------------------------------------------\n// SseClientTransport\n// ---------------------------------------------------------------------------\n\n/**\n * SSE client network adapter for @kyneta/exchange.\n *\n * Uses two HTTP channels:\n * - **EventSource** (GET, long-lived) for server→client messages\n * - **fetch POST** for client→server messages\n *\n * Both directions use the alias-aware text pipeline.\n *\n * Internally, the connection lifecycle is a `Program<Msg, Model, Fx>` —\n * a pure Mealy machine whose transitions are deterministically testable.\n * This class is the imperative shell that interprets data effects as I/O.\n *\n * @example\n * ```typescript\n * import { createSseClient } from \"@kyneta/sse-transport/client\"\n *\n * const exchange = new Exchange({\n * id: \"browser-client\",\n * transports: [createSseClient({\n * postUrl: \"/sync\",\n * eventSourceUrl: (peerId) => `/events?peerId=${peerId}`,\n * reconnect: { enabled: true },\n * })],\n * })\n * ```\n */\nexport class SseClientTransport extends Transport<void> {\n #peerId?: PeerId\n #options: SseClientOptions\n\n // Observable program handle — created in onStart(), drives all state\n #handle: ObservableHandle<SseClientMsg, SseClientState>\n\n // Executor-local I/O state — not in the program model\n #eventSource?: EventSource\n #serverChannel?: Channel\n #reconnectTimer?: ReturnType<typeof setTimeout>\n\n // Fragmentation\n readonly #fragmentThreshold: number\n\n // Alias-aware pipeline state — tracks alias bindings per connection\n #aliasState: AliasState = emptyAliasState()\n\n // Inbound reassembly for fragmented SSE messages from server\n readonly #reassembler: TextReassembler\n\n // POST retry\n #currentRetryAbortController?: AbortController\n\n constructor(options: SseClientOptions) {\n super({ transportType: \"sse-client\" })\n this.#options = options\n this.#fragmentThreshold =\n options.fragmentThreshold ?? DEFAULT_FRAGMENT_THRESHOLD\n this.#reassembler = new TextReassembler({\n timeoutMs: 10_000,\n })\n\n // Create the program with a placeholder URL — the executor resolves the\n // real eventSourceUrl (which may be a function of peerId) at effect time.\n // The URL in the program is used only as a marker; the executor overrides it.\n const program = createSseClientProgram({\n url: \"__deferred__\",\n reconnect: options.reconnect,\n })\n\n this.#handle = createObservableProgram(program, (effect, dispatch) => {\n this.#executeEffect(effect, dispatch)\n })\n\n // Set up lifecycle event forwarding\n this.#setupLifecycleEvents()\n }\n\n // ==========================================================================\n // Lifecycle event forwarding\n // ==========================================================================\n\n /**\n * Subscribe to the observable handle's transitions and forward them to\n * the lifecycle callbacks. `wasConnectedBefore` is observer-local state,\n * not in the program model.\n */\n #setupLifecycleEvents(): void {\n let wasConnectedBefore = false\n\n this.#handle.subscribeToTransitions(transition => {\n // Forward to onStateChange callback\n this.#options.lifecycle?.onStateChange?.(transition)\n\n const { from, to } = transition\n\n // onDisconnect: transitioning TO disconnected\n if (to.status === \"disconnected\" && to.reason) {\n this.#options.lifecycle?.onDisconnect?.(to.reason)\n }\n\n // onReconnecting: transitioning TO reconnecting\n if (to.status === \"reconnecting\") {\n this.#options.lifecycle?.onReconnecting?.(to.attempt, to.nextAttemptMs)\n }\n\n // onReconnected: from reconnecting/connecting TO connected (after prior connection)\n if (\n wasConnectedBefore &&\n (from.status === \"reconnecting\" || from.status === \"connecting\") &&\n to.status === \"connected\"\n ) {\n this.#options.lifecycle?.onReconnected?.()\n }\n\n // Track whether we've ever been connected\n if (to.status === \"connected\") {\n wasConnectedBefore = true\n }\n\n // Reset on intentional disconnect (stop)\n if (to.status === \"disconnected\" && to.reason?.type === \"intentional\") {\n wasConnectedBefore = false\n }\n })\n }\n\n // ==========================================================================\n // Effect executor — interprets data effects as I/O\n // ==========================================================================\n\n #executeEffect(\n effect: SseClientEffect,\n dispatch: (msg: SseClientMsg) => void,\n ): void {\n switch (effect.type) {\n case \"create-event-source\": {\n this.#doCreateEventSource(dispatch)\n break\n }\n\n case \"close-event-source\": {\n if (this.#eventSource) {\n this.#eventSource.onopen = null\n this.#eventSource.onmessage = null\n this.#eventSource.onerror = null\n this.#eventSource.close()\n this.#eventSource = undefined\n }\n break\n }\n\n case \"add-channel-and-establish\": {\n // Remove any stale channel from a previous connection\n if (this.#serverChannel) {\n this.removeChannel(this.#serverChannel.channelId)\n this.#serverChannel = undefined\n }\n\n // Fresh reassembler for the new connection — stale fragments from\n // the old connection must not collide with new fragments.\n this.#reassembler.reset()\n\n this.#serverChannel = this.addChannel()\n\n // No \"ready\" handshake — establish immediately\n this.establishChannel(this.#serverChannel.channelId)\n break\n }\n\n case \"remove-channel\": {\n if (this.#serverChannel) {\n this.removeChannel(this.#serverChannel.channelId)\n this.#serverChannel = undefined\n }\n break\n }\n\n case \"start-reconnect-timer\": {\n this.#reconnectTimer = setTimeout(() => {\n this.#reconnectTimer = undefined\n dispatch({ type: \"reconnect-timer-fired\" })\n }, effect.delayMs)\n break\n }\n\n case \"cancel-reconnect-timer\": {\n if (this.#reconnectTimer !== undefined) {\n clearTimeout(this.#reconnectTimer)\n this.#reconnectTimer = undefined\n }\n break\n }\n\n case \"abort-pending-posts\": {\n if (this.#currentRetryAbortController) {\n this.#currentRetryAbortController.abort()\n this.#currentRetryAbortController = undefined\n }\n break\n }\n }\n }\n\n /**\n * Create an EventSource and wire up event handlers.\n * The URL is resolved here (may be a function of peerId).\n */\n #doCreateEventSource(dispatch: (msg: SseClientMsg) => void): void {\n if (!this.#peerId) {\n throw new Error(\"Cannot connect: peerId not set\")\n }\n\n // Resolve URL — may be a string or function of peerId\n const url =\n typeof this.#options.eventSourceUrl === \"function\"\n ? this.#options.eventSourceUrl(this.#peerId)\n : this.#options.eventSourceUrl\n\n try {\n this.#eventSource = new EventSource(url)\n\n this.#eventSource.onopen = () => {\n dispatch({ type: \"event-source-opened\" })\n }\n\n this.#eventSource.onmessage = (event: MessageEvent) => {\n this.#handleMessage(event)\n }\n\n this.#eventSource.onerror = () => {\n dispatch({ type: \"event-source-error\" })\n }\n } catch (_error) {\n // EventSource constructor threw (e.g. invalid URL) — treat as error\n dispatch({ type: \"event-source-error\" })\n }\n }\n\n // ==========================================================================\n // State observation — delegated to the observable handle\n // ==========================================================================\n\n /**\n * Get the current connection state.\n */\n getState(): SseClientState {\n return this.#handle.getState()\n }\n\n /**\n * Subscribe to state transitions.\n */\n subscribeToTransitions(\n listener: TransitionListener<SseClientState>,\n ): () => void {\n return this.#handle.subscribeToTransitions(listener)\n }\n\n /**\n * Wait for a specific state.\n */\n waitForState(\n predicate: (state: SseClientState) => boolean,\n options?: { timeoutMs?: number },\n ): Promise<SseClientState> {\n return this.#handle.waitForState(predicate, options)\n }\n\n /**\n * Wait for a specific status.\n */\n waitForStatus(\n status: SseClientState[\"status\"],\n options?: { timeoutMs?: number },\n ): Promise<SseClientState> {\n return this.#handle.waitForStatus(status, options)\n }\n\n /**\n * Whether the client is connected and ready to send/receive.\n */\n get isConnected(): boolean {\n return this.#handle.getState().status === \"connected\"\n }\n\n // ==========================================================================\n // Transport abstract method implementations\n // ==========================================================================\n\n protected generate(): GeneratedChannel {\n const nextFrameId = createFrameIdCounter()\n // New channel = fresh alias state; reset on (re)connect.\n this.#aliasState = emptyAliasState()\n return {\n transportType: this.transportType,\n send: (msg: ChannelMsg) => {\n if (!this.#peerId) {\n return\n }\n\n // Check if EventSource is closed before sending\n // readyState: 0=CONNECTING, 1=OPEN, 2=CLOSED\n if (!this.#eventSource || this.#eventSource.readyState === 2) {\n return\n }\n\n // Resolve the postUrl with the peerId\n const resolvedPostUrl =\n typeof this.#options.postUrl === \"function\"\n ? this.#options.postUrl(this.#peerId)\n : this.#options.postUrl\n\n // Alias-aware outbound: ChannelMsg → AliasWireMessage\n const { state: nextState, wire } = applyOutboundAliasing(\n this.#aliasState,\n msg,\n )\n this.#aliasState = nextState\n\n // AliasWireMessage → JSON-safe object → JSON string\n const payload = JSON.stringify(encodeTextWireMessage(wire))\n\n // JSON string → text frame\n const textFrame = encodeTextFrame(complete(TEXT_WIRE_VERSION, payload))\n\n // Fragment large payloads\n if (\n this.#fragmentThreshold > 0 &&\n textFrame.length > this.#fragmentThreshold\n ) {\n const fragments = fragmentTextPayload(\n payload,\n this.#fragmentThreshold,\n nextFrameId(),\n )\n for (const fragment of fragments) {\n void this.#sendTextWithRetry(resolvedPostUrl, fragment)\n }\n } else {\n void this.#sendTextWithRetry(resolvedPostUrl, textFrame)\n }\n },\n stop: () => {\n // Don't call disconnect here — channel.stop() is called when\n // the channel is removed, which can happen during effect execution.\n // The actual disconnect is handled by onStop() or the program.\n },\n }\n }\n\n async onStart(): Promise<void> {\n if (!this.identity) {\n throw new Error(\n \"Adapter not properly initialized — identity not available\",\n )\n }\n this.#peerId = this.identity.peerId\n this.#handle.dispatch({ type: \"start\" })\n }\n\n async onStop(): Promise<void> {\n this.#reassembler.dispose()\n this.#handle.dispatch({ type: \"stop\" })\n }\n\n // ==========================================================================\n // Inbound message handling\n // ==========================================================================\n\n /**\n * Handle incoming SSE message.\n *\n * Each SSE `data:` event contains a text wire frame string.\n * Feed it through the TextReassembler, then through the alias-aware\n * inbound pipeline to resolve aliases and deliver ChannelMsgs.\n */\n #handleMessage(event: MessageEvent): void {\n if (!this.#serverChannel) {\n return\n }\n\n const data = event.data\n if (typeof data !== \"string\") {\n return\n }\n\n // Text wire → AliasWireMessage[] (complete batches only)\n const wires = decodeTextWires(this.#reassembler, data)\n if (!wires) {\n // Still assembling fragments, or reassembly error already logged\n return\n }\n\n for (const wire of wires) {\n const result = applyInboundAliasing(this.#aliasState, wire)\n this.#aliasState = result.state\n if (result.error || !result.msg) {\n console.warn(\"[sse-client] alias resolution failed:\", result.error)\n continue\n }\n this.#serverChannel?.onReceive(result.msg)\n }\n }\n\n // ==========================================================================\n // POST sending with retry\n // ==========================================================================\n\n /**\n * Send a text frame via POST with retry logic.\n */\n async #sendTextWithRetry(url: string, textFrame: string): Promise<void> {\n let attempt = 0\n const postRetryOpts = {\n ...DEFAULT_POST_RETRY,\n ...this.#options.postRetry,\n }\n const { maxAttempts, baseDelay, maxDelay } = postRetryOpts\n\n while (attempt < maxAttempts) {\n try {\n if (!this.#currentRetryAbortController) {\n this.#currentRetryAbortController = new AbortController()\n }\n\n if (!this.#peerId) {\n throw new Error(\"PeerId not available for retry\")\n }\n\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"text/plain\",\n \"X-Peer-Id\": this.#peerId,\n },\n body: textFrame,\n signal: this.#currentRetryAbortController.signal,\n })\n\n if (!response.ok) {\n // Don't retry on client errors (4xx)\n if (response.status >= 400 && response.status < 500) {\n throw new Error(`Failed to send message: ${response.statusText}`)\n }\n throw new Error(`Server error: ${response.statusText}`)\n }\n\n // Success\n this.#currentRetryAbortController = undefined\n return\n } catch (error: unknown) {\n attempt++\n\n const err = error as Error\n\n // If aborted, stop retrying\n if (err.name === \"AbortError\") {\n throw error\n }\n\n // If controller was cleared (e.g. by abort-pending-posts effect), stop retrying\n if (!this.#currentRetryAbortController) {\n const abortError = new Error(\"Retry aborted by connection reset\")\n abortError.name = \"AbortError\"\n throw abortError\n }\n\n // If max attempts reached, log and stop — don't throw.\n // The send callback is synchronous and uses `void`, so\n // a throw here would be an unhandled promise rejection.\n if (attempt >= maxAttempts) {\n this.#currentRetryAbortController = undefined\n console.error(\n `[SseClientTransport] Failed to send message after ${attempt} attempts:`,\n (error as Error).message,\n )\n return\n }\n\n // Calculate delay with exponential backoff and jitter\n const delay = Math.min(\n baseDelay * 2 ** (attempt - 1) + Math.random() * 100,\n maxDelay,\n )\n\n // Wait for delay or abort signal\n await new Promise<void>((resolve, reject) => {\n if (this.#currentRetryAbortController?.signal.aborted) {\n const error = new Error(\"Retry aborted\")\n error.name = \"AbortError\"\n reject(error)\n return\n }\n\n const timer = setTimeout(() => {\n cleanup()\n resolve()\n }, delay)\n\n const onAbort = () => {\n clearTimeout(timer)\n cleanup()\n const error = new Error(\"Retry aborted\")\n error.name = \"AbortError\"\n reject(error)\n }\n\n const cleanup = () => {\n this.#currentRetryAbortController?.signal.removeEventListener(\n \"abort\",\n onAbort,\n )\n }\n\n this.#currentRetryAbortController?.signal.addEventListener(\n \"abort\",\n onAbort,\n )\n })\n }\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Factory function\n// ---------------------------------------------------------------------------\n\n/**\n * Create an SSE client adapter for browser-to-server connections.\n *\n * @example\n * ```typescript\n * import { createSseClient } from \"@kyneta/sse-transport/client\"\n *\n * const exchange = new Exchange({\n * transports: [createSseClient({\n * postUrl: \"/sync\",\n * eventSourceUrl: (peerId) => `/events?peerId=${peerId}`,\n * reconnect: { enabled: true },\n * })],\n * })\n * ```\n */\nexport function createSseClient(options: SseClientOptions): TransportFactory {\n return () => new SseClientTransport(options)\n}\n"],"mappings":";;;;;;;;;;;AAyDA,SAAgB,uBACd,SACwD;CACxD,MAAM,EAAE,KAAK,iBAAiB,KAAK,QAAQ,GAAG,QAAS;CACvD,MAAM,YAA8B;EAClC,GAAG;EACH,GAAG,QAAQ;EACZ;;;;;;;;CASD,SAAS,aACP,gBACA,QACA,GAAG,cACqC;AACxC,MAAI,CAAC,UAAU,QACb,QAAO,CAAC;GAAE,QAAQ;GAAgB;GAAQ,EAAE,GAAG,aAAa;AAG9D,MAAI,kBAAkB,UAAU,YAC9B,QAAO,CACL;GACE,QAAQ;GACR,QAAQ;IAAE,MAAM;IAAwB,UAAU;IAAgB;GACnE,EACD,GAAG,aACJ;EAGH,MAAM,QAAQ,oBACZ,iBAAiB,GACjB,UAAU,WACV,UAAU,UACV,UAAU,CACX;AAED,SAAO;GACL;IACE,QAAQ;IACR,SAAS,iBAAiB;IAC1B,eAAe;IAChB;GACD,GAAG;GACH;IAAE,MAAM;IAAyB,SAAS;IAAO;GAClD;;AAGH,QAAO;EACL,MAAM,CAAC,EAAE,QAAQ,gBAAgB,CAAC;EAElC,OAAO,KAAK,OAA+C;AACzD,WAAQ,IAAI,MAAZ;IAIE,KAAK;AACH,SAAI,MAAM,WAAW,eAAgB,QAAO,CAAC,MAAM;AACnD,YAAO,CACL;MAAE,QAAQ;MAAc,SAAS;MAAG,EACpC;MAAE,MAAM;MAAuB;MAAK,SAAS;MAAG,CACjD;IAMH,KAAK;AACH,SAAI,MAAM,WA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,UAAU,KAAK,KAAK,QAAQ,GAAG,KACjD,SACD;AAGD,SAAM,IAAI,SAAe,SAAS,WAAW;AAC3C,QAAI,MAAA,6BAAmC,OAAO,SAAS;KACrD,MAAM,wBAAQ,IAAI,MAAM,gBAAgB;AACxC,WAAM,OAAO;AACb,YAAO,MAAM;AACb;;IAGF,MAAM,QAAQ,iBAAiB;AAC7B,cAAS;AACT,cAAS;OACR,MAAM;IAET,MAAM,gBAAgB;AACpB,kBAAa,MAAM;AACnB,cAAS;KACT,MAAM,wBAAQ,IAAI,MAAM,gBAAgB;AACxC,WAAM,OAAO;AACb,YAAO,MAAM;;IAGf,MAAM,gBAAgB;AACpB,WAAA,6BAAmC,OAAO,oBACxC,SACA,QACD;;AAGH,UAAA,6BAAmC,OAAO,iBACxC,SACA,QACD;KACD;;;;;;;;;;;;;;;;;;;;AA0BV,SAAgB,gBAAgB,SAA6C;AAC3E,cAAa,IAAI,mBAAmB,QAAQ"}
|
|
1
|
+
{"version":3,"file":"client.js","names":["#fragmentThreshold","#reassembler","#options","#handle","#executeEffect","#setupLifecycleEvents","#doCreateEventSource","#eventSource","#serverChannel","#reconnectTimer","#currentRetryAbortController","#peerId","#handleMessage","#aliasState","#sendTextWithRetry","err"],"sources":["../src/client-program.ts","../src/client-transport.ts"],"sourcesContent":["// client-program — pure Mealy machine for SSE client connection lifecycle.\n//\n// The client program encodes every state transition and effect as data.\n// The imperative shell (client-transport.ts) interprets effects as I/O.\n// Tests assert on data — no EventSource, no timing, never flaky.\n//\n// Algebra: Program<SseClientMsg, SseClientState, SseClientEffect>\n// Interpreter: client-transport.ts executeClientEffect()\n\nimport type { Program } from \"@kyneta/machine\"\nimport type { ReconnectOptions } from \"@kyneta/transport\"\nimport { computeBackoffDelay, DEFAULT_RECONNECT } from \"@kyneta/transport\"\n\nimport type { DisconnectReason, SseClientState } from \"./types.js\"\n\n// ---------------------------------------------------------------------------\n// Messages\n// ---------------------------------------------------------------------------\n\nexport type SseClientMsg =\n | { type: \"start\" }\n | { type: \"event-source-opened\" }\n | { type: \"event-source-error\" }\n | { type: \"stop\" }\n | { type: \"reconnect-timer-fired\" }\n\n// ---------------------------------------------------------------------------\n// Effects (data — interpreted by the imperative shell)\n// ---------------------------------------------------------------------------\n\nexport type SseClientEffect =\n | { type: \"create-event-source\"; url: string; attempt: number }\n | { type: \"close-event-source\" }\n | { type: \"add-channel-and-establish\" }\n | { type: \"remove-channel\" }\n | { type: \"start-reconnect-timer\"; delayMs: number }\n | { type: \"cancel-reconnect-timer\" }\n | { type: \"abort-pending-posts\" }\n\n// ---------------------------------------------------------------------------\n// Program factory\n// ---------------------------------------------------------------------------\n\nexport interface SseClientProgramOptions {\n url: string\n reconnect?: Partial<ReconnectOptions>\n /** Inject jitter source for deterministic testing. Default: () => Math.random() * 1000 */\n jitterFn?: () => number\n}\n\n/**\n * Create the SSE client connection lifecycle program — a pure Mealy machine.\n *\n * The returned `Program<SseClientMsg, SseClientState, SseClientEffect>`\n * encodes every state transition and effect as inspectable data. The imperative\n * shell interprets `SseClientEffect` as actual I/O.\n */\nexport function createSseClientProgram(\n options: SseClientProgramOptions,\n): Program<SseClientMsg, SseClientState, SseClientEffect> {\n const { url, jitterFn = () => Math.random() * 1000 } = options\n const reconnect: ReconnectOptions = {\n ...DEFAULT_RECONNECT,\n ...options.reconnect,\n }\n\n /**\n * Attempt to transition into reconnecting, or give up and disconnect.\n *\n * Pure — computes the next state and effects from the current attempt\n * count and reconnect configuration. Returns a tuple suitable for\n * spreading into an `update` return.\n */\n function tryReconnect(\n currentAttempt: number,\n reason: DisconnectReason,\n ...extraEffects: SseClientEffect[]\n ): [SseClientState, ...SseClientEffect[]] {\n if (!reconnect.enabled) {\n return [{ status: \"disconnected\", reason }, ...extraEffects]\n }\n\n if (currentAttempt >= reconnect.maxAttempts) {\n return [\n {\n status: \"disconnected\",\n reason: { type: \"max-retries-exceeded\", attempts: currentAttempt },\n },\n ...extraEffects,\n ]\n }\n\n const delay = computeBackoffDelay(\n currentAttempt + 1,\n reconnect.baseDelay,\n reconnect.maxDelay,\n jitterFn(),\n )\n\n return [\n {\n status: \"reconnecting\",\n attempt: currentAttempt + 1,\n nextAttemptMs: delay,\n },\n ...extraEffects,\n { type: \"start-reconnect-timer\", delayMs: delay },\n ]\n }\n\n return {\n init: [{ status: \"disconnected\" }],\n\n update(msg, model): [SseClientState, ...SseClientEffect[]] {\n switch (msg.type) {\n // -----------------------------------------------------------------\n // start\n // -----------------------------------------------------------------\n case \"start\": {\n if (model.status !== \"disconnected\") return [model]\n return [\n { status: \"connecting\", attempt: 1 },\n { type: \"create-event-source\", url, attempt: 1 },\n ]\n }\n\n // -----------------------------------------------------------------\n // event-source-opened\n // -----------------------------------------------------------------\n case \"event-source-opened\": {\n if (model.status !== \"connecting\") return [model]\n return [\n { status: \"connected\" },\n { type: \"add-channel-and-establish\" },\n ]\n }\n\n // -----------------------------------------------------------------\n // event-source-error\n // -----------------------------------------------------------------\n case \"event-source-error\": {\n const reason: DisconnectReason = {\n type: \"error\",\n error: new Error(\"EventSource connection error\"),\n }\n\n if (model.status === \"connecting\") {\n return tryReconnect(model.attempt, reason, {\n type: \"close-event-source\",\n })\n }\n\n if (model.status === \"connected\") {\n return tryReconnect(\n 0,\n reason,\n { type: \"remove-channel\" },\n { type: \"close-event-source\" },\n { type: \"abort-pending-posts\" },\n )\n }\n\n return [model]\n }\n\n // -----------------------------------------------------------------\n // reconnect-timer-fired\n // -----------------------------------------------------------------\n case \"reconnect-timer-fired\": {\n if (model.status !== \"reconnecting\") return [model]\n return [\n { status: \"connecting\", attempt: model.attempt },\n { type: \"create-event-source\", url, attempt: model.attempt },\n ]\n }\n\n // -----------------------------------------------------------------\n // stop\n // -----------------------------------------------------------------\n case \"stop\": {\n if (model.status === \"disconnected\") return [model]\n\n const effects: SseClientEffect[] = [\n { type: \"cancel-reconnect-timer\" },\n ]\n\n if (model.status === \"connecting\") {\n effects.push({ type: \"close-event-source\" })\n }\n\n if (model.status === \"connected\") {\n effects.push(\n { type: \"close-event-source\" },\n { type: \"remove-channel\" },\n { type: \"abort-pending-posts\" },\n )\n }\n\n return [\n { status: \"disconnected\", reason: { type: \"intentional\" } },\n ...effects,\n ]\n }\n }\n },\n }\n}\n","// client-transport — SSE client transport for @kyneta/exchange.\n//\n// Thin imperative shell around the pure client program (client-program.ts).\n// The program produces data effects; this module interprets them as I/O.\n//\n// FC/IS design:\n// - client-program.ts: pure Mealy machine (functional core)\n// - client-transport.ts: effect executor (imperative shell)\n//\n// Uses two HTTP channels:\n// - EventSource (GET) for server→client messages\n// - fetch POST for client→server messages\n//\n// Both directions use the alias-aware text pipeline.\n//\n// Features:\n// - Pure Mealy machine for connection lifecycle (client-program.ts)\n// - Exponential backoff reconnection with jitter\n// - POST retry with exponential backoff\n// - Text-level fragmentation for large payloads\n// - Inbound TextReassembler for fragmented SSE messages\n// - Observable connection state via subscribeToTransitions()\n//\n// The connection handshake:\n// 1. Client creates EventSource, waits for open\n// 2. EventSource.onopen fires → client creates channel + calls establishChannel()\n// 3. Synchronizer exchanges establish messages via POST + SSE\n//\n// On EventSource.onerror, the adapter closes the EventSource immediately and\n// takes over reconnection via the program's backoff logic, rather than\n// letting the browser's built-in EventSource reconnection run.\n\nimport type {\n ObservableHandle,\n StateTransition,\n TransitionListener,\n} from \"@kyneta/machine\"\nimport { createObservableProgram } from \"@kyneta/machine\"\nimport type {\n Channel,\n ChannelMsg,\n GeneratedChannel,\n PeerId,\n TransportFactory,\n} from \"@kyneta/transport\"\nimport { Transport } from \"@kyneta/transport\"\nimport {\n type AliasState,\n applyInboundAliasing,\n applyOutboundAliasing,\n complete,\n createFrameIdCounter,\n decodeTextWires,\n emptyAliasState,\n encodeTextFrame,\n encodeTextWireMessage,\n fragmentTextPayload,\n TEXT_WIRE_VERSION,\n TextReassembler,\n} from \"@kyneta/wire\"\nimport {\n createSseClientProgram,\n type SseClientEffect,\n type SseClientMsg,\n} from \"./client-program.js\"\nimport type {\n DisconnectReason,\n SseClientLifecycleEvents,\n SseClientState,\n} from \"./types.js\"\n\n// Re-export state types for convenience\nexport type { DisconnectReason, SseClientLifecycleEvents, SseClientState }\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\n/**\n * Default fragment threshold in characters.\n * 60K chars provides a safety margin below typical 100KB body-parser limits,\n * accounting for JSON overhead and potential base64 expansion.\n */\nexport const DEFAULT_FRAGMENT_THRESHOLD = 60_000\n\n/**\n * Options for the SSE client adapter.\n */\nexport interface SseClientOptions {\n /** URL for POST requests (client→server). String or function of peerId. */\n postUrl: string | ((peerId: PeerId) => string)\n\n /** URL for SSE EventSource (server→client). String or function of peerId. */\n eventSourceUrl: string | ((peerId: PeerId) => string)\n\n /** Reconnection options for EventSource. */\n reconnect?: {\n enabled?: boolean\n maxAttempts?: number\n baseDelay?: number\n maxDelay?: number\n }\n\n /** POST retry options. */\n postRetry?: {\n maxAttempts?: number\n baseDelay?: number\n maxDelay?: number\n }\n\n /** Fragment threshold in characters. Default: 60000 (60K chars). */\n fragmentThreshold?: number\n\n /** Lifecycle event callbacks. */\n lifecycle?: SseClientLifecycleEvents\n}\n\n/**\n * Default POST retry options.\n */\nconst DEFAULT_POST_RETRY = {\n maxAttempts: 3,\n baseDelay: 1000,\n maxDelay: 10000,\n}\n\n// ---------------------------------------------------------------------------\n// State transition type alias\n// ---------------------------------------------------------------------------\n\n/**\n * State transition event for SSE client states.\n */\nexport type SseClientStateTransition = StateTransition<SseClientState>\n\n// ---------------------------------------------------------------------------\n// SseClientTransport\n// ---------------------------------------------------------------------------\n\n/**\n * SSE client network adapter for @kyneta/exchange.\n *\n * Uses two HTTP channels:\n * - **EventSource** (GET, long-lived) for server→client messages\n * - **fetch POST** for client→server messages\n *\n * Both directions use the alias-aware text pipeline.\n *\n * Internally, the connection lifecycle is a `Program<Msg, Model, Fx>` —\n * a pure Mealy machine whose transitions are deterministically testable.\n * This class is the imperative shell that interprets data effects as I/O.\n *\n * @example\n * ```typescript\n * import { createSseClient } from \"@kyneta/sse-transport/client\"\n *\n * const exchange = new Exchange({\n * id: \"browser-client\",\n * transports: [createSseClient({\n * postUrl: \"/sync\",\n * eventSourceUrl: (peerId) => `/events?peerId=${peerId}`,\n * reconnect: { enabled: true },\n * })],\n * })\n * ```\n */\nexport class SseClientTransport extends Transport<void> {\n #peerId?: PeerId\n #options: SseClientOptions\n\n // Observable program handle — created in onStart(), drives all state\n #handle: ObservableHandle<SseClientMsg, SseClientState>\n\n // Executor-local I/O state — not in the program model\n #eventSource?: EventSource\n #serverChannel?: Channel\n #reconnectTimer?: ReturnType<typeof setTimeout>\n\n // Fragmentation\n readonly #fragmentThreshold: number\n\n // Alias-aware pipeline state — tracks alias bindings per connection\n #aliasState: AliasState = emptyAliasState()\n\n // Inbound reassembly for fragmented SSE messages from server\n readonly #reassembler: TextReassembler\n\n // POST retry\n #currentRetryAbortController?: AbortController\n\n constructor(options: SseClientOptions) {\n super({ transportType: \"sse-client\" })\n this.#options = options\n this.#fragmentThreshold =\n options.fragmentThreshold ?? DEFAULT_FRAGMENT_THRESHOLD\n this.#reassembler = new TextReassembler({\n timeoutMs: 10_000,\n })\n\n // Create the program with a placeholder URL — the executor resolves the\n // real eventSourceUrl (which may be a function of peerId) at effect time.\n // The URL in the program is used only as a marker; the executor overrides it.\n const program = createSseClientProgram({\n url: \"__deferred__\",\n reconnect: options.reconnect,\n })\n\n this.#handle = createObservableProgram(program, (effect, dispatch) => {\n this.#executeEffect(effect, dispatch)\n })\n\n // Set up lifecycle event forwarding\n this.#setupLifecycleEvents()\n }\n\n // ==========================================================================\n // Lifecycle event forwarding\n // ==========================================================================\n\n /**\n * Subscribe to the observable handle's transitions and forward them to\n * the lifecycle callbacks. `wasConnectedBefore` is observer-local state,\n * not in the program model.\n */\n #setupLifecycleEvents(): void {\n let wasConnectedBefore = false\n\n this.#handle.subscribeToTransitions(transition => {\n // Forward to onStateChange callback\n this.#options.lifecycle?.onStateChange?.(transition)\n\n const { from, to } = transition\n\n // onDisconnect: transitioning TO disconnected\n if (to.status === \"disconnected\" && to.reason) {\n this.#options.lifecycle?.onDisconnect?.(to.reason)\n }\n\n // onReconnecting: transitioning TO reconnecting\n if (to.status === \"reconnecting\") {\n this.#options.lifecycle?.onReconnecting?.(to.attempt, to.nextAttemptMs)\n }\n\n // onReconnected: from reconnecting/connecting TO connected (after prior connection)\n if (\n wasConnectedBefore &&\n (from.status === \"reconnecting\" || from.status === \"connecting\") &&\n to.status === \"connected\"\n ) {\n this.#options.lifecycle?.onReconnected?.()\n }\n\n // Track whether we've ever been connected\n if (to.status === \"connected\") {\n wasConnectedBefore = true\n }\n\n // Reset on intentional disconnect (stop)\n if (to.status === \"disconnected\" && to.reason?.type === \"intentional\") {\n wasConnectedBefore = false\n }\n })\n }\n\n // ==========================================================================\n // Effect executor — interprets data effects as I/O\n // ==========================================================================\n\n #executeEffect(\n effect: SseClientEffect,\n dispatch: (msg: SseClientMsg) => void,\n ): void {\n switch (effect.type) {\n case \"create-event-source\": {\n this.#doCreateEventSource(dispatch)\n break\n }\n\n case \"close-event-source\": {\n if (this.#eventSource) {\n this.#eventSource.onopen = null\n this.#eventSource.onmessage = null\n this.#eventSource.onerror = null\n this.#eventSource.close()\n this.#eventSource = undefined\n }\n break\n }\n\n case \"add-channel-and-establish\": {\n // Remove any stale channel from a previous connection\n if (this.#serverChannel) {\n this.removeChannel(this.#serverChannel.channelId)\n this.#serverChannel = undefined\n }\n\n // Fresh reassembler for the new connection — stale fragments from\n // the old connection must not collide with new fragments.\n this.#reassembler.reset()\n\n this.#serverChannel = this.addChannel()\n\n // No \"ready\" handshake — establish immediately\n this.establishChannel(this.#serverChannel.channelId)\n break\n }\n\n case \"remove-channel\": {\n if (this.#serverChannel) {\n this.removeChannel(this.#serverChannel.channelId)\n this.#serverChannel = undefined\n }\n break\n }\n\n case \"start-reconnect-timer\": {\n this.#reconnectTimer = setTimeout(() => {\n this.#reconnectTimer = undefined\n dispatch({ type: \"reconnect-timer-fired\" })\n }, effect.delayMs)\n break\n }\n\n case \"cancel-reconnect-timer\": {\n if (this.#reconnectTimer !== undefined) {\n clearTimeout(this.#reconnectTimer)\n this.#reconnectTimer = undefined\n }\n break\n }\n\n case \"abort-pending-posts\": {\n if (this.#currentRetryAbortController) {\n this.#currentRetryAbortController.abort()\n this.#currentRetryAbortController = undefined\n }\n break\n }\n }\n }\n\n /**\n * Create an EventSource and wire up event handlers.\n * The URL is resolved here (may be a function of peerId).\n */\n #doCreateEventSource(dispatch: (msg: SseClientMsg) => void): void {\n if (!this.#peerId) {\n throw new Error(\"Cannot connect: peerId not set\")\n }\n\n // Resolve URL — may be a string or function of peerId\n const url =\n typeof this.#options.eventSourceUrl === \"function\"\n ? this.#options.eventSourceUrl(this.#peerId)\n : this.#options.eventSourceUrl\n\n try {\n this.#eventSource = new EventSource(url)\n\n this.#eventSource.onopen = () => {\n dispatch({ type: \"event-source-opened\" })\n }\n\n this.#eventSource.onmessage = (event: MessageEvent) => {\n this.#handleMessage(event)\n }\n\n this.#eventSource.onerror = () => {\n dispatch({ type: \"event-source-error\" })\n }\n } catch (_error) {\n // EventSource constructor threw (e.g. invalid URL) — treat as error\n dispatch({ type: \"event-source-error\" })\n }\n }\n\n // ==========================================================================\n // State observation — delegated to the observable handle\n // ==========================================================================\n\n /**\n * Get the current connection state.\n */\n getState(): SseClientState {\n return this.#handle.getState()\n }\n\n /**\n * Subscribe to state transitions.\n */\n subscribeToTransitions(\n listener: TransitionListener<SseClientState>,\n ): () => void {\n return this.#handle.subscribeToTransitions(listener)\n }\n\n /**\n * Wait for a specific state.\n */\n waitForState(\n predicate: (state: SseClientState) => boolean,\n options?: { timeoutMs?: number },\n ): Promise<SseClientState> {\n return this.#handle.waitForState(predicate, options)\n }\n\n /**\n * Wait for a specific status.\n */\n waitForStatus(\n status: SseClientState[\"status\"],\n options?: { timeoutMs?: number },\n ): Promise<SseClientState> {\n return this.#handle.waitForStatus(status, options)\n }\n\n /**\n * Whether the client is connected and ready to send/receive.\n */\n get isConnected(): boolean {\n return this.#handle.getState().status === \"connected\"\n }\n\n // ==========================================================================\n // Transport abstract method implementations\n // ==========================================================================\n\n protected generate(): GeneratedChannel {\n const nextFrameId = createFrameIdCounter()\n // New channel = fresh alias state; reset on (re)connect.\n this.#aliasState = emptyAliasState()\n return {\n transportType: this.transportType,\n send: (msg: ChannelMsg) => {\n if (!this.#peerId) {\n return\n }\n\n // Check if EventSource is closed before sending\n // readyState: 0=CONNECTING, 1=OPEN, 2=CLOSED\n if (!this.#eventSource || this.#eventSource.readyState === 2) {\n return\n }\n\n // Resolve the postUrl with the peerId\n const resolvedPostUrl =\n typeof this.#options.postUrl === \"function\"\n ? this.#options.postUrl(this.#peerId)\n : this.#options.postUrl\n\n // Alias-aware outbound: ChannelMsg → AliasWireMessage\n const { state: nextState, wire } = applyOutboundAliasing(\n this.#aliasState,\n msg,\n )\n this.#aliasState = nextState\n\n // AliasWireMessage → JSON-safe object → JSON string\n const payload = JSON.stringify(encodeTextWireMessage(wire))\n\n // JSON string → text frame\n const textFrame = encodeTextFrame(complete(TEXT_WIRE_VERSION, payload))\n\n // Fragment large payloads\n if (\n this.#fragmentThreshold > 0 &&\n textFrame.length > this.#fragmentThreshold\n ) {\n const fragments = fragmentTextPayload(\n payload,\n this.#fragmentThreshold,\n nextFrameId(),\n )\n for (const fragment of fragments) {\n void this.#sendTextWithRetry(resolvedPostUrl, fragment)\n }\n } else {\n void this.#sendTextWithRetry(resolvedPostUrl, textFrame)\n }\n },\n stop: () => {\n // Don't call disconnect here — channel.stop() is called when\n // the channel is removed, which can happen during effect execution.\n // The actual disconnect is handled by onStop() or the program.\n },\n }\n }\n\n async onStart(): Promise<void> {\n if (!this.identity) {\n throw new Error(\n \"Adapter not properly initialized — identity not available\",\n )\n }\n this.#peerId = this.identity.peerId\n this.#handle.dispatch({ type: \"start\" })\n }\n\n async onStop(): Promise<void> {\n this.#reassembler.dispose()\n this.#handle.dispatch({ type: \"stop\" })\n }\n\n // ==========================================================================\n // Inbound message handling\n // ==========================================================================\n\n /**\n * Handle incoming SSE message.\n *\n * Each SSE `data:` event contains a text wire frame string.\n * Feed it through the TextReassembler, then through the alias-aware\n * inbound pipeline to resolve aliases and deliver ChannelMsgs.\n */\n #handleMessage(event: MessageEvent): void {\n if (!this.#serverChannel) {\n return\n }\n\n const data = event.data\n if (typeof data !== \"string\") {\n return\n }\n\n // Text wire → AliasWireMessage[] (complete batches only)\n const wires = decodeTextWires(this.#reassembler, data)\n if (!wires) {\n // Still assembling fragments, or reassembly error already logged\n return\n }\n\n for (const wire of wires) {\n const result = applyInboundAliasing(this.#aliasState, wire)\n this.#aliasState = result.state\n if (result.error || !result.msg) {\n console.warn(\"[sse-client] alias resolution failed:\", result.error)\n continue\n }\n this.#serverChannel?.onReceive(result.msg)\n }\n }\n\n // ==========================================================================\n // POST sending with retry\n // ==========================================================================\n\n /**\n * Send a text frame via POST with retry logic.\n */\n async #sendTextWithRetry(url: string, textFrame: string): Promise<void> {\n let attempt = 0\n const postRetryOpts = {\n ...DEFAULT_POST_RETRY,\n ...this.#options.postRetry,\n }\n const { maxAttempts, baseDelay, maxDelay } = postRetryOpts\n\n while (attempt < maxAttempts) {\n try {\n if (!this.#currentRetryAbortController) {\n this.#currentRetryAbortController = new AbortController()\n }\n\n if (!this.#peerId) {\n throw new Error(\"PeerId not available for retry\")\n }\n\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"text/plain\",\n \"X-Peer-Id\": this.#peerId,\n },\n body: textFrame,\n signal: this.#currentRetryAbortController.signal,\n })\n\n if (!response.ok) {\n // Don't retry on client errors (4xx)\n if (response.status >= 400 && response.status < 500) {\n throw new Error(`Failed to send message: ${response.statusText}`)\n }\n throw new Error(`Server error: ${response.statusText}`)\n }\n\n // Success\n this.#currentRetryAbortController = undefined\n return\n } catch (error: unknown) {\n attempt++\n\n const err = error as Error\n\n // If aborted, stop retrying\n if (err.name === \"AbortError\") {\n throw error\n }\n\n // If controller was cleared (e.g. by abort-pending-posts effect), stop retrying\n if (!this.#currentRetryAbortController) {\n const abortError = new Error(\"Retry aborted by connection reset\")\n abortError.name = \"AbortError\"\n throw abortError\n }\n\n // If max attempts reached, log and stop — don't throw.\n // The send callback is synchronous and uses `void`, so\n // a throw here would be an unhandled promise rejection.\n if (attempt >= maxAttempts) {\n this.#currentRetryAbortController = undefined\n console.error(\n `[SseClientTransport] Failed to send message after ${attempt} attempts:`,\n (error as Error).message,\n )\n return\n }\n\n // Calculate delay with exponential backoff and jitter\n const delay = Math.min(\n baseDelay * 2 ** (attempt - 1) + Math.random() * 100,\n maxDelay,\n )\n\n // Wait for delay or abort signal\n await new Promise<void>((resolve, reject) => {\n if (this.#currentRetryAbortController?.signal.aborted) {\n const error = new Error(\"Retry aborted\")\n error.name = \"AbortError\"\n reject(error)\n return\n }\n\n const timer = setTimeout(() => {\n cleanup()\n resolve()\n }, delay)\n\n const onAbort = () => {\n clearTimeout(timer)\n cleanup()\n const error = new Error(\"Retry aborted\")\n error.name = \"AbortError\"\n reject(error)\n }\n\n const cleanup = () => {\n this.#currentRetryAbortController?.signal.removeEventListener(\n \"abort\",\n onAbort,\n )\n }\n\n this.#currentRetryAbortController?.signal.addEventListener(\n \"abort\",\n onAbort,\n )\n })\n }\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Factory function\n// ---------------------------------------------------------------------------\n\n/**\n * Create an SSE client adapter for browser-to-server connections.\n *\n * @example\n * ```typescript\n * import { createSseClient } from \"@kyneta/sse-transport/client\"\n *\n * const exchange = new Exchange({\n * transports: [createSseClient({\n * postUrl: \"/sync\",\n * eventSourceUrl: (peerId) => `/events?peerId=${peerId}`,\n * reconnect: { enabled: true },\n * })],\n * })\n * ```\n */\nexport function createSseClient(options: SseClientOptions): TransportFactory {\n return () => new SseClientTransport(options)\n}\n"],"mappings":";;;;;;;;;;;AAyDA,SAAgB,uBACd,SACwD;CACxD,MAAM,EAAE,KAAK,iBAAiB,KAAK,OAAO,IAAI,QAAS;CACvD,MAAM,YAA8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KAAK;KACZ;IACF;IAEA,MAAM,QAAQ,iBAAiB;KAC7B,QAAQ;KACR,QAAQ;IACV,GAAG,KAAK;IAER,MAAM,gBAAgB;KACpB,aAAa,KAAK;KAClB,QAAQ;KACR,MAAM,wBAAQ,IAAI,MAAM,eAAe;KACvC,MAAM,OAAO;KACb,OAAO,KAAK;IACd;IAEA,MAAM,gBAAgB;KACpB,KAAKA,8BAA8B,OAAO,oBACxC,SACA,OACF;IACF;IAEA,KAAKA,8BAA8B,OAAO,iBACxC,SACA,OACF;GACF,CAAC;EACH;CAEJ;AACF;;;;;;;;;;;;;;;;;AAsBA,SAAgB,gBAAgB,SAA6C;CAC3E,aAAa,IAAI,mBAAmB,OAAO;AAC7C"}
|
package/dist/express.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"express.d.ts","names":[],"sources":["../src/express-router.ts"],"mappings":";;;;;UAqBiB,uBAAA;;AAAjB;;;EAKE,QAAA;EAkB6C;;;;EAZ7C,UAAA;EANA;;;;EAYA,iBAAA;EAM4B;;;;EAA5B,wBAAA,IAA4B,GAAA,EAAK,OAAA,KAAY,MAAA;EAME
|
|
1
|
+
{"version":3,"file":"express.d.ts","names":[],"sources":["../src/express-router.ts"],"mappings":";;;;;UAqBiB,uBAAA;;AAAjB;;;EAKE,QAAA;EAkB6C;;;;EAZ7C,UAAA;EANA;;;;EAYA,iBAAA;EAM4B;;;;EAA5B,wBAAA,IAA4B,GAAA,EAAK,OAAA,KAAY,MAAA;EAME;;AAAM;AA6CvD;EA7CE,0BAAA,IAA8B,GAAA,EAAK,OAAA,KAAY,MAAA;AAAA;;;;;;;;;;;;AAgDxC;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAHO,sBAAA,CACd,OAAA,EAAS,kBAAA,EACT,OAAA,GAAS,uBAAA,GACR,MAAA"}
|
package/dist/express.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { r as SseConnection, t as SseServerTransport } from "./server-transport-
|
|
1
|
+
import { r as SseConnection, t as SseServerTransport } from "./server-transport-DX3-TbCZ.js";
|
|
2
2
|
import { createRequire } from "node:module";
|
|
3
3
|
//#region \0rolldown/runtime.js
|
|
4
4
|
var __create = Object.create;
|
|
@@ -29559,6 +29559,13 @@ var require_express$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
|
29559
29559
|
});
|
|
29560
29560
|
});
|
|
29561
29561
|
}));
|
|
29562
|
+
/*!
|
|
29563
|
+
* express
|
|
29564
|
+
* Copyright(c) 2009-2013 TJ Holowaychuk
|
|
29565
|
+
* Copyright(c) 2013 Roman Shtylman
|
|
29566
|
+
* Copyright(c) 2014-2015 Douglas Christopher Wilson
|
|
29567
|
+
* MIT Licensed
|
|
29568
|
+
*/
|
|
29562
29569
|
//#endregion
|
|
29563
29570
|
//#region src/express-router.ts
|
|
29564
29571
|
var import_express = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
|