UNPKG

@libp2p/mplex

Version:

JavaScript implementation of https://github.com/libp2p/mplex

58 lines 2.13 kB
import { AbstractStream } from '@libp2p/utils/abstract-stream'; import { Uint8ArrayList } from 'uint8arraylist'; import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string'; import { MAX_MSG_SIZE } from './decode.js'; import { InitiatorMessageTypes, ReceiverMessageTypes } from './message-types.js'; export class MplexStream extends AbstractStream { name; streamId; send; types; maxDataSize; constructor(init) { super(init); this.types = init.direction === 'outbound' ? InitiatorMessageTypes : ReceiverMessageTypes; this.send = init.send; this.name = init.name; this.streamId = init.streamId; this.maxDataSize = init.maxDataSize; } async sendNewStream() { await this.send({ id: this.streamId, type: InitiatorMessageTypes.NEW_STREAM, data: new Uint8ArrayList(uint8ArrayFromString(this.name)) }); } async sendData(data) { data = data.sublist(); while (data.byteLength > 0) { const toSend = Math.min(data.byteLength, this.maxDataSize); await this.send({ id: this.streamId, type: this.types.MESSAGE, data: data.sublist(0, toSend) }); data.consume(toSend); } } async sendReset() { await this.send({ id: this.streamId, type: this.types.RESET }); } async sendCloseWrite() { await this.send({ id: this.streamId, type: this.types.CLOSE }); } async sendCloseRead() { // mplex does not support close read, only close write } } export function createStream(options) { const { id, name, send, onEnd, type = 'initiator', maxMsgSize = MAX_MSG_SIZE } = options; return new MplexStream({ id: type === 'initiator' ? (`i${id}`) : `r${id}`, streamId: id, name: `${name ?? id}`, direction: type === 'initiator' ? 'outbound' : 'inbound', maxDataSize: maxMsgSize, onEnd, send, log: options.logger.forComponent(`libp2p:mplex:stream:${type}:${id}`) }); } //# sourceMappingURL=stream.js.map