nerdbank-streams 2.9.112 → 2.10.37-alpha

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 (44) hide show
  1. package/js/Channel.d.ts +9 -8
  2. package/js/Channel.js +21 -14
  3. package/js/Channel.js.map +1 -1
  4. package/js/ControlCode.d.ts +6 -6
  5. package/js/ControlCode.js +6 -6
  6. package/js/ControlCode.js.map +1 -1
  7. package/js/Deferred.js.map +1 -1
  8. package/js/FrameHeader.d.ts +2 -2
  9. package/js/FrameHeader.js +2 -2
  10. package/js/FrameHeader.js.map +1 -1
  11. package/js/FullDuplexStream.d.ts +1 -1
  12. package/js/FullDuplexStream.js +2 -0
  13. package/js/FullDuplexStream.js.map +1 -1
  14. package/js/MultiplexingStream.d.ts +19 -19
  15. package/js/MultiplexingStream.js +67 -63
  16. package/js/MultiplexingStream.js.map +1 -1
  17. package/js/MultiplexingStreamFormatters.d.ts +9 -7
  18. package/js/MultiplexingStreamFormatters.js +50 -22
  19. package/js/MultiplexingStreamFormatters.js.map +1 -1
  20. package/js/MultiplexingStreamOptions.d.ts +1 -1
  21. package/js/QualifiedChannelId.js +10 -4
  22. package/js/QualifiedChannelId.js.map +1 -1
  23. package/js/Utilities.d.ts +3 -3
  24. package/js/Utilities.js +61 -18
  25. package/js/Utilities.js.map +1 -1
  26. package/js/index.d.ts +8 -8
  27. package/js/index.js.map +1 -1
  28. package/package.json +16 -6
  29. package/src/AcceptanceParameters.ts +2 -2
  30. package/src/Channel.ts +279 -277
  31. package/src/ChannelOptions.ts +2 -2
  32. package/src/ControlCode.ts +25 -25
  33. package/src/Deferred.ts +61 -61
  34. package/src/FrameHeader.ts +35 -35
  35. package/src/FullDuplexStream.ts +25 -23
  36. package/src/IChannelOfferEventArgs.ts +12 -12
  37. package/src/IDisposableObservable.ts +2 -2
  38. package/src/MultiplexingStream.ts +731 -727
  39. package/src/MultiplexingStreamFormatters.ts +355 -326
  40. package/src/MultiplexingStreamOptions.ts +16 -16
  41. package/src/OfferParameters.ts +4 -4
  42. package/src/QualifiedChannelId.ts +27 -21
  43. package/src/Utilities.ts +159 -114
  44. package/src/index.ts +8 -8
@@ -1,21 +1,21 @@
1
- import { ChannelOptions } from "./ChannelOptions";
1
+ import { ChannelOptions } from './ChannelOptions'
2
2
 
3
3
  export interface MultiplexingStreamOptions {
4
- /**
5
- * The protocol version to be used.
6
- * @description 1 is the original version. 2 is a protocol breaking change and adds backpressure support. 3 is a protocol breaking change, eliminates the handshake packet and adds seeded channels support.
7
- */
8
- protocolMajorVersion?: number;
4
+ /**
5
+ * The protocol version to be used.
6
+ * @description 1 is the original version. 2 is a protocol breaking change and adds backpressure support. 3 is a protocol breaking change, eliminates the handshake packet and adds seeded channels support.
7
+ */
8
+ protocolMajorVersion?: number
9
9
 
10
- /** The number of received bytes that may be buffered locally per channel (transmitted from the remote party but not yet processed). */
11
- defaultChannelReceivingWindowSize?: number;
10
+ /** The number of received bytes that may be buffered locally per channel (transmitted from the remote party but not yet processed). */
11
+ defaultChannelReceivingWindowSize?: number
12
12
 
13
- /**
14
- * A list of options for channels that are to be "seeded" into a new MultiplexingStream.
15
- * @description Seeded channels avoid the need for a round-trip for an offer/accept packet exchange.
16
- * Seeded channels are accessed within the MultiplexingStream instance by calling AcceptChannel(ulong, ChannelOptions?)
17
- * with the 0-based index into this list used as the channel ID.
18
- * They are only supported when ProtocolMajorVersion is at least 3.
19
- */
20
- seededChannels?: ChannelOptions[];
13
+ /**
14
+ * A list of options for channels that are to be "seeded" into a new MultiplexingStream.
15
+ * @description Seeded channels avoid the need for a round-trip for an offer/accept packet exchange.
16
+ * Seeded channels are accessed within the MultiplexingStream instance by calling AcceptChannel(ulong, ChannelOptions?)
17
+ * with the 0-based index into this list used as the channel ID.
18
+ * They are only supported when ProtocolMajorVersion is at least 3.
19
+ */
20
+ seededChannels?: ChannelOptions[]
21
21
  }
