UNPKG

12.6 kBJavaScriptView Raw
1"use strict";
2/**
3 * @license
4 * Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
5 * This code may only be used under the BSD style license found at
6 * http://polymer.github.io/LICENSE.txt
7 * The complete set of authors may be found at
8 * http://polymer.github.io/AUTHORS.txt
9 * The complete set of contributors may be found at
10 * http://polymer.github.io/CONTRIBUTORS.txt
11 * Code distributed by Google as part of the polymer project is also
12 * subject to an additional IP rights grant found at
13 * http://polymer.github.io/PATENTS.txt
14 */
15var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
16 return new (P || (P = Promise))(function (resolve, reject) {
17 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
18 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
19 function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
20 step((generator = generator.apply(thisArg, _arguments || [])).next());
21 });
22};
23var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
24var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
25 if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
26 var g = generator.apply(thisArg, _arguments || []), i, q = [];
27 return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
28 function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
29 function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
30 function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
31 function fulfill(value) { resume("next", value); }
32 function reject(value) { resume("throw", value); }
33 function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
34};
35var __asyncValues = (this && this.__asyncValues) || function (o) {
36 if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
37 var m = o[Symbol.asyncIterator], i;
38 return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
39 function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
40 function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
41};
42Object.defineProperty(exports, "__esModule", { value: true });
43const mz_1 = require("mz");
44const utils_1 = require("polymer-analyzer/lib/core/utils");
45const stream_1 = require("stream");
46const File = require("vinyl");
47const multipipe = require('multipipe');
48if (Symbol.asyncIterator === undefined) {
49 // tslint:disable-next-line: no-any polyfilling.
50 Symbol.asyncIterator = Symbol('asyncIterator');
51}
52/**
53 * Waits for the given ReadableStream
54 */
55function waitFor(stream) {
56 return new Promise((resolve, reject) => {
57 stream.on('end', resolve);
58 stream.on('error', reject);
59 });
60}
61exports.waitFor = waitFor;
62/**
63 * Waits for all the given ReadableStreams
64 */
65function waitForAll(streams) {
66 return Promise.all(streams.map((s) => waitFor(s)));
67}
68exports.waitForAll = waitForAll;
69/**
70 * Returns the string contents of a Vinyl File object, waiting for
71 * all chunks if the File is a stream.
72 */
73function getFileContents(file) {
74 return __awaiter(this, void 0, void 0, function* () {
75 if (file.isBuffer()) {
76 return file.contents.toString('utf-8');
77 }
78 else if (file.isStream()) {
79 const stream = file.contents;
80 stream.setEncoding('utf-8');
81 const contents = [];
82 stream.on('data', (chunk) => contents.push(chunk));
83 return new Promise((resolve, reject) => {
84 stream.on('end', () => resolve(contents.join('')));
85 stream.on('error', reject);
86 });
87 }
88 throw new Error(`Unable to get contents of file ${file.path}. ` +
89 `It has neither a buffer nor a stream.`);
90 });
91}
92exports.getFileContents = getFileContents;
93/**
94 * Composes multiple streams (or Transforms) into one.
95 */
96function compose(streams) {
97 if (streams && streams.length > 0) {
98 return multipipe(streams);
99 }
100 else {
101 return new stream_1.PassThrough({ objectMode: true });
102 }
103}
104exports.compose = compose;
105/**
106 * An asynchronous queue that is read as an async iterable.
107 */
108class AsyncQueue {
109 constructor() {
110 this.blockedOn = undefined;
111 this.backlog = [];
112 this._closed = false;
113 this._finished = false;
114 }
115 /**
116 * Add the given value onto the queue.
117 *
118 * The return value of this method resolves once the value has been removed
119 * from the queue. Useful for flow control.
120 *
121 * Must not be called after the queue has been closed.
122 */
123 write(value) {
124 return __awaiter(this, void 0, void 0, function* () {
125 if (this._closed) {
126 throw new Error('Wrote to closed writable iterable');
127 }
128 return this._write({ value, done: false });
129 });
130 }
131 /**
132 * True once the queue has been closed and all input has been read from it.
133 */
134 get finished() {
135 return this._finished;
136 }
137 /**
138 * Close the queue, indicating that no more values will be written.
139 *
140 * If this method is not called, a consumer iterating over the values will
141 * wait forever.
142 *
143 * The returned promise resolves once the consumer has been notified of the
144 * end of the queue.
145 */
146 close() {
147 return __awaiter(this, void 0, void 0, function* () {
148 this._closed = true;
149 return this._write({ done: true });
150 });
151 }
152 _write(value) {
153 return __awaiter(this, void 0, void 0, function* () {
154 if (this.blockedOn) {
155 this.blockedOn.resolve(value);
156 this.blockedOn = undefined;
157 }
158 else {
159 const deferred = new utils_1.Deferred();
160 this.backlog.push({ value, deferred });
161 yield deferred.promise;
162 }
163 });
164 }
165 /**
166 * Iterate over values in the queue. Not intended for multiple readers.
167 * In the case where there are multiple readers, some values may be received
168 * by multiple readers, but all values will be seen by at least one reader.
169 */
170 [Symbol.asyncIterator]() {
171 return __asyncGenerator(this, arguments, function* _a() {
172 while (true) {
173 let value;
174 const maybeValue = this.backlog.shift();
175 if (maybeValue) {
176 maybeValue.deferred.resolve(undefined);
177 value = maybeValue.value;
178 }
179 else {
180 this.blockedOn = new utils_1.Deferred();
181 value = yield __await(this.blockedOn.promise);
182 }
183 if (value.done) {
184 this._finished = true;
185 this._write(value);
186 return yield __await(void 0);
187 }
188 else {
189 yield yield __await(value.value);
190 }
191 }
192 });
193 }
194}
195/**
196 * Implements `stream.Transform` via standard async iteration.
197 *
198 * The main advantage over implementing stream.Transform itself is that correct
199 * error handling is built in and easy to get right, simply by using
200 * async/await.
201 *
202 * `In` and `Out` extend `{}` because they may not be `null`.
203 */
204class AsyncTransformStream extends stream_1.Transform {
205 constructor() {
206 super(...arguments);
207 this._inputs = new AsyncQueue();
208 this._initialized = false;
209 this._writingFinished = new utils_1.Deferred();
210 }
211 _initializeOnce() {
212 if (this._initialized === false) {
213 this._initialized = true;
214 const transformDonePromise = (() => __awaiter(this, void 0, void 0, function* () {
215 var e_1, _a;
216 try {
217 for (var _b = __asyncValues(this._transformIter(this._inputs)), _c; _c = yield _b.next(), !_c.done;) {
218 const value = _c.value;
219 // TODO(rictic): if `this.push` returns false, should we wait until
220 // we get a drain event to keep iterating?
221 this.push(value);
222 }
223 }
224 catch (e_1_1) { e_1 = { error: e_1_1 }; }
225 finally {
226 try {
227 if (_c && !_c.done && (_a = _b.return)) yield _a.call(_b);
228 }
229 finally { if (e_1) throw e_1.error; }
230 }
231 }))();
232 transformDonePromise.then(() => {
233 if (this._inputs.finished) {
234 this._writingFinished.resolve(undefined);
235 }
236 else {
237 this.emit('error', new Error(`${this.constructor.name}` +
238 ` did not consume all input while transforming.`));
239 // Since _transformIter has exited, but not all input was consumed,
240 // this._flush won't be called. We need to signal manually that
241 // no more output will be written by this stream.
242 this.push(null);
243 }
244 }, (err) => this.emit('error', err));
245 }
246 }
247 /**
248 * Don't override.
249 *
250 * Passes input into this._inputs.
251 */
252 _transform(input, _encoding, callback) {
253 this._initializeOnce();
254 this._inputs.write(input).then(() => {
255 callback();
256 }, (err) => callback(err));
257 }
258 /**
259 * Don't override.
260 *
261 * Finish writing out the outputs.
262 */
263 _flush(callback) {
264 return __awaiter(this, void 0, void 0, function* () {
265 try {
266 // We won't get any more inputs. Wait for them all to be processed.
267 yield this._inputs.close();
268 // Wait for all of our output to be written.
269 yield this._writingFinished.promise;
270 callback();
271 }
272 catch (e) {
273 callback(e);
274 }
275 });
276 }
277}
278exports.AsyncTransformStream = AsyncTransformStream;
279/**
280 * A stream that takes file path strings, and outputs full Vinyl file objects
281 * for the file at each location.
282 */
283class VinylReaderTransform extends AsyncTransformStream {
284 constructor() {
285 super({ objectMode: true });
286 }
287 _transformIter(paths) {
288 return __asyncGenerator(this, arguments, function* _transformIter_1() {
289 var e_2, _a;
290 try {
291 for (var paths_1 = __asyncValues(paths), paths_1_1; paths_1_1 = yield __await(paths_1.next()), !paths_1_1.done;) {
292 const filePath = paths_1_1.value;
293 yield yield __await(new File({ path: filePath, contents: yield __await(mz_1.fs.readFile(filePath)) }));
294 }
295 }
296 catch (e_2_1) { e_2 = { error: e_2_1 }; }
297 finally {
298 try {
299 if (paths_1_1 && !paths_1_1.done && (_a = paths_1.return)) yield __await(_a.call(paths_1));
300 }
301 finally { if (e_2) throw e_2.error; }
302 }
303 });
304 }
305}
306exports.VinylReaderTransform = VinylReaderTransform;
307/**
308 * pipeStreams() takes in a collection streams and pipes them together,
309 * returning the last stream in the pipeline. Each element in the `streams`
310 * array must be either a stream, or an array of streams (see PipeStream).
311 * pipeStreams() will then flatten this array before piping them all together.
312 */
313function pipeStreams(streams) {
314 return Array.prototype.concat.apply([], streams)
315 .reduce((a, b) => {
316 return a.pipe(b);
317 });
318}
319exports.pipeStreams = pipeStreams;
320//# sourceMappingURL=streams.js.map
\No newline at end of file