const proc = require('child_process'); const Transform = require('stream').Transform; module.exports = function (cb) { var ids = [] var maxBlobSize = 5242879 var add, len = 0 var onAddDone function startAdd() { return proc.execFile('sbotc', ['blobs.add'], (err, stdout, stderr) => { if (err) return console.error(stderr), cb(err) var id = stdout.trim() ids.push(id) if (onAddDone) onAddDone(id), onAddDone = null else console.trace(id) }) } return new Transform({ transform: function transform(data, encoding, cb) { if (!add) add = startAdd() var buf = Buffer.from(data, encoding) if (buf.length === 0) return cb() var remainingSpace = maxBlobSize - len if (buf.length < remainingSpace) { len += buf.length return add.stdin.write(buf, cb) } var endBuf = buf.slice(0, remainingSpace) var nextBuf = buf.slice(remainingSpace) len += endBuf.length var waiting = 2 onAddDone = function (id) { if (!--waiting) next() } var stdin = add.stdin add = null len = 0 stdin.end(endBuf, function (err) { if (err) return cb(err) if (!--waiting) next() }) function next() { transform(nextBuf, null, cb) } }, flush: (_cb) => { if (!add) { _cb() return cb(null, ids) } var waiting = 2 onAddDone = function (id) { if (!--waiting) next() } add.stdin.end(function (err) { if (err) return cb(err) if (!--waiting) next() }) function next() { _cb() cb(null, ids) } } }) }