@@ -1,7 +1,7 @@
1
1
  export interface OfferParameters {
2
- /** The name of the channel. */
3
- name: string;
2
+ /** The name of the channel. */
3
+ name: string
4
4
 
5
- /** The maximum number of bytes that may be transmitted and not yet acknowledged as processed by the remote party. */
6
- remoteWindowSize?: number;
5
+ /** The maximum number of bytes that may be transmitted and not yet acknowledged as processed by the remote party. */
6
+ remoteWindowSize?: number
7
7
  }
@@ -1,9 +1,9 @@
1
1
  export interface QualifiedChannelId {
2
- /** Gets the channel ID. */
3
- readonly id: number;
2
+ /** Gets the channel ID. */
3
+ readonly id: number
4
4
 
5
- /** Gets a value indicating where the channel originated. */
6
- readonly source: ChannelSource;
5
+ /** Gets a value indicating where the channel originated. */
6
+ readonly source: ChannelSource
7
7
  }
8
8
 
9
9
  /**
@@ -12,27 +12,33 @@ export interface QualifiedChannelId {
12
12
  * while leaving the Seeded value unchanged.
13
13
  */
14
14
  export enum ChannelSource {
15
- /** The channel was offered by this MultiplexingStream instance to the other party. */
16
- Local = 1,
15
+ /** The channel was offered by this MultiplexingStream instance to the other party. */
16
+ // eslint-disable-next-line @typescript-eslint/naming-convention
17
+ Local = 1,
17
18
 
18
- /** The channel was offered to this MultiplexingStream instance by the other party. */
19
- Remote = -1,
19
+ /** The channel was offered to this MultiplexingStream instance by the other party. */
20
+ // eslint-disable-next-line @typescript-eslint/naming-convention
21
+ Remote = -1,
20
22
 
21
- /**
22
- * The channel was seeded during construction via the Options.SeededChannels collection.
23
- * This channel is to be accepted by both parties.
24
- */
25
- Seeded = 0,
23
+ /**
24
+ * The channel was seeded during construction via the Options.SeededChannels collection.
25
+ * This channel is to be accepted by both parties.
26
+ */
27
+ // eslint-disable-next-line @typescript-eslint/naming-convention
28
+ Seeded = 0,
26
29
  }
27
30
 
28
31
  // tslint:disable-next-line: no-namespace
29
32
  export namespace QualifiedChannelId {
30
- export function toString(id: QualifiedChannelId): string {
31
- const sourceName =
32
- id.source === ChannelSource.Local ? "local" :
33
- id.source === ChannelSource.Remote ? "remote" :
34
- id.source === ChannelSource.Seeded ? "seeded" :
35
- "unknown";
36
- return `${id.id} (${sourceName})`;
37
- }
33
+ export function toString(id: QualifiedChannelId): string {
34
+ const sourceName =
35
+ id.source === ChannelSource.Local
36
+ ? 'local'
37
+ : id.source === ChannelSource.Remote
38
+ ? 'remote'
39
+ : id.source === ChannelSource.Seeded
40
+ ? 'seeded'
41
+ : 'unknown'
42
+ return `${id.id} (${sourceName})`
43
+ }
38
44
  }
package/src/Utilities.ts CHANGED
@@ -1,138 +1,183 @@
1
- import CancellationToken from "cancellationtoken";
2
- import { Readable, Writable } from "stream";
3
- import { Deferred } from "./Deferred";
4
- import { IDisposableObservable } from "./IDisposableObservable";
1
+ import CancellationToken from 'cancellationtoken'
2
+ import { Readable, Writable } from 'stream'
3
+ import { Deferred } from './Deferred'
4
+ import { IDisposableObservable } from './IDisposableObservable'
5
5
 
