index.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. 'use strict';
  2. const {Readable, Writable, Duplex, Transform} = require('stream');
  3. const none = Symbol.for('object-stream.none');
  4. const finalSymbol = Symbol.for('object-stream.final');
  5. const manySymbol = Symbol.for('object-stream.many');
  6. const final = value => ({[finalSymbol]: value});
  7. const many = values => ({[manySymbol]: values});
  8. const isFinal = o => o && typeof o == 'object' && finalSymbol in o;
  9. const isMany = o => o && typeof o == 'object' && manySymbol in o;
  10. const getFinalValue = o => o[finalSymbol];
  11. const getManyValues = o => o[manySymbol];
  12. const runAsyncGenerator = async (gen, stream) => {
  13. for (;;) {
  14. let data = gen.next();
  15. if (data && typeof data.then == 'function') {
  16. data = await data;
  17. }
  18. if (data.done) break;
  19. let value = data.value;
  20. if (value && typeof value.then == 'function') {
  21. value = await value;
  22. }
  23. Chain.sanitize(value, stream);
  24. }
  25. };
  26. const wrapFunction = fn =>
  27. new Transform({
  28. writableObjectMode: true,
  29. readableObjectMode: true,
  30. transform(chunk, encoding, callback) {
  31. try {
  32. const result = fn.call(this, chunk, encoding);
  33. if (result && typeof result.then == 'function') {
  34. // thenable
  35. result.then(
  36. result => (Chain.sanitize(result, this), callback(null)),
  37. error => callback(error)
  38. );
  39. return;
  40. }
  41. if (result && typeof result.next == 'function') {
  42. // generator
  43. runAsyncGenerator(result, this).then(
  44. () => callback(null),
  45. error => callback(error)
  46. );
  47. return;
  48. }
  49. Chain.sanitize(result, this);
  50. callback(null);
  51. } catch (error) {
  52. callback(error);
  53. }
  54. }
  55. });
  56. const wrapArray = fns =>
  57. new Transform({
  58. writableObjectMode: true,
  59. readableObjectMode: true,
  60. transform(chunk, encoding, callback) {
  61. try {
  62. let value = chunk;
  63. for (let i = 0; i < fns.length; ++i) {
  64. const result = fns[i].call(this, value, encoding);
  65. if (result === Chain.none) {
  66. callback(null);
  67. return;
  68. }
  69. if (Chain.isFinal(result)) {
  70. value = Chain.getFinalValue(result);
  71. break;
  72. }
  73. value = result;
  74. }
  75. Chain.sanitize(value, this);
  76. callback(null);
  77. } catch (error) {
  78. callback(error);
  79. }
  80. }
  81. });
  82. // is*NodeStream functions taken from https://github.com/nodejs/node/blob/master/lib/internal/streams/utils.js
  83. const isReadableNodeStream = obj =>
  84. obj &&
  85. typeof obj.pipe === 'function' &&
  86. typeof obj.on === 'function' &&
  87. (!obj._writableState || (typeof obj._readableState === 'object' ? obj._readableState.readable : null) !== false) && // Duplex
  88. (!obj._writableState || obj._readableState); // Writable has .pipe.
  89. const isWritableNodeStream = obj =>
  90. obj &&
  91. typeof obj.write === 'function' &&
  92. typeof obj.on === 'function' &&
  93. (!obj._readableState || (typeof obj._writableState === 'object' ? obj._writableState.writable : null) !== false); // Duplex
  94. const isDuplexNodeStream = obj =>
  95. obj && typeof obj.pipe === 'function' && obj._readableState && typeof obj.on === 'function' && typeof obj.write === 'function';
  96. class Chain extends Duplex {
  97. constructor(fns, options) {
  98. super(options || {writableObjectMode: true, readableObjectMode: true});
  99. if (!(fns instanceof Array) || !fns.length) {
  100. throw Error("Chain's argument should be a non-empty array.");
  101. }
  102. this.streams = fns
  103. .filter(fn => fn)
  104. .map((fn, index, fns) => {
  105. if (typeof fn === 'function' || fn instanceof Array) return Chain.convertToTransform(fn);
  106. if (isDuplexNodeStream(fn) || (!index && isReadableNodeStream(fn)) || (index === fns.length - 1 && isWritableNodeStream(fn))) {
  107. return fn;
  108. }
  109. throw Error('Arguments should be functions, arrays or streams.');
  110. })
  111. .filter(s => s);
  112. this.input = this.streams[0];
  113. this.output = this.streams.reduce((output, stream) => (output && output.pipe(stream)) || stream);
  114. if (!isWritableNodeStream(this.input)) {
  115. this._write = (_1, _2, callback) => callback(null);
  116. this._final = callback => callback(null); // unavailable in Node 6
  117. this.input.on('end', () => this.end());
  118. }
  119. if (isReadableNodeStream(this.output)) {
  120. this.output.on('data', chunk => !this.push(chunk) && this.output.pause());
  121. this.output.on('end', () => this.push(null));
  122. } else {
  123. this._read = () => {}; // nop
  124. this.resume();
  125. this.output.on('finish', () => this.push(null));
  126. }
  127. // connect events
  128. if (!options || !options.skipEvents) {
  129. this.streams.forEach(stream => stream.on('error', error => this.emit('error', error)));
  130. }
  131. }
  132. _write(chunk, encoding, callback) {
  133. let error = null;
  134. try {
  135. this.input.write(chunk, encoding, e => callback(e || error));
  136. } catch (e) {
  137. error = e;
  138. }
  139. }
  140. _final(callback) {
  141. let error = null;
  142. try {
  143. this.input.end(null, null, e => callback(e || error));
  144. } catch (e) {
  145. error = e;
  146. }
  147. }
  148. _read() {
  149. this.output.resume();
  150. }
  151. static make(fns, options) {
  152. return new Chain(fns, options);
  153. }
  154. static sanitize(result, stream) {
  155. if (Chain.isFinal(result)) {
  156. result = Chain.getFinalValue(result);
  157. } else if (Chain.isMany(result)) {
  158. result = Chain.getManyValues(result);
  159. }
  160. if (result !== undefined && result !== null && result !== Chain.none) {
  161. if (result instanceof Array) {
  162. result.forEach(value => value !== undefined && value !== null && stream.push(value));
  163. } else {
  164. stream.push(result);
  165. }
  166. }
  167. }
  168. static convertToTransform(fn) {
  169. if (typeof fn === 'function') return wrapFunction(fn);
  170. if (fn instanceof Array) return fn.length ? wrapArray(fn) : null;
  171. return null;
  172. }
  173. }
  174. Chain.none = none;
  175. Chain.final = final;
  176. Chain.isFinal = isFinal;
  177. Chain.getFinalValue = getFinalValue;
  178. Chain.many = many;
  179. Chain.isMany = isMany;
  180. Chain.getManyValues = getManyValues;
  181. Chain.chain = Chain.make;
  182. Chain.make.Constructor = Chain;
  183. module.exports = Chain;