From cabc4ee097c6b0ee1b03c300709233ef9495d293 Mon Sep 17 00:00:00 2001 From: Rich-Harris Date: Mon, 2 Nov 2015 20:41:06 -0500 Subject: [PATCH] support async transformers (closes #260) --- src/utils/transform.js | 35 ++++++++++++---------- test/function/transformer-async/_config.js | 24 +++++++++++++++ test/function/transformer-async/main.js | 1 + 3 files changed, 45 insertions(+), 15 deletions(-) create mode 100644 test/function/transformer-async/_config.js create mode 100644 test/function/transformer-async/main.js diff --git a/src/utils/transform.js b/src/utils/transform.js index 16ca598..761a217 100644 --- a/src/utils/transform.js +++ b/src/utils/transform.js @@ -1,3 +1,5 @@ +import Promise from 'es6-promise/lib/es6-promise/promise.js'; + export default function transform ( source, id, transformers ) { let sourceMapChain = []; @@ -11,24 +13,27 @@ export default function transform ( source, id, transformers ) { let originalCode = source.code; let ast = source.ast; - let code = transformers.reduce( ( previous, transformer ) => { - let result = transformer( previous, id ); + return transformers.reduce( ( promise, transformer ) => { + return promise.then( previous => { + return Promise.resolve( transformer( previous, id ) ).then( result => { + if ( result == null ) return previous; - if ( result == null ) return previous; + if ( typeof result === 'string' ) { + result = { + code: result, + ast: null, + map: null + }; + } - if ( typeof result === 'string' ) { - result = { - code: result, - ast: null, - map: null - }; - } + sourceMapChain.push( result.map ); + ast = result.ast; - sourceMapChain.push( result.map ); - ast = result.ast; + return result.code; + }); + }); - return result.code; - }, source.code ); + }, Promise.resolve( source.code ) ) - return { code, originalCode, ast, sourceMapChain }; + .then( code => ({ code, originalCode, ast, sourceMapChain }) ); } diff --git a/test/function/transformer-async/_config.js b/test/function/transformer-async/_config.js new file mode 100644 index 0000000..960eb69 --- /dev/null +++ b/test/function/transformer-async/_config.js @@ -0,0 +1,24 @@ +var Promise = require( 'es6-promise' ).Promise; + +module.exports = { + description: 'transformers can be asynchronous', + options: { + plugins: [ + { + transform: function ( code ) { + return Promise.resolve( code.replace( 'x', 1 ) ); + } + }, + { + transform: function ( code ) { + return code.replace( '1', 2 ); + } + }, + { + transform: function ( code ) { + return Promise.resolve( code.replace( '2', 3 ) ); + } + } + ] + } +}; diff --git a/test/function/transformer-async/main.js b/test/function/transformer-async/main.js new file mode 100644 index 0000000..a09d995 --- /dev/null +++ b/test/function/transformer-async/main.js @@ -0,0 +1 @@ +assert.equal( x, 3 );