6
6
  export async function writeAsync(stream: NodeJS.WritableStream, chunk: any) {
7
- return new Promise<void>((resolve, reject) => {
8
- stream.write(chunk, (err: Error | null | undefined) => {
9
- if (err) {
10
- reject(err);
11
- } else {
12
- resolve();
13
- }
14
- });
15
- });
7
+ return new Promise<void>((resolve, reject) => {
8
+ stream.write(chunk, (err: Error | null | undefined) => {
9
+ if (err) {
10
+ reject(err)
11
+ } else {
12
+ resolve()
13
+ }
14
+ })
15
+ })
16
16
  }
17
17
 
18
18
  export function writeSubstream(stream: NodeJS.WritableStream): NodeJS.WritableStream {
19
- return new Writable({
20
- async write(chunk: Buffer, _: string, callback: (error?: Error | null) => void) {
21
- try {
22
- const dv = new DataView(new ArrayBuffer(4));
23
- dv.setUint32(0, chunk.length, false);
24
- await writeAsync(stream, Buffer.from(dv.buffer));
25
- await writeAsync(stream, chunk);
26
- callback();
27
- } catch (err) {
28
- callback(err as Error);
29
- }
30
- },
31
- final(callback: (error?: Error | null) => void) {
32
- // Write the terminating 0 length sequence.
33
- stream.write(new Uint8Array(4), callback);
34
- },
35
- });
19
+ return new Writable({
20
+ async write(chunk: Buffer, _: string, callback: (error?: Error | null) => void) {
21
+ try {
22
+ const dv = new DataView(new ArrayBuffer(4))
23
+ dv.setUint32(0, chunk.length, false)
24
+ await writeAsync(stream, Buffer.from(dv.buffer))
25
+ await writeAsync(stream, chunk)
26
+ callback()
27
+ } catch (err) {
28
+ callback(err as Error)
29
+ }
30
+ },
31
+ final(callback: (error?: Error | null) => void) {
32
+ // Write the terminating 0 length sequence.
33
+ stream.write(new Uint8Array(4), callback)
34
+ },
35
+ })
36
36
  }
37
37
 
38
38
  export function readSubstream(stream: NodeJS.ReadableStream): NodeJS.ReadableStream {
39
- return new Readable({
40
- async read(_: number) {
41
- const lenBuffer = await getBufferFrom(stream, 4);
42
- const dv = new DataView(lenBuffer.buffer, lenBuffer.byteOffset, lenBuffer.length);
43
- const chunkSize = dv.getUint32(0, false);
44
- if (chunkSize === 0) {
45
- this.push(null);
46
- return;
47
- }
48
-
49
- // TODO: make this *stream* instead of read as an atomic chunk.
50
- const payload = await getBufferFrom(stream, chunkSize);
51
- this.push(payload);
52
- },
53
- });
39
+ return new Readable({
40
+ async read(_: number) {
41
+ const lenBuffer = await getBufferFrom(stream, 4)
42
+ const dv = new DataView(lenBuffer.buffer, lenBuffer.byteOffset, lenBuffer.length)
43
+ const chunkSize = dv.getUint32(0, false)
44
+ if (chunkSize === 0) {
45
+ this.push(null)
46
+ return
47
+ }
48
+
49
+ // TODO: make this *stream* instead of read as an atomic chunk.
50
+ const payload = await getBufferFrom(stream, chunkSize)
51
+ this.push(payload)
52
+ },
53
+ })
54
54
  }
55
55
 
56
56
  export async function getBufferFrom(
57
- readable: NodeJS.ReadableStream,
58
- size: number,
59
- allowEndOfStream?: false,
60
- cancellationToken?: CancellationToken): Promise<Buffer>;
57
+ readable: NodeJS.ReadableStream,
58
+ size: number,
59
+ allowEndOfStream?: false,
60
+ cancellationToken?: CancellationToken
61
+ ): Promise<Buffer>
61
62
 
