index.js 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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(result => (Chain.sanitize(result, this), callback(null)), error => callback(error));
  36. return;
  37. }
  38. if (result && typeof result.next == 'function') {
  39. // generator
  40. runAsyncGenerator(result, this).then(() => callback(null), error => callback(error));
  41. return;
  42. }
  43. Chain.sanitize(result, this);
  44. callback(null);
  45. } catch (error) {
  46. callback(error);
  47. }
  48. }
  49. });
  50. const wrapArray = fns =>
  51. new Transform({
  52. writableObjectMode: true,
  53. readableObjectMode: true,
  54. transform(chunk, encoding, callback) {
  55. try {
  56. let value = chunk;
  57. for (let i = 0; i < fns.length; ++i) {
  58. const result = fns[i].call(this, value, encoding);
  59. if (result === Chain.none) {
  60. callback(null);
  61. return;
  62. }
  63. if (Chain.isFinal(result)) {
  64. value = Chain.getFinalValue(result);
  65. break;
  66. }
  67. value = result;
  68. }
  69. Chain.sanitize(value, this);
  70. callback(null);
  71. } catch (error) {
  72. callback(error);
  73. }
  74. }
  75. });
  76. class Chain extends Duplex {
  77. constructor(fns, options) {
  78. super(options || {writableObjectMode: true, readableObjectMode: true});
  79. if (!(fns instanceof Array) || !fns.length) {
  80. throw Error("Chain's argument should be a non-empty array.");
  81. }
  82. this.streams = fns
  83. .filter(fn => fn)
  84. .map((fn, index, fns) => {
  85. if (typeof fn === 'function' || fn instanceof Array) return Chain.convertToTransform(fn);
  86. if (
  87. fn instanceof Duplex ||
  88. fn instanceof Transform ||
  89. (!index && fn instanceof Readable) ||
  90. (index === fns.length - 1 && fn instanceof Writable)
  91. ) {
  92. return fn;
  93. }
  94. throw Error('Arguments should be functions, arrays or streams.');
  95. })
  96. .filter(s => s);
  97. this.input = this.streams[0];
  98. this.output = this.streams.reduce((output, stream) => (output && output.pipe(stream)) || stream);
  99. if (!(this.input instanceof Writable)) {
  100. this._write = (_1, _2, callback) => callback(null);
  101. this._final = callback => callback(null); // unavailable in Node 6
  102. this.input.on('end', () => this.end());
  103. }
  104. if (this.output instanceof Readable) {
  105. this.output.on('data', chunk => !this.push(chunk) && this.output.pause());
  106. this.output.on('end', () => this.push(null));
  107. } else {
  108. this._read = () => {}; // nop
  109. this.resume();
  110. this.output.on('finish', () => this.push(null));
  111. }
  112. // connect events
  113. if (!options || !options.skipEvents) {
  114. this.streams.forEach(stream => stream.on('error', error => this.emit('error', error)));
  115. }
  116. }
  117. _write(chunk, encoding, callback) {
  118. let error = null;
  119. try {
  120. this.input.write(chunk, encoding, e => callback(e || error));
  121. } catch (e) {
  122. error = e;
  123. }
  124. }
  125. _final(callback) {
  126. let error = null;
  127. try {
  128. this.input.end(null, null, e => callback(e || error));
  129. } catch (e) {
  130. error = e;
  131. }
  132. }
  133. _read() {
  134. this.output.resume();
  135. }
  136. static make(fns, options) {
  137. return new Chain(fns, options);
  138. }
  139. static sanitize(result, stream) {
  140. if (Chain.isFinal(result)) {
  141. result = Chain.getFinalValue(result);
  142. } else if (Chain.isMany(result)) {
  143. result = Chain.getManyValues(result);
  144. }
  145. if (result !== undefined && result !== null && result !== Chain.none) {
  146. if (result instanceof Array) {
  147. result.forEach(value => value !== undefined && value !== null && stream.push(value));
  148. } else {
  149. stream.push(result);
  150. }
  151. }
  152. }
  153. static convertToTransform(fn) {
  154. if (typeof fn === 'function') return wrapFunction(fn);
  155. if (fn instanceof Array) return fn.length ? wrapArray(fn) : null;
  156. return null;
  157. }
  158. }
  159. Chain.none = none;
  160. Chain.final = final;
  161. Chain.isFinal = isFinal;
  162. Chain.getFinalValue = getFinalValue;
  163. Chain.many = many;
  164. Chain.isMany = isMany;
  165. Chain.getManyValues = getManyValues;
  166. Chain.chain = Chain.make;
  167. Chain.make.Constructor = Chain;
  168. module.exports = Chain;