@libp2p/webrtc 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/LICENSE +4 -0
  2. package/README.md +210 -0
  3. package/dist/index.min.js +54 -0
  4. package/dist/index.min.js.map +7 -0
  5. package/dist/proto_ts/message.d.ts +56 -0
  6. package/dist/proto_ts/message.d.ts.map +1 -0
  7. package/dist/proto_ts/message.js +86 -0
  8. package/dist/proto_ts/message.js.map +1 -0
  9. package/dist/src/error.d.ts +54 -0
  10. package/dist/src/error.d.ts.map +1 -0
  11. package/dist/src/error.js +105 -0
  12. package/dist/src/error.js.map +1 -0
  13. package/dist/src/index.d.ts +4 -0
  14. package/dist/src/index.d.ts.map +1 -0
  15. package/dist/src/index.js +6 -0
  16. package/dist/src/index.js.map +1 -0
  17. package/dist/src/maconn.d.ts +43 -0
  18. package/dist/src/maconn.d.ts.map +1 -0
  19. package/dist/src/maconn.js +29 -0
  20. package/dist/src/maconn.js.map +1 -0
  21. package/dist/src/muxer.d.ts +55 -0
  22. package/dist/src/muxer.d.ts.map +1 -0
  23. package/dist/src/muxer.js +92 -0
  24. package/dist/src/muxer.js.map +1 -0
  25. package/dist/src/options.d.ts +6 -0
  26. package/dist/src/options.d.ts.map +1 -0
  27. package/dist/src/options.js +2 -0
  28. package/dist/src/options.js.map +1 -0
  29. package/dist/src/sdp.d.ts +33 -0
  30. package/dist/src/sdp.d.ts.map +1 -0
  31. package/dist/src/sdp.js +118 -0
  32. package/dist/src/sdp.js.map +1 -0
  33. package/dist/src/stream.d.ts +141 -0
  34. package/dist/src/stream.d.ts.map +1 -0
  35. package/dist/src/stream.js +290 -0
  36. package/dist/src/stream.js.map +1 -0
  37. package/dist/src/transport.d.ts +60 -0
  38. package/dist/src/transport.d.ts.map +1 -0
  39. package/dist/src/transport.js +193 -0
  40. package/dist/src/transport.js.map +1 -0
  41. package/dist/src/util.d.ts +5 -0
  42. package/dist/src/util.d.ts.map +1 -0
  43. package/dist/src/util.js +5 -0
  44. package/dist/src/util.js.map +1 -0
  45. package/dist/stats.json +1 -0
  46. package/package.json +170 -0
  47. package/proto_ts/message.ts +105 -0
  48. package/src/error.ts +123 -0
  49. package/src/index.ts +6 -0
  50. package/src/maconn.ts +67 -0
  51. package/src/message.proto +22 -0
  52. package/src/muxer.ts +120 -0
  53. package/src/options.ts +4 -0
  54. package/src/sdp.ts +136 -0
  55. package/src/stream.ts +422 -0
  56. package/src/transport.ts +243 -0
  57. package/src/util.ts +5 -0