62
63
  export async function getBufferFrom(
63
- readable: NodeJS.ReadableStream,
64
- size: number,
65
- allowEndOfStream: true,
66
- cancellationToken?: CancellationToken): Promise<Buffer | null>;
64
+ readable: NodeJS.ReadableStream,
65
+ size: number,
66
+ allowEndOfStream: true,
67
+ cancellationToken?: CancellationToken
68
+ ): Promise<Buffer | null>
67
69
 
68
70
  export async function getBufferFrom(
69
- readable: NodeJS.ReadableStream,
70
- size: number,
71
- allowEndOfStream: boolean = false,
72
- cancellationToken?: CancellationToken): Promise<Buffer | null> {
73
-
74
- const streamEnded = new Deferred<void>();
75
- while (size > 0) {
76
- cancellationToken?.throwIfCancelled();
77
-
78
- const readBuffer = readable.read(size) as Buffer;
79
- if (readBuffer === null) {
80
- const bytesAvailable = new Deferred<void>();
81
- readable.once("readable", bytesAvailable.resolve.bind(bytesAvailable));
82
- readable.once("end", streamEnded.resolve.bind(streamEnded));
83
- const endPromise = Promise.race([bytesAvailable.promise, streamEnded.promise]);
84
- await (cancellationToken ? cancellationToken.racePromise(endPromise) : endPromise);
85
-
86
- if (bytesAvailable.isCompleted) {
87
- continue;
88
- }
89
- }
90
-
91
- if (!allowEndOfStream) {
92
- if (!readBuffer || readBuffer.length < size) {
93
- throw new Error("Stream terminated before required bytes were read.");
94
- }
95
- }
96
-
97
- return readBuffer;
98
- }
99
-
100
- return new Buffer([]);
71
+ readable: NodeJS.ReadableStream,
72
+ size: number,
73
+ allowEndOfStream: boolean = false,
74
+ cancellationToken?: CancellationToken
75
+ ): Promise<Buffer | null> {
76
+ const streamEnded = new Deferred<void>()
77
+
78
+ if (size === 0) {
79
+ return Buffer.from([])
80
+ }
81
+
82
+ let readBuffer: Buffer | null = null
83
+ let index: number = 0
84
+ while (size > 0) {
85
+ cancellationToken?.throwIfCancelled()
86
+ let availableSize = (readable as Readable).readableLength
87
+ if (!availableSize) {
88
+ // Check the end of stream
89
+ if ((readable as Readable).readableEnded || streamEnded.isCompleted) {
90
+ // stream is closed
91
+ if (!allowEndOfStream) {
92
+ throw new Error('Stream terminated before required bytes were read.')
93
+ }
94
+
95
+ // Returns what has been read so far
96
+ if (readBuffer === null) {
97
+ return null
98
+ }
99
+
100
+ // we need trim extra spaces
101
+ return readBuffer.subarray(0, index)
102
+ }
103
+
104
+ // we retain this behavior when availableSize === false
105
+ // to make existing unit tests happy (which assumes we will try to read stream when no data is ready.)
106
+ availableSize = size
107
+ } else if (availableSize > size) {
108
+ availableSize = size
109
+ }
110
+
111
+ const newBuffer = readable.read(availableSize) as Buffer
112
+ if (newBuffer) {
113
+ if (newBuffer.length < availableSize && !allowEndOfStream) {
114
+ throw new Error('Stream terminated before required bytes were read.')
115
+ }
116
+
117
+ if (readBuffer === null) {
118
+ if (availableSize === size || newBuffer.length < availableSize) {
119
+ // in the fast pass, we read the entire data once, and donot allocate an extra array.
120
+ return newBuffer
121
+ }
122
+
123
+ // if we read partial data, we need allocate a buffer to join all data together.
124
+ readBuffer = Buffer.alloc(size)
125
+ }
126
+
127
+ // now append new data to the buffer
128
+ newBuffer.copy(readBuffer, index)
129
+
130
+ size -= newBuffer.length
131
+ index += newBuffer.length
132
+ }
133
+
134
+ if (size > 0) {
135
+ const bytesAvailable = new Deferred<void>()
136
+ const bytesAvailableCallback = bytesAvailable.resolve.bind(bytesAvailable)
137
+ const streamEndedCallback = streamEnded.resolve.bind(streamEnded)
138
+ readable.once('readable', bytesAvailableCallback)
139
+ readable.once('end', streamEndedCallback)
140
+ try {
141
+ const endPromise = Promise.race([bytesAvailable.promise, streamEnded.promise])
142
+ await (cancellationToken ? cancellationToken.racePromise(endPromise) : endPromise)
143
+ } finally {
144
+ readable.removeListener('readable', bytesAvailableCallback)
145
+ readable.removeListener('end', streamEndedCallback)
146
+ }
147
+ }
148
+ }
149
+
150
+ return readBuffer
101
151
  }
