2016-06-26 10:59:03 +08:00
|
|
|
'use strict'
|
2016-04-27 01:29:27 +08:00
|
|
|
|
2016-06-26 10:59:03 +08:00
|
|
|
const createRenderer = require('./create-renderer')
|
|
|
|
const Module = require('./module')
|
|
|
|
const stream = require('stream')
|
|
|
|
|
|
|
|
function runAsNewModule (code, context) {
|
|
|
|
const path = '__app__'
|
|
|
|
const m = new Module(path, null, context)
|
2016-06-25 12:05:39 +08:00
|
|
|
m.load(path)
|
|
|
|
m._compile(code, path)
|
2016-06-26 10:59:03 +08:00
|
|
|
const res = Object.prototype.hasOwnProperty.call(m.exports, 'default')
|
2016-06-25 12:05:39 +08:00
|
|
|
? m.exports.default
|
|
|
|
: m.exports
|
2016-06-26 10:59:03 +08:00
|
|
|
if (typeof res.then !== 'function') {
|
|
|
|
throw new Error('SSR bundle should export a Promise.')
|
|
|
|
}
|
|
|
|
return res
|
2016-06-08 09:53:43 +08:00
|
|
|
}
|
|
|
|
|
2016-06-25 12:05:39 +08:00
|
|
|
exports.createRenderer = createRenderer
|
2016-06-08 09:53:43 +08:00
|
|
|
|
2016-06-26 10:59:03 +08:00
|
|
|
exports.createBundleRenderer = function (code, rendererOptions) {
|
|
|
|
const renderer = createRenderer(rendererOptions)
|
2016-06-08 09:53:43 +08:00
|
|
|
return {
|
2016-06-26 10:59:03 +08:00
|
|
|
renderToString: (context, cb) => {
|
|
|
|
runAsNewModule(code, context).then(app => {
|
|
|
|
renderer.renderToString(app, cb)
|
|
|
|
})
|
2016-06-08 09:53:43 +08:00
|
|
|
},
|
2016-06-26 10:59:03 +08:00
|
|
|
renderToStream: (context) => {
|
|
|
|
const res = new stream.PassThrough()
|
|
|
|
runAsNewModule(code, context).then(app => {
|
|
|
|
renderer.renderToStream(app).pipe(res)
|
|
|
|
})
|
|
|
|
return res
|
2016-04-27 01:29:27 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|