{"version":3,"file":"extension.mjs","sources":["../../../../src/room/rpc/extension.ts"],"sourcesContent":["import { RpcClientManager, RpcError, type RpcInvocationData, RpcServerManager } from '.';\nimport type TypedPromise from '../../utils/TypedPromise';\nimport { CLIENT_PROTOCOL_DEFAULT } from '../../version';\nimport type { CoreRoom } from '../CoreRoom';\nimport { DataChannelKind } from '../data-channel/types';\nimport { dataStreams } from '../data-stream/extension';\nimport { RoomEvent } from '../events';\nimport type {\n  ConnectionHooks,\n  DataPacketOwner,\n  ExtensionContext,\n  LocalParticipantApiProvider,\n  RoomApiProvider,\n  RoomExtension,\n} from '../extensions';\nimport {\n  type PerformRpcParams,\n  RPC_REQUEST_DATA_STREAM_TOPIC,\n  RPC_RESPONSE_DATA_STREAM_TOPIC,\n} from './utils';\n\n/**\n * Methods the `rpc` extension adds to the room.\n * @experimental\n */\nexport interface RpcRoomApi {\n  /**\n   * Establishes the participant as a receiver for calls of the specified RPC method.\n   *\n   * @param method - The name of the indicated RPC method\n   * @param handler - Will be invoked when an RPC request for this method is received\n   * @returns A promise that resolves when the method is successfully registered\n   * @throws {Error} If a handler for this method is already registered (must call unregisterRpcMethod first)\n   *\n   * @example\n   * ```typescript\n   * room.localParticipant?.registerRpcMethod(\n   *   'greet',\n   *   async (data: RpcInvocationData) => {\n   *     console.log(`Received greeting from ${data.callerIdentity}: ${data.payload}`);\n   *     return `Hello, ${data.callerIdentity}!`;\n   *   }\n   * );\n   * ```\n   *\n   * The handler should return a Promise that resolves to a string.\n   * If unable to respond within `responseTimeout`, the request will result in an error on the caller's side.\n   *\n   * You may throw errors of type `RpcError` with a string `message` in the handler,\n   * and they will be received on the caller's side with the message intact.\n   * Other errors thrown in your handler will not be transmitted as-is, and will instead arrive to the caller as `1500` (\"Application Error\").\n   */\n  registerRpcMethod(method: string, handler: (data: RpcInvocationData) => Promise<string>): void;\n\n  /**\n   * Unregisters a previously registered RPC method.\n   *\n   * @param method - The name of the RPC method to unregister\n   */\n  unregisterRpcMethod(method: string): void;\n}\n\n/**\n * Methods the `rpc` extension adds to the local participant.\n * @experimental\n */\nexport interface RpcLocalParticipantApi {\n  /**\n   * Initiate an RPC call to a remote participant\n   * @param params - Parameters for initiating the RPC call, see {@link PerformRpcParams}\n   * @returns A promise that resolves with the response payload or rejects with an error.\n   * @throws Error on failure. Details in `message`.\n   */\n  performRpc(params: PerformRpcParams): TypedPromise<string, RpcError>;\n}\n\n/**\n * RPC over the room (`performRpc`, `registerRpcMethod`). Requires {@link dataStreams}.\n * @experimental\n */\nexport const rpc = {\n  key: /* @__PURE__ */ Symbol('lk.extension.rpc'),\n  requires: [dataStreams] as const,\n  install(\n    room: CoreRoom,\n    ctx: ExtensionContext,\n  ): RoomApiProvider<RpcRoomApi> &\n    LocalParticipantApiProvider<RpcLocalParticipantApi> &\n    DataPacketOwner &\n    ConnectionHooks {\n    const { incoming, outgoing } = ctx.get(dataStreams);\n    const clientProtocol = (identity: string) =>\n      room.remoteParticipants.get(identity)?.clientProtocol ?? CLIENT_PROTOCOL_DEFAULT;\n\n    const client = new RpcClientManager(\n      ctx.log,\n      outgoing,\n      clientProtocol,\n      () => room.engine?.serverVersion,\n    );\n    client.on('sendDataPacket', ({ packet }) => {\n      room.engine?.sendDataPacket(packet, DataChannelKind.RELIABLE);\n    });\n    const server = new RpcServerManager(ctx.log, outgoing, clientProtocol);\n    server.on('sendDataPacket', ({ packet }) => {\n      room.engine?.sendDataPacket(packet, DataChannelKind.RELIABLE);\n    });\n\n    incoming.registerTextStreamHandler(\n      RPC_REQUEST_DATA_STREAM_TOPIC,\n      async (reader, { identity }) => {\n        await server.handleIncomingDataStream(reader, identity, reader.info.attributes ?? {});\n      },\n    );\n    incoming.registerTextStreamHandler(\n      RPC_RESPONSE_DATA_STREAM_TOPIC,\n      async (reader, { identity }) => {\n        await client.handleIncomingDataStream(reader, identity, reader.info.attributes ?? {});\n      },\n    );\n\n    room.on(RoomEvent.ParticipantDisconnected, (participant) =>\n      client.handleParticipantDisconnected(participant.identity),\n    );\n\n    const registerRpcMethod: RpcRoomApi['registerRpcMethod'] = (method, handler) =>\n      server.registerRpcMethod(method, handler);\n    const unregisterRpcMethod: RpcRoomApi['unregisterRpcMethod'] = (method) =>\n      server.unregisterRpcMethod(method);\n\n    return {\n      dataPackets: {\n        rpcRequest: (request, packet) => {\n          server.handleIncomingRpcRequest(packet.participantIdentity, request);\n        },\n        rpcResponse: (response) => {\n          switch (response.value.case) {\n            case 'payload':\n              client.handleIncomingRpcResponseSuccess(response.requestId, response.value.value);\n              break;\n            case 'error':\n              client.handleIncomingRpcResponseFailure(\n                response.requestId,\n                RpcError.fromProto(response.value.value),\n              );\n              break;\n            default:\n              ctx.log.warn(`Unknown rpcResponse.value.case: ${response.value.case}`);\n              break;\n          }\n        },\n        rpcAck: (ack) => client.handleIncomingRpcAck(ack.requestId),\n      },\n      onDisconnect: () => client.handleRoomDisconnected(),\n      room: { registerRpcMethod, unregisterRpcMethod },\n      localParticipant: {\n        performRpc: (params) =>\n          client.performRpc(params).then(([_id, completionPromise]) => completionPromise),\n      },\n    };\n  },\n} satisfies RoomExtension<RpcRoomApi, RpcLocalParticipantApi>;\n"],"names":["rpc","key","Symbol","requires","dataStreams","install","room","ctx","_ctx$get","get","incoming","outgoing","clientProtocol","identity","_a","_b","remoteParticipants","CLIENT_PROTOCOL_DEFAULT","client","RpcClientManager","log","engine","serverVersion","on","_ref","packet","sendDataPacket","DataChannelKind","RELIABLE","server","RpcServerManager","_ref2","registerTextStreamHandler","RPC_REQUEST_DATA_STREAM_TOPIC","reader_1","__awaiter","reader","_ref3","handleIncomingDataStream","info","attributes","RPC_RESPONSE_DATA_STREAM_TOPIC","_ref4","RoomEvent","ParticipantDisconnected","participant","handleParticipantDisconnected","registerRpcMethod","method","handler","unregisterRpcMethod","dataPackets","rpcRequest","request","handleIncomingRpcRequest","participantIdentity","rpcResponse","response","value","case","handleIncomingRpcResponseSuccess","requestId","handleIncomingRpcResponseFailure","RpcError","fromProto","warn","concat","rpcAck","ack","handleIncomingRpcAck","onDisconnect","handleRoomDisconnected","localParticipant","performRpc","params","then","_ref5","_ref6","_slicedToArray","_id","completionPromise"],"mappings":"8hBA4EA;;;AAGG;AACI,MAAMA,GAAG,GAAG;AACjBC,EAAAA,GAAG,iBAAkBC,MAAM,CAAC,kBAAkB,CAAC;EAC/CC,QAAQ,EAAE,CAACC,WAAW,CAAU;AAChCC,EAAAA,OAAOA,CACLC,IAAc,EACdC,GAAqB,EAAA;AAKrB,IAAA,MAAAC,QAAA,GAA+BD,GAAG,CAACE,GAAG,CAACL,WAAW,CAAC;MAA3CM,QAAQ,GAAAF,QAAA,CAARE,QAAQ;MAAEC,QAAQ,GAAAH,QAAA,CAARG,QAAQ;IAC1B,MAAMC,cAAc,GAAIC,QAAgB,IAAI;MAAA,IAAAC,EAAA,EAAAC,EAAA;AAC1C,MAAA,OAAA,CAAAA,EAAA,GAAA,CAAAD,EAAA,GAAAR,IAAI,CAACU,kBAAkB,CAACP,GAAG,CAACI,QAAQ,CAAC,MAAA,IAAA,IAAAC,EAAA,KAAA,MAAA,GAAA,MAAA,GAAAA,EAAA,CAAEF,cAAc,MAAA,IAAA,IAAAG,EAAA,KAAA,MAAA,GAAAA,EAAA,GAAIE,uBAAuB;IAAA,CAAA;AAElF,IAAA,MAAMC,MAAM,GAAG,IAAIC,gBAAgB,CACjCZ,GAAG,CAACa,GAAG,EACPT,QAAQ,EACRC,cAAc,EACd,MAAK;AAAA,MAAA,IAAAE,EAAA;AAAC,MAAA,OAAA,CAAAA,EAAA,GAAAR,IAAI,CAACe,MAAM,MAAA,IAAA,IAAAP,EAAA,KAAA,MAAA,GAAA,MAAA,GAAAA,EAAA,CAAEQ,aAAa;AAAA,IAAA,CAAA,CACjC;AACDJ,IAAAA,MAAM,CAACK,EAAE,CAAC,gBAAgB,EAAEC,IAAA,IAAe;AAAA,MAAA,IAAZC,MAAM,GAAAD,IAAA,CAANC,MAAM;;MACnC,CAAAX,EAAA,GAAAR,IAAI,CAACe,MAAM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