102
152
 
103
153
  export function throwIfDisposed(value: IDisposableObservable) {
104
- if (value.isDisposed) {
105
- throw new Error("disposed");
106
- }
154
+ if (value.isDisposed) {
155
+ throw new Error('disposed')
156
+ }
107
157
  }
108
158
 
109
- export function requireInteger(
110
- parameterName: string,
111
- value: number,
112
- serializedByteLength: number,
113
- signed: "unsigned" | "signed" = "signed"): void {
114
-
115
- if (!Number.isInteger(value)) {
116
- throw new Error(`${parameterName} must be an integer.`);
117
- }
118
-
119
- let bits = serializedByteLength * 8;
120
- if (signed === "signed") {
121
- bits--;
122
- }
123
-
124
- const maxValue = Math.pow(2, bits) - 1;
125
- const minValue = signed === "signed" ? -Math.pow(2, bits) : 0;
126
- if (value > maxValue || value < minValue) {
127
- throw new Error(`${parameterName} must be in the range ${minValue}-${maxValue}.`);
128
- }
159
+ export function requireInteger(parameterName: string, value: number, serializedByteLength: number, signed: 'unsigned' | 'signed' = 'signed'): void {
160
+ if (!Number.isInteger(value)) {
161
+ throw new Error(`${parameterName} must be an integer.`)
162
+ }
163
+
164
+ let bits = serializedByteLength * 8
165
+ if (signed === 'signed') {
166
+ bits--
167
+ }
168
+
169
+ const maxValue = Math.pow(2, bits) - 1
170
+ const minValue = signed === 'signed' ? -Math.pow(2, bits) : 0
171
+ if (value > maxValue || value < minValue) {
172
+ throw new Error(`${parameterName} must be in the range ${minValue}-${maxValue}.`)
173
+ }
129
174
  }
130
175
 
131
176
  export function removeFromQueue<T>(value: T, queue: T[]) {
132
- if (queue) {
133
- const idx = queue.indexOf(value);
134
- if (idx >= 0) {
135
- queue.splice(idx, 1);
136
- }
137
- }
177
+ if (queue) {
178
+ const idx = queue.indexOf(value)
179
+ if (idx >= 0) {
180
+ queue.splice(idx, 1)
181
+ }
182
+ }
138
183
  }
package/src/index.ts CHANGED
@@ -1,8 +1,8 @@
1
- export { Channel } from "./Channel";
2
- export { ChannelOptions } from "./ChannelOptions";
3
- export { FullDuplexStream } from "./FullDuplexStream";
4
- export { IDisposableObservable } from "./IDisposableObservable";
5
- export { MultiplexingStream } from "./MultiplexingStream";
6
- export { MultiplexingStreamOptions } from "./MultiplexingStreamOptions";
7
- export { writeSubstream, readSubstream } from "./Utilities";
8
- export { QualifiedChannelId, ChannelSource } from "./QualifiedChannelId";
1
+ export { Channel } from './Channel'
2
+ export { ChannelOptions } from './ChannelOptions'
3
+ export { FullDuplexStream } from './FullDuplexStream'
4
+ export { IDisposableObservable } from './IDisposableObservable'
5
+ export { MultiplexingStream } from './MultiplexingStream'
6
+ export { MultiplexingStreamOptions } from './MultiplexingStreamOptions'
7
+ export { writeSubstream, readSubstream } from './Utilities'
8
+ export { QualifiedChannelId, ChannelSource } from './QualifiedChannelId'