@@ -7,9 +7,9 @@ const RecursiveIterable = require('./recursiveIterable');
77const isReadableStream = require ( './utils' ) . isReadableStream ;
88
99class JSONStreamify extends CoStream {
10- constructor ( value , replacer ) {
10+ constructor ( value , replacer , space , _visited ) {
1111 super ( arguments ) ;
12- this . _iter = new RecursiveIterable ( replacer instanceof Function ? replacer ( undefined , value ) : value , replacer ) ;
12+ this . _iter = new RecursiveIterable ( replacer instanceof Function ? replacer ( undefined , value ) : value , replacer , space , _visited ) ;
1313 }
1414
1515 * _makeGenerator ( value , replacer ) {
@@ -54,12 +54,12 @@ class JSONStreamify extends CoStream {
5454 const pass = new PassThrough ( ) ;
5555 obj . value . pipe ( new Transform ( {
5656 objectMode : true ,
57- transform : function ( data , enc , next ) {
57+ transform : ( data , enc , next ) => {
5858 if ( ! first ) {
5959 pass . push ( ',' ) ;
6060 }
6161 first = false ;
62- let stream = new JSONStreamify ( data ) ;
62+ let stream = new JSONStreamify ( data , this . _iter . replacer , this . _iter . space , this . _iter . visited ) ;
6363 stream . _iter . _parentCtxType = Array ;
6464 stream . once ( 'end' , ( ) => next ( null , undefined ) ) . pipe ( pass , {
6565 end : false
@@ -71,8 +71,27 @@ class JSONStreamify extends CoStream {
7171 continue ;
7272 }
7373
74+ if ( obj . state === 'circular' ) {
75+ let replacer ;
76+ this . emit ( 'circular' , Object . assign ( obj , {
77+ replace : ( promise ) => {
78+ if ( promise instanceof Promise ) {
79+ obj . value = promise ;
80+ }
81+ }
82+ } ) ) ;
83+
84+ // Wait for replace
85+ yield new Promise ( resolve => process . nextTick ( resolve ) ) ;
86+
87+ if ( ! ( obj . value instanceof Promise ) ) {
88+ yield this . push ( '"[Circular]"' ) ;
89+ }
90+ }
91+
7492 if ( obj . value instanceof Promise ) {
75- obj . value = obj . attachChild ( new RecursiveIterable ( yield obj . value ) [ Symbol . iterator ] ( ) ) ;
93+ let childIterator = new RecursiveIterable ( yield obj . value , this . _iter . replacer , this . _iter . space , this . _iter . visited ) [ Symbol . iterator ] ( ) ;
94+ obj . value = obj . attachChild ( childIterator ) ;
7695 insertSeparator = false ;
7796 continue ;
7897 }
@@ -87,6 +106,6 @@ class JSONStreamify extends CoStream {
87106 }
88107}
89108
90- module . exports = function ( obj , replacer ) {
109+ module . exports = function ( obj , replacer ) {
91110 return new JSONStreamify ( obj , replacer ) ;
92111} ;
0 commit comments