[6a3a178] | 1 | 'use strict'
|
---|
| 2 |
|
---|
| 3 | const index = require('./lib/entry-index')
|
---|
| 4 | const memo = require('./lib/memoization')
|
---|
| 5 | const write = require('./lib/content/write')
|
---|
| 6 | const Flush = require('minipass-flush')
|
---|
| 7 | const { PassThrough } = require('minipass-collect')
|
---|
| 8 | const Pipeline = require('minipass-pipeline')
|
---|
| 9 |
|
---|
| 10 | const putOpts = (opts) => ({
|
---|
| 11 | algorithms: ['sha512'],
|
---|
| 12 | ...opts,
|
---|
| 13 | })
|
---|
| 14 |
|
---|
| 15 | module.exports = putData
|
---|
| 16 |
|
---|
| 17 | function putData (cache, key, data, opts = {}) {
|
---|
| 18 | const { memoize } = opts
|
---|
| 19 | opts = putOpts(opts)
|
---|
| 20 | return write(cache, data, opts).then((res) => {
|
---|
| 21 | return index
|
---|
| 22 | .insert(cache, key, res.integrity, { ...opts, size: res.size })
|
---|
| 23 | .then((entry) => {
|
---|
| 24 | if (memoize)
|
---|
| 25 | memo.put(cache, entry, data, opts)
|
---|
| 26 |
|
---|
| 27 | return res.integrity
|
---|
| 28 | })
|
---|
| 29 | })
|
---|
| 30 | }
|
---|
| 31 |
|
---|
| 32 | module.exports.stream = putStream
|
---|
| 33 |
|
---|
| 34 | function putStream (cache, key, opts = {}) {
|
---|
| 35 | const { memoize } = opts
|
---|
| 36 | opts = putOpts(opts)
|
---|
| 37 | let integrity
|
---|
| 38 | let size
|
---|
| 39 |
|
---|
| 40 | let memoData
|
---|
| 41 | const pipeline = new Pipeline()
|
---|
| 42 | // first item in the pipeline is the memoizer, because we need
|
---|
| 43 | // that to end first and get the collected data.
|
---|
| 44 | if (memoize) {
|
---|
| 45 | const memoizer = new PassThrough().on('collect', data => {
|
---|
| 46 | memoData = data
|
---|
| 47 | })
|
---|
| 48 | pipeline.push(memoizer)
|
---|
| 49 | }
|
---|
| 50 |
|
---|
| 51 | // contentStream is a write-only, not a passthrough
|
---|
| 52 | // no data comes out of it.
|
---|
| 53 | const contentStream = write.stream(cache, opts)
|
---|
| 54 | .on('integrity', (int) => {
|
---|
| 55 | integrity = int
|
---|
| 56 | })
|
---|
| 57 | .on('size', (s) => {
|
---|
| 58 | size = s
|
---|
| 59 | })
|
---|
| 60 |
|
---|
| 61 | pipeline.push(contentStream)
|
---|
| 62 |
|
---|
| 63 | // last but not least, we write the index and emit hash and size,
|
---|
| 64 | // and memoize if we're doing that
|
---|
| 65 | pipeline.push(new Flush({
|
---|
| 66 | flush () {
|
---|
| 67 | return index
|
---|
| 68 | .insert(cache, key, integrity, { ...opts, size })
|
---|
| 69 | .then((entry) => {
|
---|
| 70 | if (memoize && memoData)
|
---|
| 71 | memo.put(cache, entry, memoData, opts)
|
---|
| 72 |
|
---|
| 73 | if (integrity)
|
---|
| 74 | pipeline.emit('integrity', integrity)
|
---|
| 75 |
|
---|
| 76 | if (size)
|
---|
| 77 | pipeline.emit('size', size)
|
---|
| 78 | })
|
---|
| 79 | },
|
---|
| 80 | }))
|
---|
| 81 |
|
---|
| 82 | return pipeline
|
---|
| 83 | }
|
---|