@@ -0,0 +1,118 @@
1
+ import { logger } from '@libp2p/logger';
2
+ import '@multiformats/multiaddr';
3
+ import { bases } from 'multiformats/basics';
4
+ import * as multihashes from 'multihashes';
5
+ import { inappropriateMultiaddr, invalidArgument, invalidFingerprint, unsupportedHashAlgorithm } from './error.js';
6
+ import { CERTHASH_CODE } from './transport.js';
7
+ const log = logger('libp2p:webrtc:sdp');
8
+ /**
9
+ * Get base2 | identity decoders
10
+ */
11
+ export const mbdecoder = (function () {
12
+ const decoders = Object.values(bases).map((b) => b.decoder);
13
+ let acc = decoders[0].or(decoders[1]);
14
+ decoders.slice(2).forEach((d) => (acc = acc.or(d)));
15
+ return acc;
16
+ })();
17
+ /**
18
+ * Get base2 | identity decoders
19
+ */
20
+ function ipv(ma) {
21
+ for (const proto of ma.protoNames()) {
22
+ if (proto.startsWith('ip')) {
23
+ return proto.toUpperCase();
24
+ }
25
+ }
26
+ log('Warning: multiaddr does not appear to contain IP4 or IP6, defaulting to IP6', ma);
27
+ return 'IP6';
28
+ }
29
+ // Extract the certhash from a multiaddr
30
+ export function certhash(ma) {
31
+ const tups = ma.stringTuples();
32
+ const certhash = tups.filter((tup) => tup[0] === CERTHASH_CODE).map((tup) => tup[1])[0];
33
+ if (certhash === undefined || certhash === '') {
34
+ throw inappropriateMultiaddr(`Couldn't find a certhash component of multiaddr: ${ma.toString()}`);
35
+ }
36
+ return certhash;
37
+ }
38
+ /**
39
+ * Convert a certhash into a multihash
40
+ */
41
+ export function decodeCerthash(certhash) {
42
+ const mbdecoded = mbdecoder.decode(certhash);
43
+ return multihashes.decode(mbdecoded);
44
+ }
45
+ /**
46
+ * Extract the fingerprint from a multiaddr
47
+ */
48
+ export function ma2Fingerprint(ma) {
49
+ // certhash_value is a multibase encoded multihash encoded string
50
+ const mhdecoded = decodeCerthash(certhash(ma));
51
+ const prefix = toSupportedHashFunction(mhdecoded.name);
52
+ const fingerprint = mhdecoded.digest.reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');
53
+ const sdp = fingerprint.match(/.{1,2}/g);
54
+ if (sdp == null) {
55
+ throw invalidFingerprint(fingerprint, ma.toString());
56
+ }
57
+ return [`${prefix.toUpperCase()} ${sdp.join(':').toUpperCase()}`, fingerprint];
58
+ }
59
+ /**
60
+ * Normalize the hash name from a given multihash has name
61
+ */
62
+ export function toSupportedHashFunction(name) {
63
+ switch (name) {
64
+ case 'sha1':
65
+ return 'sha-1';
66
+ case 'sha2-256':
67
+ return 'sha-256';
68
+ case 'sha2-512':
69
+ return 'sha-512';
70
+ default:
71
+ throw unsupportedHashAlgorithm(name);
72
+ }
73
+ }
74
+ /**
75
+ * Convert a multiaddr into a SDP
76
+ */
77
+ function ma2sdp(ma, ufrag) {
78
+ const { host, port } = ma.toOptions();
79
+ const ipVersion = ipv(ma);
80
+ const [CERTFP] = ma2Fingerprint(ma);
81
+ return `v=0
82
+ o=- 0 0 IN ${ipVersion} ${host}
83
+ s=-
84
+ c=IN ${ipVersion} ${host}
85
+ t=0 0
86
+ a=ice-lite
87
+ m=application ${port} UDP/DTLS/SCTP webrtc-datachannel
88
+ a=mid:0
89
+ a=setup:passive
90
+ a=ice-ufrag:${ufrag}
91
+ a=ice-pwd:${ufrag}
92
+ a=fingerprint:${CERTFP}
93
+ a=sctp-port:5000
94
+ a=max-message-size:100000
95
+ a=candidate:1467250027 1 UDP 1467250027 ${host} ${port} typ host\r\n`;
96
+ }
97
+ /**
98
+ * Create an answer SDP from a multiaddr
99
+ */
100
+ export function fromMultiAddr(ma, ufrag) {
101
+ return {
102
+ type: 'answer',
103
+ sdp: ma2sdp(ma, ufrag)
104
+ };
105
+ }
106
+ /**
107
+ * Replace (munge) the ufrag and password values in a SDP
108
+ */
109
+ export function munge(desc, ufrag) {
110
+ if (desc.sdp === undefined) {
111
+ throw invalidArgument("Can't munge a missing SDP");
112
+ }
113
+ desc.sdp = desc.sdp
114
+ .replace(/\na=ice-ufrag:[^\n]*\n/, '\na=ice-ufrag:' + ufrag + '\n')
115
+ .replace(/\na=ice-pwd:[^\n]*\n/, '\na=ice-pwd:' + ufrag + '\n');
116
+ return desc;
117
+ }
118
+ //# sourceMappingURL=sdp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sdp.js","sourceRoot":"","sources":["../../src/sdp.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAA;AACvC,OAA0B,yBAAyB,CAAA;AACnD,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAA;AAC3C,OAAO,KAAK,WAAW,MAAM,aAAa,CAAA;AAE1C,OAAO,EAAE,sBAAsB,EAAE,eAAe,EAAE,kBAAkB,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAA;AAClH,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAA;AAE9C,MAAM,GAAG,GAAG,MAAM,CAAC,mBAAmB,CAAC,CAAA;AAEvC;;GAEG;AACH,MAAM,CAAC,MAAM,SAAS,GAAQ,CAAC;IAC7B,MAAM,QAAQ,GAAG,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAA;IAC3D,IAAI,GAAG,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAA;IACrC,QAAQ,CAAC,KAAK,CAAC,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,OAAO;aACI,SAAS,IAAI,IAAI;;OAEvB,SAAS,IAAI,IAAI;;;gBAGR,IAAI;;;cAGN,KAAK;YACP,KAAK;gBACD,MAAM;;;0CAGoB,IAAI,IAAI,IAAI,eAAe,CAAA;AACrE,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,aAAa,CAAE,EAAa,EAAE,KAAa;IACzD,OAAO;QACL,IAAI,EAAE,QAAQ;QACd,GAAG,EAAE,MAAM,CAAC,EAAE,EAAE,KAAK,CAAC;KACvB,CAAA;AACH,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,KAAK,CAAE,IAA+B,EAAE,KAAa;IACnE,IAAI,IAAI,CAAC,GAAG,KAAK,SAAS,EAAE;QAC1B,MAAM,eAAe,CAAC,2BAA2B,CAAC,CAAA;KACnD;IAED,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,GAAG;SAChB,OAAO,CAAC,wBAAwB,EAAE,gBAAgB,GAAG,KAAK,GAAG,IAAI,CAAC;SAClE,OAAO,CAAC,sBAAsB,EAAE,cAAc,GAAG,KAAK,GAAG,IAAI,CAAC,CAAA;IACjE,OAAO,IAAI,CAAA;AACb,CAAC"}
@@ -0,0 +1,141 @@
1
+ import { Stream, StreamStat, Direction } from '@libp2p/interface-connection';
2
+ import { DeferredPromise } from 'p-defer';
3
+ import { Source, Sink } from 'it-stream-types';
4
+ import { Uint8ArrayList } from 'uint8arraylist';
5
+ import * as pb from '../proto_ts/message.js';
6
+ /**
7
+ * Constructs a default StreamStat
8
+ */
9
+ export declare function defaultStat(dir: Direction): StreamStat;
10
+ interface StreamInitOpts {
11
+ /**
12
+ * The network channel used for bidirectional peer-to-peer transfers of
13
+ * arbitrary data
14
+ *
15
+ * {@link https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel}
16
+ */
17
+ channel: RTCDataChannel;
18
+ /**
19
+ * User defined stream metadata
20
+ */
21
+ metadata?: Record<string, any>;
22
+ /**
23
+ * Stats about this stream
24
+ */
25
+ stat: StreamStat;
26
+ /**
27
+ * Callback to invoke when the stream is closed.
28
+ */
29
+ closeCb?: (stream: WebRTCStream) => void;
30
+ }
31
+ interface StreamStateInput {
32
+ /**
33
+ * Outbound conections are opened by the local node, inbound streams are
34
+ * opened by the remote
35
+ */
36
+ direction: 'inbound' | 'outbound';
37
+ /**
38
+ * Message flag from the protobuffs
39
+ *
40
+ * 0 = FIN
41
+ * 1 = STOP_SENDING
42
+ * 2 = RESET
43
+ */
44
+ flag: pb.Message_Flag;
45
+ }
46
+ export declare enum StreamStates {
47
+ OPEN = 0,
48
+ READ_CLOSED = 1,
49
+ WRITE_CLOSED = 2,
50
+ CLOSED = 3
51
+ }
52
+ declare class StreamState {
53
+ state: StreamStates;
54
+ transition({ direction, flag }: StreamStateInput): [StreamStates, StreamStates];
55
+ }
56
+ export declare class WebRTCStream implements Stream {
57
+ /**
58
+ * Unique identifier for a stream
59
+ */
60
+ id: string;
61
+ /**
62
+ * Stats about this stream
63
+ */
64
+ stat: StreamStat;
65
+ /**
66
+ * User defined stream metadata
67
+ */
68
+ metadata: Record<string, any>;
69
+ /**
70
+ * The data channel used to send and receive data
71
+ */
72
+ private readonly channel;
73
+ /**
74
+ * The current state of the stream
75
+ */
76
+ streamState: StreamState;
77
+ /**
78
+ * Read unwrapped protobuf data from the underlying datachannel.
79
+ * _src is exposed to the user via the `source` getter to .
80
+ */
81
+ private readonly _src;
82
+ /**
83
+ * push data from the underlying datachannel to the length prefix decoder
84
+ * and then the protobuf decoder.
85
+ */
86
+ private readonly _innersrc;
87
+ /**
88
+ * Write data to the remote peer.
89
+ * It takes care of wrapping data in a protobuf and adding the length prefix.
90
+ */
91
+ sink: Sink<Uint8ArrayList | Uint8Array, Promise<void>>;
92
+ /**
93
+ * Deferred promise that resolves when the underlying datachannel is in the
94
+ * open state.
95
+ */
96
+ opened: DeferredPromise<void>;
97
+ /**
98
+ * Triggers a generator which can be used to close the sink.
99
+ */
100
+ closeWritePromise: DeferredPromise<void>;
101
+ /**
102
+ * Callback to invoke when the stream is closed.
103
+ */
104
+ closeCb?: (stream: WebRTCStream) => void;
105
+ constructor(opts: StreamInitOpts);
106
+ set source(_src: Source<Uint8ArrayList>);
107
+ get source(): Source<Uint8ArrayList>;
108
+ /**
109
+ * Closable sink
110
+ */
111
+ private _sinkFn;
112
+ /**
113
+ * Handle incoming
114
+ */
115
+ processIncomingProtobuf(buffer: Uint8Array): Uint8Array | undefined;
116
+ /**
117
+ * Close a stream for reading and writing
118
+ */
119
+ close(): void;
120
+ /**
121
+ * Close a stream for reading only
122
+ */
123
+ closeRead(): void;
124
+ /**
125
+ * Close a stream for writing only
126
+ */
127
+ closeWrite(): void;
128
+ /**
129
+ * Call when a local error occurs, should close the stream for reading and writing
130
+ */
131
+ abort(err: Error): void;
132
+ /**
133
+ * Close the stream for writing, and indicate to the remote side this is being done 'abruptly'
134
+ *
135
+ * @see closeWrite
136
+ */
137
+ reset(): void;
138
+ private _sendFlag;
139
+ }
140
+ export {};
141
+ //# sourceMappingURL=stream.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stream.d.ts","sourceRoot":"","sources":["../../src/stream.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,8BAA8B,CAAA;AAM5E,OAAc,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AAChD,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAA;AAC9C,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAA;AAE/C,OAAO,KAAK,EAAE,MAAM,wBAAwB,CAAA;AAI5C;;GAEG;AACH,wBAAgB,WAAW,CAAE,GAAG,EAAE,SAAS,GAAG,UAAU,CAQvD;AAED,UAAU,cAAc;IACtB;;;;;OAKG;IACH,OAAO,EAAE,cAAc,CAAA;IAEvB;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;IAE9B;;O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E,cAAc;IAqEjC,IAAI,MAAM,CAAE,IAAI,EAAE,MAAM,CAAC,cAAc,CAAC,EAAK;IAE7C,IAAI,MAAM,IAAK,MAAM,CAAC,cAAc,CAAC,CAEpC;IAED;;OAEG;YACW,OAAO;IA6BrB;;OAEG;IACH,uBAAuB,CAAE,MAAM,EAAE,UAAU,GAAG,UAAU,GAAG,SAAS;IA2BpE;;OAEG;IACH,KAAK,IAAK,IAAI;IAYd;;OAEG;IACH,SAAS,IAAK,IAAI;IAalB;;OAEG;IACH,UAAU,IAAK,IAAI;IAanB;;OAEG;IACH,KAAK,CAAE,GAAG,EAAE,KAAK,GAAG,IAAI;IAKxB;;;;OAIG;IACH,KAAK,IAAK,IAAI;IAUd,OAAO,CAAC,SAAS;CAWnB"}
@@ -0,0 +1,290 @@
1
+ import '@libp2p/interface-connection';
2
+ import { logger } from '@libp2p/logger';
3
+ import * as lengthPrefixed from 'it-length-prefixed';
4
+ import merge from 'it-merge';
5
+ import { pipe } from 'it-pipe';
6
+ import { pushable } from 'it-pushable';
7
+ import defer from 'p-defer';
8
+ import 'it-stream-types';
9
+ import { Uint8ArrayList } from 'uint8arraylist';
10
+ import * as pb from '../proto_ts/message.js';
11
+ const log = logger('libp2p:webrtc:stream');
12
+ /**
13
+ * Constructs a default StreamStat
14
+ */
15
+ export function defaultStat(dir) {
16
+ return {
17
+ direction: dir,
18
+ timeline: {
19
+ open: 0,
20
+ close: undefined
21
+ }
22
+ };
23
+ }
24
+ export var StreamStates;
25
+ (function (StreamStates) {
26
+ StreamStates[StreamStates["OPEN"] = 0] = "OPEN";
27
+ StreamStates[StreamStates["READ_CLOSED"] = 1] = "READ_CLOSED";
28
+ StreamStates[StreamStates["WRITE_CLOSED"] = 2] = "WRITE_CLOSED";
29
+ StreamStates[StreamStates["CLOSED"] = 3] = "CLOSED";
30
+ })(StreamStates || (StreamStates = {}));
31
+ class StreamState {
32
+ constructor() {
33
+ this.state = StreamStates.OPEN;
34
+ }
35
+ transition({ direction, flag }) {
36
+ const prev = this.state;
37
+ // return early if the stream is closed
38
+ if (this.state === StreamStates.CLOSED) {
39
+ return [prev, StreamStates.CLOSED];
40
+ }
41
+ if (direction === 'inbound') {
42
+ switch (flag) {
43
+ case pb.Message_Flag.FIN:
44
+ if (this.state === StreamStates.OPEN) {
45
+ this.state = StreamStates.READ_CLOSED;
46
+ }
47
+ else if (this.state === StreamStates.WRITE_CLOSED) {
48
+ this.state = StreamStates.CLOSED;
49
+ }
50
+ break;
51
+ case pb.Message_Flag.STOP_SENDING:
52
+ if (this.state === StreamStates.OPEN) {
53
+ this.state = StreamStates.WRITE_CLOSED;
54
+ }
55
+ else if (this.state === StreamStates.READ_CLOSED) {
56
+ this.state = StreamStates.CLOSED;
57
+ }
58
+ break;
59
+ case pb.Message_Flag.RESET:
60
+ this.state = StreamStates.CLOSED;
61
+ break;
62
+ // no default
63
+ }
64
+ }
65
+ else {
66
+ switch (flag) {
67
+ case pb.Message_Flag.FIN:
68
+ if (this.state === StreamStates.OPEN) {
69
+ this.state = StreamStates.WRITE_CLOSED;
70
+ }
71
+ else if (this.state === StreamStates.READ_CLOSED) {
72
+ this.state = StreamStates.CLOSED;
73
+ }
74
+ break;
75
+ case pb.Message_Flag.STOP_SENDING:
76
+ if (this.state === StreamStates.OPEN) {
77
+ this.state = StreamStates.READ_CLOSED;
78
+ }
79
+ else if (this.state === StreamStates.WRITE_CLOSED) {
80
+ this.state = StreamStates.CLOSED;
81
+ }
82
+ break;
83
+ case pb.Message_Flag.RESET:
84
+ this.state = StreamStates.CLOSED;
85
+ break;
86
+ // no default
87
+ }
88
+ }
89
+ return [prev, this.state];
90
+ }
91
+ }
92
+ export class WebRTCStream {
93
+ constructor(opts) {
94
+ /**
95
+ * The current state of the stream
96
+ */
97
+ this.streamState = new StreamState();
98
+ /**
99
+ * push data from the underlying datachannel to the length prefix decoder
100
+ * and then the protobuf decoder.
101
+ */
102
+ this._innersrc = pushable();
103
+ /**
104
+ * Deferred promise that resolves when the underlying datachannel is in the
105
+ * open state.
106
+ */
107
+ this.opened = defer();
108
+ /**
109
+ * Triggers a generator which can be used to close the sink.
110
+ */
111
+ this.closeWritePromise = defer();
112
+ this.channel = opts.channel;
113
+ this.id = this.channel.label;
114
+ this.stat = opts.stat;
115
+ switch (this.channel.readyState) {
116
+ case 'open':
117
+ this.opened.resolve();
118
+ break;
119
+ case 'closed':
120
+ case 'closing':
121
+ this.streamState.state = StreamStates.CLOSED;
122
+ if (this.stat.timeline.close === undefined || this.stat.timeline.close === 0) {
123
+ this.stat.timeline.close = new Date().getTime();
124
+ }
125
+ this.opened.resolve();
126
+ break;
127
+ // no default
128
+ }
129
+ this.metadata = opts.metadata ?? {};
130
+ // closable sink
131
+ this.sink = this._sinkFn;
132
+ // handle RTCDataChannel events
133
+ this.channel.onopen = (_evt) => {
134
+ this.stat.timeline.open = new Date().getTime();
135
+ this.opened.resolve();
136
+ };
137
+ this.channel.onclose = (_evt) => {
138
+ this.close();
139
+ };
140
+ this.channel.onerror = (evt) => {
141
+ const err = evt.error;
142
+ this.abort(err);
143
+ };
144
+ const self = this;
145
+ // reader pipe
146
+ this.channel.onmessage = async ({ data }) => {
147
+ if (data === null || data.length === 0) {
148
+ return;
149
+ }
150
+ this._innersrc.push(new Uint8Array(data));
151
+ };
152
+ // pipe framed protobuf messages through a length prefixed decoder, and
153
+ // surface data from the `Message.message` field through a source.
154
+ this._src = pipe(this._innersrc, lengthPrefixed.decode(), (source) => (async function* () {
155
+ for await (const buf of source) {
156
+ const message = self.processIncomingProtobuf(buf.subarray());
157
+ if (message != null) {
158
+ yield new Uint8ArrayList(message);
159
+ }
160
+ }
161
+ })());
162
+ }
163
+ // If user attempts to set a new source this should be a noop
164
+ set source(_src) { }
165
+ get source() {
166
+ return this._src;
167
+ }
168
+ /**
169
+ * Closable sink
170
+ */
171
+ async _sinkFn(src) {
172
+ await this.opened.promise;
173
+ const isClosed = (state) => state === StreamStates.CLOSED || state === StreamStates.WRITE_CLOSED;
174
+ if (isClosed(this.streamState.state)) {
175
+ return;
176
+ }
177
+ const self = this;
178
+ const closeWriteIterable = {
179
+ async *[Symbol.asyncIterator]() {
180
+ await self.closeWritePromise.promise;
181
+ yield new Uint8Array(0);
182
+ }
183
+ };
184
+ for await (const buf of merge(closeWriteIterable, src)) {
185
+ if (isClosed(self.streamState.state)) {
186
+ return;
187
+ }
188
+ const msgbuf = pb.Message.toBinary({ message: buf.subarray() });
189
+ const sendbuf = lengthPrefixed.encode.single(msgbuf);
190
+ this.channel.send(sendbuf.subarray());
191
+ }
192
+ }
193
+ /**
194
+ * Handle incoming
195
+ */
196
+ processIncomingProtobuf(buffer) {
197
+ const message = pb.Message.fromBinary(buffer);
198
+ if (message.flag !== undefined) {
199
+ const [currentState, nextState] = this.streamState.transition({ direction: 'inbound', flag: message.flag });
200
+ if (currentState !== nextState) {
201
+ // @TODO(ddimaria): determine if we need to check for StreamStates.OPEN
202
+ switch (nextState) {
203
+ case StreamStates.READ_CLOSED:
204
+ this._innersrc.end();
205
+ break;
206
+ case StreamStates.WRITE_CLOSED:
207
+ this.closeWritePromise.resolve();
208
+ break;
209
+ case StreamStates.CLOSED:
210
+ this.close();
211
+ break;
212
+ // no default
213
+ }
214
+ }
215
+ }
216
+ return message.message;
217
+ }
218
+ /**
219
+ * Close a stream for reading and writing
220
+ */
221
+ close() {
222
+ this.stat.timeline.close = new Date().getTime();
223
+ this.streamState.state = StreamStates.CLOSED;
224
+ this._innersrc.end();
225
+ this.closeWritePromise.resolve();
226
+ this.channel.close();
227
+ if (this.closeCb !== undefined) {
228
+ this.closeCb(this);
229
+ }
230
+ }
231
+ /**
232
+ * Close a stream for reading only
233
+ */
234
+ closeRead() {
235
+ const [currentState, nextState] = this.streamState.transition({ direction: 'outbound', flag: pb.Message_Flag.STOP_SENDING });
236
+ if (currentState === StreamStates.OPEN || currentState === StreamStates.WRITE_CLOSED) {
237
+ this._sendFlag(pb.Message_Flag.STOP_SENDING);
238
+ (this._innersrc).end();
239
+ }
240
+ if (currentState !== nextState && nextState === StreamStates.CLOSED) {
241
+ this.close();
242
+ }
243
+ }
244
+ /**
245
+ * Close a stream for writing only
246
+ */
247
+ closeWrite() {
248
+ const [currentState, nextState] = this.streamState.transition({ direction: 'outbound', flag: pb.Message_Flag.FIN });
249
+ if (currentState === StreamStates.OPEN || currentState === StreamStates.READ_CLOSED) {
250
+ this._sendFlag(pb.Message_Flag.FIN);
251
+ this.closeWritePromise.resolve();
252
+ }
253
+ if (currentState !== nextState && nextState === StreamStates.CLOSED) {
254
+ this.close();
255
+ }
256
+ }
257
+ /**
258
+ * Call when a local error occurs, should close the stream for reading and writing
259
+ */
260
+ abort(err) {
261
+ log.error(`An error occurred, clost the stream for reading and writing: ${err.message}`);
262
+ this.close();
263
+ }
264
+ /**
265
+ * Close the stream for writing, and indicate to the remote side this is being done 'abruptly'
266
+ *
267
+ * @see closeWrite
268
+ */
269
+ reset() {
270
+ this.stat = defaultStat(this.stat.direction);
271
+ const [currentState, nextState] = this.streamState.transition({ direction: 'outbound', flag: pb.Message_Flag.RESET });
272
+ if (currentState !== nextState) {
273
+ this._sendFlag(pb.Message_Flag.RESET);
274
+ this.close();
275
+ }
276
+ }
277
+ _sendFlag(flag) {
278
+ try {
279
+ log.trace('Sending flag: %s', flag.toString());
280
+ const msgbuf = pb.Message.toBinary({ flag: flag });
281
+ this.channel.send(lengthPrefixed.encode.single(msgbuf).subarray());
282
+ }
283
+ catch (err) {
284
+ if (err instanceof Error) {
285
+ log.error(`Exception while sending flag ${flag}: ${err.message}`);
286
+ }
287
+ }
288
+ }
289
+ }
290
+ //# sourceMappingURL=stream.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stream.js","sourceRoot":"","sources":["../../src/stream.ts"],"names":[],"mappings":"AAAA,OAA8C,8BAA8B,CAAA;AAC5E,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAA;AACvC,OAAO,KAAK,cAAc,MAAM,oBAAoB,CAAA;AACpD,OAAO,KAAK,MAA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AAgE,GAAG,CAAC,OAAO,EAAE,CAAC,CAAA;QACxF,IAAI,CAAC,KAAK,EAAE,CAAA;IACd,CAAC;IAED;;;;OAIG;IACH,KAAK;QACH,IAAI,CAAC,IAAI,GAAG,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,CAAA;QAC5C,MAAM,CAAC,YAAY,EAAE,SAAS,CAAC,GAAG,IAAI,CAAC,WAAW,CAAC,UAAU,CAAC,EAAE,SAAS,EAAE,UAAU,EAAE,IAAI,EAAE,EAAE,CAAC,YAAY,CAAC,KAAK,EAAE,CAAC,CAAA;QAErH,IAAI,YAAY,KAAK,SAAS,EAAE;YAC9B,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC,YAAY,CAAC,KAAK,CAAC,CAAA;YACrC,IAAI,CAAC,KAAK,EAAE,CAAA;SACb;IACH,CAAC;IAEO,SAAS,CAAE,IAAqB;QACtC,IAAI;YACF,GAAG,CAAC,KAAK,CAAC,kBAAkB,EAAE,IAAI,CAAC,QAAQ,EAAE,CAAC,CAAA;YAC9C,MAAM,MAAM,GAAG,EAAE,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAA;YAClD,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,cAAc,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAA;SACnE;QAAC,OAAO,GAAG,EAAE;YACZ,IAAI,GAAG,YAAY,KAAK,EAAE;gBACxB,GAAG,CAAC,KAAK,CAAC,gCAAgC,IAAI,KAAK,GAAG,CAAC,OAAO,EAAE,CAAC,CAAA;aAClE;SACF;IACH,CAAC;CACH"}
@@ -0,0 +1,60 @@
1
+ import { Connection } from '@libp2p/interface-connection';
2
+ import type { PeerId } from '@libp2p/interface-peer-id';
3
+ import { CreateListenerOptions, Listener, symbol, Transport } from '@libp2p/interface-transport';
4
+ import { Multiaddr } from '@multiformats/multiaddr';
5
+ import { WebRTCDialOptions } from './options.js';
6
+ /**
7
+ * Created by converting the hexadecimal protocol code to an integer.
8
+ *
9
+ * {@link https://github.com/multiformats/multiaddr/blob/master/protocols.csv}
10
+ */
11
+ export declare const WEBRTC_CODE: number;
12
+ /**
13
+ * Created by converting the hexadecimal protocol code to an integer.
14
+ *
15
+ * {@link https://github.com/multiformats/multiaddr/blob/master/protocols.csv}
16
+ */
17
+ export declare const CERTHASH_CODE: number;
18
+ /**
19
+ * The peer for this transport
20
+ */
21
+ export interface WebRTCTransportComponents {
22
+ peerId: PeerId;
23
+ }
24
+ export declare class WebRTCTransport implements Transport {
25
+ /**
26
+ * The peer for this transport
27
+ */
28
+ private readonly components;
29
+ constructor(components: WebRTCTransportComponents);
30
+ /**
31
+ * Dial a given multiaddr
32
+ */
33
+ dial(ma: Multiaddr, options: WebRTCDialOptions): Promise<Connection>;
34
+ /**
35
+ * Create transport listeners no supported by browsers
36
+ */
37
+ createListener(options: CreateListenerOptions): Listener;
38
+ /**
39
+ * Takes a list of `Multiaddr`s and returns only valid addresses for the transport
40
+ */
41
+ filter(multiaddrs: Multiaddr[]): Multiaddr[];
42
+ /**
43
+ * Implement toString() for WebRTCTransport
44
+ */
45
+ get [Symbol.toStringTag](): string;
46
+ /**
47
+ * Symbol.for('@libp2p/transport')
48
+ */
49
+ get [symbol](): true;
50
+ /**
51
+ * Connect to a peer using a multiaddr
52
+ */
53
+ _connect(ma: Multiaddr, options: WebRTCDialOptions): Promise<Connection>;
54
+ /**
55
+ * Generate a noise prologue from the peer connection's certificate.
56
+ * noise prologue = bytes('libp2p-webrtc-noise:') + noise-responder fingerprint + noise-initiator fingerprint
57
+ */
58
+ private generateNoisePrologue;
59
+ }
60
+ //# sourceMappingURL=transport.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../../src/transport.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,8BAA8B,CAAA;AACzD,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