{"version":3,"file":"IncomingDataStreamManager.mjs","sources":["../../../../../src/room/data-stream/incoming/IncomingDataStreamManager.ts"],"sourcesContent":["import {\n  type DataPacket,\n  DataStream_Chunk,\n  DataStream_CompressionType,\n  DataStream_Header,\n  DataStream_Trailer,\n  Encryption_Type,\n} from '@livekit/protocol';\nimport { EventEmitter } from 'events';\nimport type TypedEmitter from 'typed-emitter';\nimport log from '../../../logger';\nimport { type RoomDataStreamOptions } from '../../../options';\nimport { type NonSharedUint8Array } from '../../../type-polyfills/non-shared-typed-arrays';\nimport { DataStreamError, DataStreamErrorReason } from '../../errors';\nimport { type ByteStreamInfo, type StreamController, type TextStreamInfo } from '../../types';\nimport { bigIntToNumber, isDeflateRawCompressionSupported, numberToBigInt } from '../../utils';\nimport { deflateRawDecompress, inflateRawTransform } from '../compression';\nimport {\n  DEFAULT_MAX_OPEN_STREAMS_PER_PARTICIPANT,\n  DEFAULT_MAX_PAYLOAD_BYTE_LENGTH,\n  TRANSCRIPTION_TOPIC,\n} from '../constants';\nimport {\n  type ByteStreamHandler,\n  ByteStreamReader,\n  type TextStreamHandler,\n  TextStreamReader,\n} from './StreamReader';\nimport type { IncomingDataStreamManagerCallbacks } from './events';\n\n/**\n * The receive state for one in-flight text stream. A text stream can have several consumers (an\n * application handler for its topic, plus the SDK's own transcription tap), each reading through\n * its own `ReadableStream`. Everything that describes the *stream* - its info, when it started, who\n * sent it - is held once here rather than copied per consumer, so consumers cannot disagree about\n * it and a trailer's attribute merge is visible to all of them by construction.\n */\ntype TextStreamControllerGroup = {\n  info: TextStreamInfo;\n  sendingParticipantIdentity: string;\n  /** The controller of each underlying {@link ReadableStream} which is currently being fed by this text stream. */\n  controllers: Array<ReadableStreamDefaultController<DataStream_Chunk>>;\n};\n\nexport default class IncomingDataStreamManager extends (EventEmitter as new () => TypedEmitter<IncomingDataStreamManagerCallbacks>) {\n  private log = log;\n\n  /** Max number of decompressed bytes an incoming compressed stream may produce before it is\n   * errored (decompression-bomb guard). */\n  private maxPayloadByteLength: number;\n\n  /** Max number of incoming streams a single remote participant may have open at once. */\n  private maxOpenStreamsPerParticipant: number;\n\n  constructor({\n    maxPayloadByteLength = DEFAULT_MAX_PAYLOAD_BYTE_LENGTH,\n    maxOpenStreamsPerParticipant = DEFAULT_MAX_OPEN_STREAMS_PER_PARTICIPANT,\n  }: RoomDataStreamOptions = {}) {\n    super();\n    this.maxPayloadByteLength = maxPayloadByteLength;\n    this.maxOpenStreamsPerParticipant = maxOpenStreamsPerParticipant;\n  }\n\n  private byteStreamControllers = new Map<string, StreamController<DataStream_Chunk>>();\n\n  private textStreamControllers = new Map<string, TextStreamControllerGroup>();\n\n  private byteStreamHandlers = new Map<string, ByteStreamHandler>();\n\n  private textStreamHandlers = new Map<string, TextStreamHandler>();\n\n  private isConnected = false;\n\n  private bufferedPackets: Array<{ packet: DataPacket; encryptionType: Encryption_Type }> = [];\n\n  setConnected(connected: boolean) {\n    this.isConnected = connected;\n    if (connected) {\n      this.flushBufferedPackets();\n    }\n  }\n\n  private flushBufferedPackets() {\n    const packets = this.bufferedPackets;\n    this.bufferedPackets = [];\n    for (const { packet, encryptionType } of packets) {\n      this.handleDataStreamPacket(packet, encryptionType);\n    }\n  }\n\n  registerTextStreamHandler(topic: string, callback: TextStreamHandler) {\n    if (this.textStreamHandlers.has(topic)) {\n      throw new DataStreamError(\n        `A text stream handler for topic \"${topic}\" has already been set.`,\n        DataStreamErrorReason.HandlerAlreadyRegistered,\n      );\n    }\n    this.textStreamHandlers.set(topic, callback);\n  }\n\n  unregisterTextStreamHandler(topic: string) {\n    this.textStreamHandlers.delete(topic);\n  }\n\n  registerByteStreamHandler(topic: string, callback: ByteStreamHandler) {\n    if (this.byteStreamHandlers.has(topic)) {\n      throw new DataStreamError(\n        `A byte stream handler for topic \"${topic}\" has already been set.`,\n        DataStreamErrorReason.HandlerAlreadyRegistered,\n      );\n    }\n    this.byteStreamHandlers.set(topic, callback);\n  }\n\n  unregisterByteStreamHandler(topic: string) {\n    this.byteStreamHandlers.delete(topic);\n  }\n\n  clearControllers() {\n    // Error any in flight streams so readers do not wait forever for chunks that can no longer arrive.\n    const abnormalEndError = new DataStreamError(\n      'Room disconnected in the middle of receiving data',\n      DataStreamErrorReason.AbnormalEnd,\n    );\n    for (const { controller } of this.byteStreamControllers.values()) {\n      controller.error(abnormalEndError);\n    }\n    for (const group of this.textStreamControllers.values()) {\n      for (const controller of group.controllers) {\n        controller.error(abnormalEndError);\n      }\n    }\n    this.byteStreamControllers.clear();\n    this.textStreamControllers.clear();\n    this.bufferedPackets = [];\n  }\n\n  validateParticipantHasNoActiveDataStreams(participantIdentity: string) {\n    // Terminate any in flight data stream receives from the given participant\n    const textStreamsBeingSentByDisconnectingParticipant = Array.from(\n      this.textStreamControllers.entries(),\n    ).filter(([, group]) => group.sendingParticipantIdentity === participantIdentity);\n    const byteStreamsBeingSentByDisconnectingParticipant = Array.from(\n      this.byteStreamControllers.entries(),\n    ).filter((entry) => entry[1].sendingParticipantIdentity === participantIdentity);\n\n    if (\n      textStreamsBeingSentByDisconnectingParticipant.length > 0 ||\n      byteStreamsBeingSentByDisconnectingParticipant.length > 0\n    ) {\n      const abnormalEndError = new DataStreamError(\n        `Participant ${participantIdentity} unexpectedly disconnected in the middle of sending data`,\n        DataStreamErrorReason.AbnormalEnd,\n      );\n      for (const [id, controller] of byteStreamsBeingSentByDisconnectingParticipant) {\n        controller.controller.error(abnormalEndError);\n        this.byteStreamControllers.delete(id);\n      }\n      for (const [id, group] of textStreamsBeingSentByDisconnectingParticipant) {\n        for (const controller of group.controllers) {\n          controller.error(abnormalEndError);\n        }\n        this.textStreamControllers.delete(id);\n      }\n    }\n  }\n\n  handleDataStreamPacket(packet: DataPacket, encryptionType: Encryption_Type) {\n    if (!this.isConnected) {\n      this.bufferedPackets.push({ packet, encryptionType });\n      return;\n    }\n    switch (packet.value.case) {\n      case 'streamHeader':\n        return this.handleStreamHeader(\n          packet.value.value,\n          packet.participantIdentity,\n          encryptionType,\n        );\n      case 'streamChunk':\n        return this.handleStreamChunk(packet.value.value, encryptionType);\n      case 'streamTrailer':\n        return this.handleStreamTrailer(packet.value.value, encryptionType);\n      default:\n        throw new Error(`DataPacket of value \"${packet.value.case}\" is not data stream related!`);\n    }\n  }\n\n  /** Returns true if the given participant already has the maximum number of streams open. */\n  private hasTooManyOpenStreams(participantIdentity: string) {\n    let openStreamCount = 0;\n    for (const controllers of [this.byteStreamControllers, this.textStreamControllers]) {\n      for (const { sendingParticipantIdentity } of controllers.values()) {\n        if (sendingParticipantIdentity === participantIdentity) {\n          openStreamCount += 1;\n        }\n      }\n    }\n    return openStreamCount >= this.maxOpenStreamsPerParticipant;\n  }\n\n  private handleStreamHeader(\n    streamHeader: DataStream_Header,\n    participantIdentity: string,\n    encryptionType: Encryption_Type,\n  ) {\n    if (this.hasTooManyOpenStreams(participantIdentity)) {\n      this.log.error(\n        `Participant ${participantIdentity} already has ${this.maxOpenStreamsPerParticipant} data streams open, dropping stream ${streamHeader.streamId}`,\n      );\n      return;\n    }\n\n    switch (streamHeader.contentHeader.case) {\n      case 'byteHeader': {\n        const streamHandlerCallback = this.byteStreamHandlers.get(streamHeader.topic);\n        if (!streamHandlerCallback) {\n          this.log.debug(\n            'ignoring incoming byte stream due to no handler for topic',\n            streamHeader.topic,\n          );\n          return;\n        }\n\n        let streamController: ReadableStreamDefaultController<DataStream_Chunk>;\n\n        const info: ByteStreamInfo = {\n          id: streamHeader.streamId,\n          name: streamHeader.contentHeader.value.name ?? 'unknown',\n          mimeType: streamHeader.mimeType,\n          size: streamHeader.totalLength ? Number(streamHeader.totalLength) : undefined,\n          topic: streamHeader.topic,\n          timestamp: bigIntToNumber(streamHeader.timestamp),\n          attributes: streamHeader.attributes,\n          encryptionType,\n        };\n\n        // Determine if the byte payload needs to be decompressed.\n        let compressed;\n        switch (streamHeader.compression) {\n          case DataStream_CompressionType.DEFLATE_RAW:\n            if (!isDeflateRawCompressionSupported()) {\n              // NOTE: this shouldn't really ever happen, if this warning is logged then the sender\n              // isn't properly abiding by the data streams v2 protocol.\n              log.warn(\n                `Data stream ${streamHeader.streamId} received with deflate-raw compression, but this browser does not support deflate-raw decompression. Dropping...`,\n              );\n              return;\n            }\n            compressed = true;\n            break;\n          case DataStream_CompressionType.NONE:\n            compressed = false;\n            break;\n          default:\n            // NOTE: this shouldn't really ever happen, if this warning is logged then the sender\n            // isn't properly abiding by the data streams v2 protocol.\n            log.warn(\n              `Data stream ${streamHeader.streamId} received with unknown compression type ${streamHeader.compression}, dropping...`,\n            );\n            return;\n        }\n\n        // Single-packet stream: the entire payload was packaged into the header's `inlineContent`.\n        // Synthesize an already-complete stream and skip waiting for chunk/trailer packets.\n        const inlineContent = streamHeader.inlineContent as NonSharedUint8Array;\n        if (typeof inlineContent !== 'undefined') {\n          // Inline bytes are the raw payload, optionally deflate-raw compressed.\n          streamHandlerCallback(\n            new ByteStreamReader(\n              info,\n              createInlineStream(\n                streamHeader.streamId,\n                compressed\n                  ? deflateRawDecompress(inlineContent, this.maxPayloadByteLength)\n                  : inlineContent,\n              ),\n              bigIntToNumber(streamHeader.totalLength),\n            ),\n            { identity: participantIdentity },\n          );\n          return;\n        }\n\n        const stream = new ReadableStream<DataStream_Chunk>({\n          start: (controller) => {\n            streamController = controller;\n\n            if (this.byteStreamControllers.has(streamHeader.streamId)) {\n              throw new DataStreamError(\n                `A data stream read is already in progress for a stream with id ${streamHeader.streamId}.`,\n                DataStreamErrorReason.AlreadyOpened,\n              );\n            }\n\n            this.byteStreamControllers.set(streamHeader.streamId, {\n              info,\n              controller: streamController,\n              startTime: Date.now(),\n              sendingParticipantIdentity: participantIdentity,\n            });\n          },\n          cancel: () => {\n            // The consumer side of the pipe chain errored (e.g. `ensureOrderedChunks` saw a gap) or\n            // was cancelled, which cancels this source stream. Unregister it so later chunks and the\n            // trailer for this stream are dropped rather than hitting a closed controller.\n            if (\n              this.byteStreamControllers.get(streamHeader.streamId)?.controller === streamController\n            ) {\n              this.byteStreamControllers.delete(streamHeader.streamId);\n            }\n          },\n        });\n        streamHandlerCallback(\n          new ByteStreamReader(\n            info,\n            compressed\n              ? inflateRawByteChunkStream(stream, streamHeader.streamId, this.maxPayloadByteLength)\n              : stream.pipeThrough(ensureOrderedChunks(streamHeader.streamId)),\n            // `totalLength` is the pre-compression size, and the reader counts decompressed bytes,\n            // so it applies to both paths (mirrors text).\n            bigIntToNumber(streamHeader.totalLength),\n          ),\n          {\n            identity: participantIdentity,\n          },\n        );\n        return;\n      }\n      case 'textHeader': {\n        // The transcription tap runs alongside the application handler, each with its own reader,\n        // so the SDK can rebuild transcription events without taking the reserved topic away from\n        // an application that reads it too. `listenerCount` keeps the \"nobody wants this stream,\n        // drop it\" behavior intact when no one has subscribed.\n        const streamHandlerCallbacks: Array<TextStreamHandler> = [];\n        if (\n          streamHeader.topic === TRANSCRIPTION_TOPIC &&\n          this.listenerCount('transcriptionStreamArrived') > 0\n        ) {\n          streamHandlerCallbacks.push((reader, { identity }) => {\n            this.emit('transcriptionStreamArrived', { reader, participantIdentity: identity });\n          });\n        }\n        const applicationCallback = this.textStreamHandlers.get(streamHeader.topic);\n        if (applicationCallback) {\n          streamHandlerCallbacks.push(applicationCallback);\n        }\n        if (streamHandlerCallbacks.length === 0) {\n          this.log.debug(\n            'ignoring incoming text stream due to no handler for topic',\n            streamHeader.topic,\n          );\n          return;\n        }\n\n        const info: TextStreamInfo = {\n          id: streamHeader.streamId,\n          mimeType: streamHeader.mimeType,\n          size: streamHeader.totalLength ? Number(streamHeader.totalLength) : undefined,\n          topic: streamHeader.topic,\n          timestamp: Number(streamHeader.timestamp),\n          attributes: streamHeader.attributes,\n          encryptionType,\n          attachedStreamIds: streamHeader.contentHeader.value.attachedStreamIds,\n        };\n\n        // Determine if the byte payload needs to be decompressed.\n        let compressed;\n        switch (streamHeader.compression) {\n          case DataStream_CompressionType.DEFLATE_RAW:\n            if (!isDeflateRawCompressionSupported()) {\n              // NOTE: this shouldn't really ever happen, if this warning is logged then the sender\n              // isn't properly abiding by the data streams v2 protocol.\n              log.warn(\n                `Data stream ${streamHeader.streamId} received with deflate-raw compression, but this browser does not support deflate-raw decompression. Dropping...`,\n              );\n              return;\n            }\n            compressed = true;\n            break;\n          case DataStream_CompressionType.NONE:\n            compressed = false;\n            break;\n          default:\n            // NOTE: this shouldn't really ever happen, if this warning is logged then the sender\n            // isn't properly abiding by the data streams v2 protocol.\n            log.warn(\n              `Data stream ${streamHeader.streamId} received with unknown compression type ${streamHeader.compression}, dropping...`,\n            );\n            return;\n        }\n\n        // Single-packet stream: the entire payload was smuggled into the header's `inlineContent`.\n        // Synthesize an already-complete stream and skip waiting for chunk/trailer packets.\n        const inlineContent = streamHeader.inlineContent as NonSharedUint8Array;\n        if (typeof inlineContent !== 'undefined') {\n          // Inline text is the raw UTF-8 payload, optionally deflate-raw compressed. `content` is\n          // computed once and shared: when compressed it is a promise, so each inline stream awaits\n          // the same decompression rather than repeating it.\n          const content = compressed\n            ? deflateRawDecompress(inlineContent, this.maxPayloadByteLength)\n            : inlineContent;\n          for (const streamHandlerCallback of streamHandlerCallbacks) {\n            streamHandlerCallback(\n              new TextStreamReader(\n                info,\n                createInlineStream(streamHeader.streamId, content),\n                bigIntToNumber(streamHeader.totalLength),\n              ),\n              { identity: participantIdentity },\n            );\n          }\n          return;\n        }\n\n        if (this.textStreamControllers.has(streamHeader.streamId)) {\n          throw new DataStreamError(\n            `A data stream read is already in progress for a stream with id ${streamHeader.streamId}.`,\n            DataStreamErrorReason.AlreadyOpened,\n          );\n        }\n\n        const group: TextStreamControllerGroup = {\n          info,\n          sendingParticipantIdentity: participantIdentity,\n          controllers: [],\n        };\n        this.textStreamControllers.set(streamHeader.streamId, group);\n\n        for (const streamHandlerCallback of streamHandlerCallbacks) {\n          let streamController: ReadableStreamDefaultController<DataStream_Chunk>;\n          const stream = new ReadableStream<DataStream_Chunk>({\n            start: (controller) => {\n              streamController = controller;\n              group.controllers.push(controller);\n            },\n            cancel: () => {\n              // This consumer's side of the pipe chain errored (e.g. `ensureOrderedChunks` saw a\n              // gap) or was cancelled, which cancels this source stream. Drop its controller so later\n              // chunks and the trailer skip it rather than hitting a closed controller, and\n              // unregister the stream once no consumers remain.\n              const index = group.controllers.indexOf(streamController);\n              if (index !== -1) {\n                group.controllers.splice(index, 1);\n              }\n              if (\n                group.controllers.length === 0 &&\n                this.textStreamControllers.get(streamHeader.streamId) === group\n              ) {\n                this.textStreamControllers.delete(streamHeader.streamId);\n              }\n            },\n          });\n          streamHandlerCallback(\n            new TextStreamReader(\n              info,\n              compressed\n                ? inflateRawChunkStream(stream, streamHeader.streamId, this.maxPayloadByteLength)\n                : stream.pipeThrough(ensureOrderedChunks(streamHeader.streamId)),\n              // `totalLength` is the pre-compression size, and the reader sees decompressed bytes,\n              // so it applies to both paths.\n              bigIntToNumber(streamHeader.totalLength),\n            ),\n            { identity: participantIdentity },\n          );\n        }\n        return;\n      }\n    }\n  }\n\n  private handleStreamChunk(chunk: DataStream_Chunk, encryptionType: Encryption_Type) {\n    const fileBuffer = this.byteStreamControllers.get(chunk.streamId);\n    if (fileBuffer) {\n      if (fileBuffer.info.encryptionType !== encryptionType) {\n        fileBuffer.controller.error(\n          new DataStreamError(\n            `Encryption type mismatch for stream ${chunk.streamId}. Expected ${encryptionType}, got ${fileBuffer.info.encryptionType}`,\n            DataStreamErrorReason.EncryptionTypeMismatch,\n          ),\n        );\n        this.byteStreamControllers.delete(chunk.streamId);\n      } else {\n        fileBuffer.controller.enqueue(chunk);\n      }\n    }\n    const textGroup = this.textStreamControllers.get(chunk.streamId);\n    if (textGroup) {\n      if (textGroup.info.encryptionType !== encryptionType) {\n        const error = new DataStreamError(\n          `Encryption type mismatch for stream ${chunk.streamId}. Expected ${encryptionType}, got ${textGroup.info.encryptionType}`,\n          DataStreamErrorReason.EncryptionTypeMismatch,\n        );\n        for (const controller of textGroup.controllers) {\n          controller.error(error);\n        }\n        this.textStreamControllers.delete(chunk.streamId);\n      } else {\n        for (const controller of textGroup.controllers) {\n          controller.enqueue(chunk);\n        }\n      }\n    }\n  }\n\n  private handleStreamTrailer(trailer: DataStream_Trailer, encryptionType: Encryption_Type) {\n    const textGroup = this.textStreamControllers.get(trailer.streamId);\n    if (textGroup) {\n      if (textGroup.info.encryptionType !== encryptionType) {\n        const error = new DataStreamError(\n          `Encryption type mismatch for stream ${trailer.streamId}. Expected ${encryptionType}, got ${textGroup.info.encryptionType}`,\n          DataStreamErrorReason.EncryptionTypeMismatch,\n        );\n        for (const controller of textGroup.controllers) {\n          controller.error(error);\n        }\n      } else {\n        // One `info` per stream, so this merge is visible to every consumer's reader.\n        textGroup.info.attributes = { ...textGroup.info.attributes, ...trailer.attributes };\n        if (trailer.reason) {\n          // A non-empty reason marks an abnormal close by the sender (e.g. an aborted send);\n          // surface it as an error rather than pretending the stream completed.\n          const error = new DataStreamError(\n            `Data stream ${trailer.streamId} closed abnormally: ${trailer.reason}`,\n            DataStreamErrorReason.AbnormalEnd,\n          );\n          for (const controller of textGroup.controllers) {\n            controller.error(error);\n          }\n        } else {\n          for (const controller of textGroup.controllers) {\n            controller.close();\n          }\n        }\n      }\n      this.textStreamControllers.delete(trailer.streamId);\n    }\n\n    const fileBuffer = this.byteStreamControllers.get(trailer.streamId);\n    if (fileBuffer) {\n      if (fileBuffer.info.encryptionType !== encryptionType) {\n        fileBuffer.controller.error(\n          new DataStreamError(\n            `Encryption type mismatch for stream ${trailer.streamId}. Expected ${encryptionType}, got ${fileBuffer.info.encryptionType}`,\n            DataStreamErrorReason.EncryptionTypeMismatch,\n          ),\n        );\n      } else {\n        fileBuffer.info.attributes = { ...fileBuffer.info.attributes, ...trailer.attributes };\n        if (trailer.reason) {\n          // A non-empty reason marks an abnormal close by the sender (e.g. an aborted send);\n          // surface it as an error rather than pretending the stream completed.\n          fileBuffer.controller.error(\n            new DataStreamError(\n              `Data stream ${trailer.streamId} closed abnormally: ${trailer.reason}`,\n              DataStreamErrorReason.AbnormalEnd,\n            ),\n          );\n        } else {\n          fileBuffer.controller.close();\n        }\n      }\n      this.byteStreamControllers.delete(trailer.streamId);\n    }\n  }\n}\n\n/**\n * Builds a `ReadableStream` that yields the given content as a single chunk and then immediately\n * closes - used to surface an inline (single-packet) data stream as a fully-formed stream. `content`\n * may be a promise (e.g. async gzip decompression); a rejection errors the stream.\n */\nfunction createInlineStream(\n  streamId: string,\n  content: Uint8Array | Promise<Uint8Array>,\n): ReadableStream<DataStream_Chunk> {\n  return new ReadableStream<DataStream_Chunk>({\n    start: async (controller) => {\n      const bytes = await content;\n      controller.enqueue(new DataStream_Chunk({ streamId, chunkIndex: BigInt(0), content: bytes }));\n      controller.close();\n    },\n  });\n}\n\n/**\n * Validates that chunks are received in order, dropping duplicates and throwing if gaps are found.\n *\n * Reassembly (and, for compressed streams, a stateful decompressor) silently corrupts on duplicated\n * or out-of-order input, so duplicates are dropped (with a warning - in-order delivery is expected\n * on the reliable channel, but reconnect handling may replay) and a gap is a hard error. Empty\n * chunks consume their index and are then dropped, so they never reach the reader. Applied to every\n * chunked stream, compressed or not.\n */\nfunction ensureOrderedChunks(\n  streamId: string,\n): TransformStream<DataStream_Chunk, DataStream_Chunk> {\n  let lastChunkIndex = -1;\n  return new TransformStream({\n    transform: (value, controller) => {\n      const index = bigIntToNumber(value.chunkIndex);\n      if (index <= lastChunkIndex) {\n        log.warn(\n          `ignoring duplicate chunk ${index} ${value.version > 0 ? `(version ${value.version})` : ''} for data stream ${streamId} (last processed: ${lastChunkIndex})`,\n        );\n        return;\n      }\n      if (index > lastChunkIndex + 1) {\n        throw new DataStreamError(\n          `Missing chunk(s) ${lastChunkIndex + 1}..${index - 1} for data stream ${streamId} - cannot reassemble payload`,\n          DataStreamErrorReason.Incomplete,\n        );\n      }\n      lastChunkIndex = index;\n      if (value.content.length === 0) {\n        return;\n      }\n      controller.enqueue(value);\n    },\n  });\n}\n\n/** Unwraps compressed `DataStream_Chunk`s to their compressed bytes (in `chunkIndex` order), */\nfunction chunksToBytes(): TransformStream<DataStream_Chunk, Uint8Array> {\n  return new TransformStream({\n    transform: (value, controller) => {\n      controller.enqueue(value.content);\n    },\n  });\n}\n\n/** Re-wraps decompressed bytes into contiguous `DataStream_Chunk`s, skipping inflate's empty reads. */\nfunction bytesToChunks(streamId: string): TransformStream<Uint8Array, DataStream_Chunk> {\n  let outIndex = 0;\n  return new TransformStream({\n    transform: (value, controller) => {\n      // Inflate can emit empty reads; only synthesize a chunk when there is content.\n      if (value.byteLength > 0) {\n        controller.enqueue(\n          new DataStream_Chunk({\n            streamId,\n            chunkIndex: numberToBigInt(outIndex),\n            content: value,\n          }),\n        );\n        outIndex += 1;\n      }\n    },\n  });\n}\n\n/**\n * Reframes decompressed byte chunks onto UTF-8 character boundaries via a streaming `TextDecoder`\n * (a write larger than the MTU spans several packets, which may split a codepoint), so each\n * synthesized text chunk decodes independently. The `flush` emits the decoder's trailing bytes.\n */\nfunction bytesToDecodedUtf8(streamId: string): TransformStream<Uint8Array, DataStream_Chunk> {\n  const decoder = new TextDecoder('utf-8');\n  const encoder = new TextEncoder();\n\n  let outIndex = 0;\n  const decodeOrThrow = (bytes?: Uint8Array): string => {\n    try {\n      return bytes ? decoder.decode(bytes, { stream: true }) : decoder.decode();\n    } catch (err) {\n      throw new DataStreamError(\n        `Cannot decode compressed data stream ${streamId} as text: ${err}`,\n        DataStreamErrorReason.DecodeFailed,\n      );\n    }\n  };\n\n  return new TransformStream({\n    transform: (value, controller) => {\n      const text = decodeOrThrow(value);\n      // Everything so far may have been a partial codepoint; only emit once we have characters.\n      if (text.length > 0) {\n        controller.enqueue(\n          new DataStream_Chunk({\n            streamId,\n            chunkIndex: numberToBigInt(outIndex),\n            content: encoder.encode(text),\n          }),\n        );\n        outIndex += 1;\n      }\n    },\n    flush: (controller) => {\n      const tail = decodeOrThrow();\n      if (tail.length > 0) {\n        controller.enqueue(\n          new DataStream_Chunk({\n            streamId,\n            chunkIndex: numberToBigInt(outIndex),\n            content: encoder.encode(tail),\n          }),\n        );\n        outIndex += 1;\n      }\n    },\n  });\n}\n\n/**\n * Transforms a stream of deflate-raw-compressed byte `DataStream_Chunk`s into a stream of\n * decompressed chunks, so `ByteStreamReader` consumes it unchanged. All chunk contents are fed (in\n * `chunkIndex` order) through ONE raw-deflate decompressor for the stream's lifetime; decompressed\n * output is re-wrapped as chunks as soon as it is produced. The sender (sendFile) compresses the\n * whole payload in one shot, but the format also supports a single context-takeover stream\n * sync-flushed at write boundaries, so a future incremental streamBytes could compress with no\n * protocol change. Errors and cancellation propagate through the pipe chain.\n */\nfunction inflateRawByteChunkStream(\n  raw: ReadableStream<DataStream_Chunk>,\n  streamId: string,\n  maxPayloadByteLength: number,\n): ReadableStream<DataStream_Chunk> {\n  return raw\n    .pipeThrough(ensureOrderedChunks(streamId))\n    .pipeThrough(chunksToBytes())\n    .pipeThrough(inflateRawTransform())\n    .pipeThrough(maxDecompressedLengthGuard(streamId, maxPayloadByteLength))\n    .pipeThrough(bytesToChunks(streamId));\n}\n\n/**\n * Transforms a stream of deflate-raw-compressed text `DataStream_Chunk`s into a stream of\n * decompressed chunks, so `TextStreamReader` consumes it unchanged. Builds on\n * {@link inflateRawByteChunkStream} (single decompressor + ordering guard) and adds a streaming\n * `TextDecoder` that reframes the decompressed bytes on UTF-8 character boundaries so each\n * synthesized chunk decodes independently. Errors and cancellation propagate through the pipe chain.\n */\nfunction inflateRawChunkStream(\n  raw: ReadableStream<DataStream_Chunk>,\n  streamId: string,\n  maxPayloadByteLength: number,\n): ReadableStream<DataStream_Chunk> {\n  return raw\n    .pipeThrough(ensureOrderedChunks(streamId))\n    .pipeThrough(chunksToBytes())\n    .pipeThrough(inflateRawTransform())\n    .pipeThrough(maxDecompressedLengthGuard(streamId, maxPayloadByteLength))\n    .pipeThrough(bytesToDecodedUtf8(streamId));\n}\n\n/**\n * Caps the total decompressed byte count of a compressed stream (decompression-bomb guard): a\n * tiny compressed payload can inflate to an arbitrarily large output, so the decompressor's\n * output is bounded rather than trusting the wire size. Exceeding the cap errors the stream with\n * `PayloadTooLarge`.\n */\nfunction maxDecompressedLengthGuard(\n  streamId: string,\n  maxByteLength: number,\n): TransformStream<Uint8Array, Uint8Array> {\n  let total = 0;\n  return new TransformStream({\n    transform: (value, controller) => {\n      total += value.byteLength;\n      if (total > maxByteLength) {\n        throw new DataStreamError(\n          `Data stream ${streamId} exceeds the maximum payload size of ${maxByteLength} bytes`,\n          DataStreamErrorReason.PayloadTooLarge,\n        );\n      }\n      controller.enqueue(value);\n    },\n  });\n}\n"],"names":["IncomingDataStreamManager","EventEmitter","constructor","_ref","arguments","length","undefined","_ref$maxPayloadByteLe","maxPayloadByteLength","DEFAULT_MAX_PAYLOAD_BYTE_LENGTH","_ref$maxOpenStreamsPe","maxOpenStreamsPerParticipant","DEFAULT_MAX_OPEN_STREAMS_PER_PARTICIPANT","log","byteStreamControllers","Map","textStreamControllers","byteStreamHandlers","textStreamHandlers","isConnected","bufferedPackets","setConnected","connected","flushBufferedPackets","packets","_ref2","packet","encryptionType","handleDataStreamPacket","registerTextStreamHandler","topic","callback","has","DataStreamError","concat","DataStreamErrorReason","HandlerAlreadyRegistered","set","unregisterTextStreamHandler","delete","registerByteStreamHandler","unregisterByteStreamHandler","clearControllers","abnormalEndError","AbnormalEnd","_ref3","values","controller","error","group","controllers","clear","validateParticipantHasNoActiveDataStreams","participantIdentity","textStreamsBeingSentByDisconnectingParticipant","Array","from","entries","filter","_ref4","_ref5","_slicedToArray","sendingParticipantIdentity","byteStreamsBeingSentByDisconnectingParticipant","entry","_ref6","_ref7","id","_ref8","_ref9","push","value","case","handleStreamHeader","handleStreamChunk","handleStreamTrailer","Error","hasTooManyOpenStreams","openStreamCount","_ref0","streamHeader","streamId","contentHeader","streamHandlerCallback","get","debug","streamController","info","name","_a","mimeType","size","totalLength","Number","timestamp","bigIntToNumber","attributes","compressed","compression","DataStream_CompressionType","DEFLATE_RAW","isDeflateRawCompressionSupported","warn","NONE","inlineContent","ByteStreamReader","createInlineStream","deflateRawDecompress","identity","stream","ReadableStream","start","AlreadyOpened","startTime","Date","now","cancel","inflateRawByteChunkStream","pipeThrough","ensureOrderedChunks","streamHandlerCallbacks","TRANSCRIPTION_TOPIC","listenerCount","reader","_ref1","emit","applicationCallback","attachedStreamIds","content","TextStreamReader","index","indexOf","splice","inflateRawChunkStream","chunk","fileBuffer","EncryptionTypeMismatch","enqueue","textGroup","trailer","reason","close","__awaiter","bytes","DataStream_Chunk","chunkIndex","BigInt","lastChunkIndex","TransformStream","transform","version","Incomplete","chunksToBytes","bytesToChunks","outIndex","byteLength","numberToBigInt","bytesToDecodedUtf8","decoder","TextDecoder","encoder","TextEncoder","decodeOrThrow","decode","err","DecodeFailed","text","encode","flush","tail","raw","inflateRawTransform","maxDecompressedLengthGuard","maxByteLength","total","PayloadTooLarge"],"mappings":"osBA4Cc,MAAOA,yBAA0B,SAASC,YAA2E,CAAA;AAUjIC,EAAAA,WAAAA,GAG6B;AAAA,IAAA,IAAAC,IAAA,GAAAC,SAAA,CAAAC,MAAA,GAAA,CAAA,IAAAD,SAAA,CAAA,CAAA,CAAA,KAAAE,SAAA,GAAAF,SAAA,CAAA,CAAA,CAAA,GAAF,EAAE;MAAAG,qBAAA,GAAAJ,IAAA,CAF3BK,oBAAoB;AAApBA,MAAAA,oBAAoB,GAAAD,qBAAA,KAAA,MAAA,GAAGE,+BAA+B,GAAAF,qBAAA;MAAAG,qBAAA,GAAAP,IAAA,CACtDQ,4BAA4B;AAA5BA,MAAAA,4BAA4B,GAAAD,qBAAA,KAAA,MAAA,GAAGE,wCAAwC,GAAAF,qBAAA;AAEvE,IAAA,KAAK,EAAE;IAbD,IAAA,CAAAG,GAAG,GAAGA,aAAG;AAkBT,IAAA,IAAA,CAAAC,qBAAqB,GAAG,IAAIC,GAAG,EAA8C;AAE7E,IAAA,IAAA,CAAAC,qBAAqB,GAAG,IAAID,GAAG,EAAqC;AAEpE,IAAA,IAAA,CAAAE,kBAAkB,GAAG,IAAIF,GAAG,EAA6B;AAEzD,IAAA,IAAA,CAAAG,kBAAkB,GA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