{"version":3,"file":"SignalClientStateMachine.mjs","sources":["../../../src/api/SignalClientStateMachine.ts"],"sourcesContent":["import { type HandlerArgs, type HandlerFn, createFsm } from 'machina';\n\n/**\n * Runtime lifecycle states of the signal connection.\n *\n * `offline` is the resting state after the transport was lost without an explicit close: no\n * attempt is in flight, but a resume is still legal. It is what makes retrying a failed resume\n * expressible — `closed` is only reached by an explicit close or by a terminal attempt failure.\n */\nexport type SignalLifecycleState =\n  'new' | 'connecting' | 'connected' | 'offline' | 'reconnecting' | 'disconnecting' | 'closed';\n\nexport interface SignalMachineContext {\n  /** Monotonic id of the current (re)connection attempt and of the transport it owns */\n  attemptId: number;\n  /** Error or reason that ended the last attempt, kept for diagnostics. */\n  lastError?: unknown;\n  /** Reason passed to the last close request. */\n  closeReason?: string;\n}\n\nexport type SignalMachineInput =\n  /**\n   * Start an initial session, or restart from scratch (full reconnect).\n   *\n   * Establishing is legal exactly where no transport and no attempt are in play: `new`, `offline`\n   * and `closed`. `closed` is included because it means \"no transport\", not \"session over\" — a\n   * deliberate close and an unexpected loss leave the session equally resumable, and the engine\n   * recovers from both. Establishing over a live session, or over an attempt already in flight, is\n   * a caller error; `disconnecting` is waited out rather than refused.\n   */\n  | { type: 'connect' }\n  /**\n   * Resume the existing session: legal wherever establishing is, minus `new` (nothing to resume\n   * yet), plus `connected` — the peer connection can be severed while signalling stays up.\n   */\n  | { type: 'reconnect' }\n  /**\n   * An attempt established its transport. Carries the attempt it belongs to: an attempt that a\n   * newer one has already superseded must not declare the session live.\n   */\n  | { type: 'connectComplete'; attemptId: number }\n  | { type: 'connectFailed'; error?: unknown }\n  | { type: 'reconnectComplete'; attemptId: number }\n  /**\n   * A resume attempt ended. `recoverable` distinguishes \"another resume may follow\" (→ `offline`)\n   * from a terminal outcome such as a server leave or an expired token (→ `closed`).\n   */\n  | { type: 'reconnectFailed'; error?: unknown; recoverable: boolean }\n  /** The transport identified by `attemptId` was lost (unexpected ws close, ping timeout). */\n  | { type: 'transportFailed'; attemptId: number; reason: string }\n  | { type: 'close'; reason: string }\n  | { type: 'closeComplete' };\n\ntype Args = HandlerArgs<SignalMachineContext, SignalLifecycleState>;\n\ntype Handler = HandlerFn<SignalMachineContext, SignalLifecycleState>;\n\n/**\n * Declares a handler for one input, restoring the payload typing that machina's `...unknown[]`\n * handler arguments give up.\n */\nfunction on<T extends SignalMachineInput['type']>(\n  handler: (\n    args: Args,\n    event: Extract<SignalMachineInput, { type: T }>,\n  ) => SignalLifecycleState | void,\n): Handler {\n  return handler as Handler;\n}\n\n/**\n * Whether a transport-originated input belongs to the attempt that currently owns the session.\n * Inputs from a superseded attempt are dropped: its transport is already being replaced, so it can\n * neither declare the session live nor take it down.\n */\nfunction isCurrentAttempt(ctx: SignalMachineContext, event: { attemptId: number }) {\n  return event.attemptId === ctx.attemptId;\n}\n\nconst attemptEstablished = on<'connectComplete' | 'reconnectComplete'>(({ ctx }, event) => {\n  if (!isCurrentAttempt(ctx, event)) {\n    return;\n  }\n  return 'connected';\n});\n\nconst startConnect = on<'connect'>(({ ctx }) => {\n  ctx.attemptId += 1;\n  ctx.lastError = undefined;\n  return 'connecting';\n});\n\nconst startReconnect = on<'reconnect'>(({ ctx }) => {\n  ctx.attemptId += 1;\n  ctx.lastError = undefined;\n  return 'reconnecting';\n});\n\nconst requestClose = on<'close'>(({ ctx }, event) => {\n  ctx.closeReason = event.reason;\n  return 'disconnecting';\n});\n\nconst signalStates = {\n  new: {\n    connect: startConnect,\n    close: requestClose,\n  },\n  connecting: {\n    connectComplete: attemptEstablished,\n    // An initial connect has no session to fall back on, so failure is terminal.\n    connectFailed: on<'connectFailed'>(({ ctx }, event) => {\n      ctx.lastError = event.error;\n      return 'closed';\n    }),\n    close: requestClose,\n  },\n  connected: {\n    reconnect: startReconnect,\n    transportFailed: on<'transportFailed'>(({ ctx }, event) => {\n      if (!isCurrentAttempt(ctx, event)) {\n        // a transport that has already been replaced, reporting its close late\n        return;\n      }\n      ctx.lastError = event.reason;\n      return 'offline';\n    }),\n    close: requestClose,\n  },\n  offline: {\n    connect: startConnect,\n    reconnect: startReconnect,\n    close: requestClose,\n  },\n  reconnecting: {\n    reconnectComplete: attemptEstablished,\n    reconnectFailed: on<'reconnectFailed'>(({ ctx }, event) => {\n      ctx.lastError = event.error;\n      return event.recoverable ? 'offline' : 'closed';\n    }),\n    close: requestClose,\n  },\n  // Owns the transport until the close handshake settles. Every path into this state is followed\n  // by a `closeComplete`, so it cannot become a trap.\n  disconnecting: {\n    closeComplete: 'closed',\n  },\n  // No transport, but the session may still be resumable: the engine resumes after an unexpected\n  // close just as it does from `offline`.\n  closed: {\n    connect: startConnect,\n    reconnect: startReconnect,\n  },\n} as const;\n\n/**\n * Lifecycle model of the signal connection.\n *\n * The machine deliberately does not own connection attempts: `SignalClient` performs the\n * asynchronous work and reports the outcome. It also does not decide *whether* to reconnect —\n * that policy (backoff, resume vs. full reconnect, region failover, giving up) belongs to\n * `RTCEngine`, so transport loss lands in `offline` rather than starting a reconnect on its own.\n *\n * Each client gets its own instance: the context is mutable and per-connection.\n */\nexport function createSignalMachine(initialState: SignalLifecycleState = 'new') {\n  const context: SignalMachineContext = { attemptId: 0 };\n  return createFsm({\n    id: 'signal',\n    initialState: initialState,\n    context,\n    states: signalStates,\n  });\n}\n\nexport type SignalMachine = ReturnType<typeof createSignalMachine>;\n\n/** All lifecycle states, derived from the machine itself so the two cannot drift. */\nexport const signalLifecycleStates = Object.keys(signalStates) as Array<SignalLifecycleState>;\n"],"names":["on","handler","isCurrentAttempt","ctx","event","attemptId","attemptEstablished","_ref","startConnect","_ref2","lastError","undefined","startReconnect","_ref3","requestClose","_ref4","closeReason","reason","signalStates","new","connect","close","connecting","connectComplete","connectFailed","_ref5","error","connected","reconnect","transportFailed","_ref6","offline","reconnecting","reconnectComplete","reconnectFailed","_ref7","recoverable","disconnecting","closeComplete","closed","createSignalMachine","initialState","arguments","length","context","createFsm","id","states"],"mappings":"gCA0DA;;;AAGG;AACH,SAASA,EAAEA,CACTC,O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