{"version":3,"file":"extension.mjs","sources":["../../../../src/room/data-stream/extension.ts"],"sourcesContent":["import type { DataPacket, Encryption_Type } from '@livekit/protocol';\nimport type { RoomDataStreamOptions } from '../../options';\nimport { CLIENT_PROTOCOL_DEFAULT } from '../../version';\nimport { ConnectionState } from '../CoreRoom';\nimport type { CoreRoom } from '../CoreRoom';\nimport { RoomEvent } from '../events';\nimport {\n  type ConnectionHooks,\n  type DataPacketOwner,\n  type EngineHooks,\n  type ExtensionContext,\n  type LocalParticipantApiProvider,\n  type RoomApiProvider,\n  type SlotProvider,\n  defineExtension,\n} from '../extensions';\nimport type Participant from '../participant/Participant';\nimport { ParticipantAgentAttributes } from '../participant/attributes';\nimport { Track } from '../track/Track';\nimport TranscriptionStreamConverter from '../transcription/TranscriptionStreamConverter';\nimport type {\n  ByteStreamInfo,\n  SendBytesOptions,\n  SendFileOptions,\n  SendTextOptions,\n  StreamBytesOptions,\n  StreamTextOptions,\n  TextStreamInfo,\n} from '../types';\nimport IncomingDataStreamManager from './incoming/IncomingDataStreamManager';\nimport type { ByteStreamHandler, TextStreamHandler } from './incoming/StreamReader';\nimport OutgoingDataStreamManager from './outgoing/OutgoingDataStreamManager';\nimport type { ByteStreamWriter, TextStreamWriter } from './outgoing/StreamWriter';\n\n/**\n * Methods the `dataStreams` extension adds to the room.\n * @experimental\n */\nexport interface DataStreamRoomApi {\n  registerTextStreamHandler(topic: string, callback: TextStreamHandler): void;\n  unregisterTextStreamHandler(topic: string): void;\n  registerByteStreamHandler(topic: string, callback: ByteStreamHandler): void;\n  unregisterByteStreamHandler(topic: string): void;\n}\n\n/**\n * Methods the `dataStreams` extension adds to the local participant.\n * @experimental\n */\nexport interface DataStreamLocalParticipantApi {\n  /**\n   * Sends the given string to participants in the room via the data channel.\n   * For longer messages, consider using {@link streamText} instead.\n   *\n   * @param text The text payload\n   * @param options.topic Topic identifier used to route the stream to appropriate handlers.\n   */\n  sendText(text: string, options?: SendTextOptions): Promise<TextStreamInfo>;\n\n  /**\n   * Creates a new TextStreamWriter which can be used to stream text incrementally\n   * to participants in the room via the data channel.\n   *\n   * @param options.topic Topic identifier used to route the stream to appropriate handlers.\n   *\n   * @internal\n   * @experimental CAUTION, might get removed in a minor release\n   */\n  streamText(options?: StreamTextOptions): Promise<TextStreamWriter>;\n\n  /** Send a File to all participants in the room via the data channel.\n   * @param file The File object payload\n   * @param options.topic Topic identifier used to route the stream to appropriate handlers.\n   * @param options.onProgress A callback function used to monitor the upload progress percentage.\n   */\n  sendFile(file: File, options?: SendFileOptions): Promise<{ id: string }>;\n\n  /**\n   * Sends the given bytes to participants in the room via the data channel.\n   * For files, consider using {@link sendFile}; for longer/incremental payloads, {@link streamBytes}.\n   *\n   * @param bytes The byte payload\n   * @param options.topic Topic identifier used to route the stream to appropriate handlers.\n   */\n  sendBytes(bytes: Uint8Array, options?: SendBytesOptions): Promise<ByteStreamInfo>;\n\n  /**\n   * Stream bytes incrementally to participants in the room via the data channel.\n   * For sending files, consider using {@link sendFile} instead.\n   *\n   * @param options.topic Topic identifier used to route the stream to appropriate handlers.\n   */\n  streamBytes(options?: StreamBytesOptions): Promise<ByteStreamWriter>;\n}\n\n/**\n * Text and byte streams (`sendText`, `sendFile`, `registerTextStreamHandler`, ...).\n * @experimental\n */\nexport const dataStreams = /* @__PURE__ */ defineExtension(\n  'dataStreams',\n  [],\n  (\n    room: CoreRoom,\n    ctx: ExtensionContext,\n    streamOptions: RoomDataStreamOptions | undefined,\n  ): RoomApiProvider<DataStreamRoomApi> &\n    LocalParticipantApiProvider<DataStreamLocalParticipantApi> &\n    SlotProvider<'byteStreamOpener'> &\n    DataPacketOwner &\n    EngineHooks &\n    ConnectionHooks & {\n      incoming: IncomingDataStreamManager;\n      outgoing: OutgoingDataStreamManager;\n    } => {\n    const incoming = new IncomingDataStreamManager(streamOptions ?? room.options.dataStream);\n    const outgoing = new OutgoingDataStreamManager(\n      room.engine,\n      ctx.log,\n      (identity) =>\n        room.remoteParticipants.get(identity)?.clientProtocol ?? CLIENT_PROTOCOL_DEFAULT,\n      (identity) => room.remoteParticipants.get(identity)?.capabilities ?? [],\n      () => Array.from(room.remoteParticipants.keys()),\n    );\n\n    const getMicrophoneTrackSid = (identity: Participant['identity']): string | undefined => {\n      const participant = room.getParticipantByIdentity(identity);\n      for (const publication of participant?.trackPublications.values() ?? []) {\n        if (publication.source === Track.Source.Microphone) {\n          return publication.trackSid;\n        }\n      }\n      return undefined;\n    };\n\n    const getDelegatingPublisherIdentity = (\n      identity: Participant['identity'],\n    ): string | undefined => {\n      // An avatar worker carries `lk.publish_on_behalf` naming the agent it speaks for.\n      for (const participant of room.remoteParticipants.values()) {\n        if (participant.attributes[ParticipantAgentAttributes.PublishOnBehalf] === identity) {\n          return participant.identity;\n        }\n      }\n      return undefined;\n    };\n\n    const transcriptionStreamConverter = new TranscriptionStreamConverter({\n      onTranscription: (transcription) => ctx.handleTranscription(transcription),\n      getMicrophoneTrackSid,\n      getDelegatingPublisherIdentity,\n    });\n    incoming.on('transcriptionStreamArrived', ({ reader, participantIdentity }) => {\n      transcriptionStreamConverter.handleTextStream(reader, participantIdentity);\n    });\n\n    const onStreamPacket = (_value: unknown, packet: DataPacket, encryptionType: Encryption_Type) =>\n      incoming.handleDataStreamPacket(packet, encryptionType);\n\n    room\n      .on(RoomEvent.ConnectionStateChanged, (state) =>\n        incoming.setConnected(state === ConnectionState.Connected),\n      )\n      .on(RoomEvent.ParticipantDisconnected, (participant) =>\n        incoming.validateParticipantHasNoActiveDataStreams(participant.identity),\n      );\n\n    return {\n      incoming,\n      outgoing,\n      // The preconnect audio buffer is sent as a byte stream from inside the core publish path.\n      byteStreamOpener: (options) => outgoing.streamBytes(options),\n      dataPackets: {\n        streamHeader: onStreamPacket,\n        streamChunk: onStreamPacket,\n        streamTrailer: onStreamPacket,\n      },\n      onEngineCreated: (engine) => outgoing.setupEngine(engine),\n      onDisconnect: () => {\n        transcriptionStreamConverter.reset();\n        incoming.clearControllers();\n      },\n      room: {\n        registerTextStreamHandler: (topic, callback) =>\n          incoming.registerTextStreamHandler(topic, callback),\n        unregisterTextStreamHandler: (topic) => incoming.unregisterTextStreamHandler(topic),\n        registerByteStreamHandler: (topic, callback) =>\n          incoming.registerByteStreamHandler(topic, callback),\n        unregisterByteStreamHandler: (topic) => incoming.unregisterByteStreamHandler(topic),\n      },\n      localParticipant: {\n        sendText: (text, options) => outgoing.sendText(text, options),\n        streamText: (options) => outgoing.streamText(options),\n        sendFile: (file, options) => outgoing.sendFile(file, options),\n        sendBytes: (bytes, options) => outgoing.sendBytes(bytes, options),\n        streamBytes: (options) => outgoing.streamBytes(options),\n      },\n    };\n  },\n);\n"],"names":["dataStreams","defineExtension","room","ctx","streamOptions","incoming","IncomingDataStreamManager","options","dataStream","outgoing","OutgoingDataStreamManager","engine","log","identity","_a","_b","remoteParticipants","get","clientProtocol","CLIENT_PROTOCOL_DEFAULT","capabilities","Array","from","keys","getMicrophoneTrackSid","participant","getParticipantByIdentity","publication","trackPublications","values","source","Track","Source","Microphone","trackSid","undefined","getDelegatingPublisherIdentity","attributes","ParticipantAgentAttributes","PublishOnBehalf","transcriptionStreamConverter","TranscriptionStreamConverter","onTranscription","transcription","handleTranscription","on","_ref","reader","participantIdentity","handleTextStream","onStreamPacket","_value","packet","encryptionType","handleDataStreamPacket","RoomEvent","ConnectionStateChanged","state","setConnected","ConnectionState","Connected","ParticipantDisconnected","validateParticipantHasNoActiveDataStreams","byteStreamOpener","streamBytes","dataPackets","streamHeader","streamChunk","streamTrailer","onEngineCreated","setupEngine","onDisconnect","reset","clearControllers","registerTextStreamHandler","topic","callback","unregisterTextStreamHandler","registerByteStreamHandler","unregisterByteStreamHandler","localParticipant","sendText","text","streamText","sendFile","file","sendBytes","bytes"],"mappings":"siBA+FA;;;AAGG;MACUA,WAAW,kBAAmBC,eAAe,CACxD,aAAa,EACb,EAAE,EACF,CACEC,IAAc,EACdC,GAAqB,EACrBC,aAAgD,KAS5C;EACJ,MAAMC,QAAQ,GAAG,IAAIC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