Import packages/webrtc/src/rtc-adapter.ts

This commit is contained in:
QQ 2026-11-17 09:19:39 +08:00
parent 63d6a8ea47
commit a5c5568984
1 changed files with 11 additions and 4 deletions

View File

@ -107,7 +107,11 @@ export const RTC_DATA_CHANNEL_OPTIONS = { ordered: true } as const
* package that references the DOM `RTCPeerConnection` global, so Node hosts
* inject their own factory and never import browser natives.
*/
export function browserRtcFactory(): RtcPeerConnectionFactory {
/** Return false only if no send was attempted. Errors propagate without replaying data. */
export type RtcBinarySender = (channel: unknown, data: ArrayBuffer) => boolean
export function browserRtcFactory(options: { sendBinary?: RtcBinarySender } = {}): RtcPeerConnectionFactory {
const binarySender = options.sendBinary
return {
create(configuration) {
// `any` keeps the DOM handler `this`/event typing out of the adapter.
@ -131,7 +135,7 @@ export function browserRtcFactory(): RtcPeerConnectionFactory {
get onicecandidate() { return raw.onicecandidate as ((event: { candidate: RtcIceCandidateInit | null }) => void) | null },
set ondatachannel(value) { raw.ondatachannel = value },
get ondatachannel() { return raw.ondatachannel as ((event: { channel: RtcDataChannel }) => void) | null },
createDataChannel(label, options) { return adaptDataChannel(raw.createDataChannel(label, options)) },
createDataChannel(label, options) { return adaptDataChannel(raw.createDataChannel(label, options), binarySender) },
createOffer() { return raw.createOffer() },
createAnswer() { return raw.createAnswer() },
setLocalDescription(description) { return raw.setLocalDescription(description) },
@ -233,7 +237,7 @@ function summarizeIpv6Scope(address: string): RtcAddressScope {
return 'public'
}
function adaptDataChannel(raw: RTCDataChannel): RtcDataChannel {
function adaptDataChannel(raw: RTCDataChannel, sendBinary?: RtcBinarySender): RtcDataChannel {
return {
get label(): string { return raw.label },
get ordered(): boolean { return raw.ordered },
@ -251,7 +255,10 @@ function adaptDataChannel(raw: RTCDataChannel): RtcDataChannel {
get onerror() { return raw.onerror as (() => void) | null },
set onbufferedamountlow(value) { raw.onbufferedamountlow = value },
get onbufferedamountlow() { return raw.onbufferedamountlow as (() => void) | null },
send(data) { raw.send(data as never) },
send(data) {
if (data instanceof ArrayBuffer && sendBinary?.(raw, data)) return
raw.send(data as never)
},
close() { raw.close() },
}
}