This repository has been archived by the owner on Sep 14, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 39
/
streams.ts
268 lines (244 loc) · 7.67 KB
/
streams.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
/**
* @license
* Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at
* http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at
* http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at
* http://polymer.github.io/PATENTS.txt
*/
import {fs} from 'mz';
import {Deferred} from 'polymer-analyzer/lib/core/utils';
import {PassThrough, Transform} from 'stream';
import File = require('vinyl');
const multipipe = require('multipipe');
if ((Symbol as any).asyncIterator === undefined) {
(Symbol as any).asyncIterator = Symbol('asyncIterator');
}
/**
* Waits for the given ReadableStream
*/
export function waitFor(stream: NodeJS.ReadableStream):
Promise<NodeJS.ReadableStream> {
return new Promise<NodeJS.ReadableStream>((resolve, reject) => {
stream.on('end', resolve);
stream.on('error', reject);
});
}
/**
* Waits for all the given ReadableStreams
*/
export function waitForAll(streams: NodeJS.ReadableStream[]):
Promise<NodeJS.ReadableStream[]> {
return Promise.all<NodeJS.ReadableStream>(streams.map((s) => waitFor(s)));
}
/**
* Returns the string contents of a Vinyl File object, waiting for
* all chunks if the File is a stream.
*/
export async function getFileContents(file: File): Promise<string> {
if (file.isBuffer()) {
return file.contents.toString('utf-8');
} else if (file.isStream()) {
const stream = file.contents;
stream.setEncoding('utf-8');
const contents: string[] = [];
stream.on('data', (chunk: string) => contents.push(chunk));
return new Promise<string>((resolve, reject) => {
stream.on('end', () => resolve(contents.join('')));
stream.on('error', reject);
});
}
throw new Error(
`Unable to get contents of file ${file.path}. ` +
`It has neither a buffer nor a stream.`);
}
/**
* Composes multiple streams (or Transforms) into one.
*/
export function compose(streams: NodeJS.ReadWriteStream[]) {
if (streams && streams.length > 0) {
return multipipe(streams);
} else {
return new PassThrough({objectMode: true});
}
}
/**
* An asynchronous queue that is read as an async iterable.
*/
class AsyncQueue<V> implements AsyncIterable<V> {
private blockedOn: Deferred<IteratorResult<V>>|undefined = undefined;
backlog: Array<{value: IteratorResult<V>, deferred: Deferred<void>}> = [];
private _closed = false;
private _finished = false;
/**
* Add the given value onto the queue.
*
* The return value of this method resolves once the value has been removed
* from the queue. Useful for flow control.
*
* Must not be called after the queue has been closed.
*/
async write(value: V) {
if (this._closed) {
throw new Error('Wrote to closed writable iterable');
}
return this._write({value, done: false});
}
/**
* True once the queue has been closed and all input has been read from it.
*/
get finished() {
return this._finished;
}
/**
* Close the queue, indicating that no more values will be written.
*
* If this method is not called, a consumer iterating over the values will
* wait forever.
*
* The returned promise resolves once the consumer has been notified of the
* end of the queue.
*/
async close() {
this._closed = true;
return this._write({done: true} as any);
}
private async _write(value: IteratorResult<V>) {
if (this.blockedOn) {
this.blockedOn.resolve(value);
this.blockedOn = undefined;
} else {
const deferred = new Deferred<void>();
this.backlog.push({value, deferred});
await deferred.promise;
}
}
/**
* Iterate over values in the queue. Not intended for multiple readers.
* In the case where there are multiple readers, some values may be received
* by multiple readers, but all values will be seen by at least one reader.
*/
async * [Symbol.asyncIterator](): AsyncIterator<V> {
while (true) {
let value;
const maybeValue = this.backlog.shift();
if (maybeValue) {
maybeValue.deferred.resolve(undefined);
value = maybeValue.value;
} else {
this.blockedOn = new Deferred();
value = await this.blockedOn.promise;
}
if (value.done) {
this._finished = true;
this._write(value);
return;
} else {
yield value.value;
}
}
}
}
/**
* Implements `stream.Transform` via standard async iteration.
*
* The main advantage over implementing stream.Transform itself is that correct
* error handling is built in and easy to get right, simply by using
* async/await.
*
* `In` and `Out` extend `{}` because they may not be `null`.
*/
export abstract class AsyncTransformStream<In extends{}, Out extends{}> extends
Transform {
private readonly _inputs = new AsyncQueue<In>();
/**
* Implement this method!
*
* Read from the given iterator to consume input, yield values to write
* chunks of your own. You may yield any number of values for each input.
*
* Note: currently you *must* completely consume `inputs` and return for this
* stream to close.
*/
protected abstract _transformIter(inputs: AsyncIterable<In>):
AsyncIterable<Out>;
private _initialized = false;
private _writingFinished = new Deferred<void>();
private _initializeOnce() {
if (this._initialized === false) {
this._initialized = true;
const transformDonePromise = (async () => {
for await (const value of this._transformIter(this._inputs)) {
// TODO(rictic): if `this.push` returns false, should we wait until
// we get a drain event to keep iterating?
this.push(value);
}
})();
transformDonePromise.then(() => {
if (this._inputs.finished) {
this._writingFinished.resolve(undefined);
} else {
this.emit(
'error',
new Error(
`${this.constructor.name}` +
` did not consume all input while transforming.`));
// Since _transformIter has exited, but not all input was consumed,
// this._flush won't be called. We need to signal manually that
// no more output will be written by this stream.
this.push(null);
}
}, (err) => this.emit('error', err));
}
}
/**
* Don't override.
*
* Passes input into this._inputs.
*/
_transform(
input: In,
_encoding: string,
callback: (error?: any, value?: Out) => void) {
this._initializeOnce();
this._inputs.write(input).then(() => {
callback();
}, (err) => callback(err));
}
/**
* Don't override.
*
* Finish writing out the outputs.
*/
protected async _flush(callback: (err?: any) => void) {
try {
// We won't get any more inputs. Wait for them all to be processed.
await this._inputs.close();
// Wait for all of our output to be written.
await this._writingFinished.promise;
callback();
} catch (e) {
callback(e);
}
}
}
/**
* A stream that takes file path strings, and outputs full Vinyl file objects
* for the file at each location.
*/
export class VinylReaderTransform extends AsyncTransformStream<string, File> {
constructor() {
super({objectMode: true});
}
protected async *
_transformIter(paths: AsyncIterable<string>): AsyncIterable<File> {
for await (const filePath of paths) {
yield new File({path: filePath, contents: await fs.readFile(filePath)});
}
}
}