5807f6f72f7b002cc8fc0dd2fc1dd95351b29544c5a506e0d642b251c5d1b3290ec851ef50f7b419ffeabb2a688370fe1ad485cba72ed3f6440f07345f3eb1 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. 'use strict'
  2. const figgyPudding = require('figgy-pudding')
  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. const PutOpts = figgyPudding({
  10. algorithms: {
  11. default: ['sha512']
  12. },
  13. integrity: {},
  14. memoize: {},
  15. metadata: {},
  16. pickAlgorithm: {},
  17. size: {},
  18. tmpPrefix: {},
  19. single: {},
  20. sep: {},
  21. error: {},
  22. strict: {}
  23. })
  24. module.exports = putData
  25. function putData (cache, key, data, opts) {
  26. opts = PutOpts(opts)
  27. return write(cache, data, opts).then((res) => {
  28. return index
  29. .insert(cache, key, res.integrity, opts.concat({ size: res.size }))
  30. .then((entry) => {
  31. if (opts.memoize) {
  32. memo.put(cache, entry, data, opts)
  33. }
  34. return res.integrity
  35. })
  36. })
  37. }
  38. module.exports.stream = putStream
  39. function putStream (cache, key, opts) {
  40. opts = PutOpts(opts)
  41. let integrity
  42. let size
  43. let memoData
  44. const pipeline = new Pipeline()
  45. // first item in the pipeline is the memoizer, because we need
  46. // that to end first and get the collected data.
  47. if (opts.memoize) {
  48. const memoizer = new PassThrough().on('collect', data => {
  49. memoData = data
  50. })
  51. pipeline.push(memoizer)
  52. }
  53. // contentStream is a write-only, not a passthrough
  54. // no data comes out of it.
  55. const contentStream = write.stream(cache, opts)
  56. .on('integrity', (int) => {
  57. integrity = int
  58. })
  59. .on('size', (s) => {
  60. size = s
  61. })
  62. pipeline.push(contentStream)
  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.concat({ size }))
  69. .then((entry) => {
  70. if (opts.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. }