Welcome to mirror list, hosted at ThFree Co, Russian Federation.

index.js « minipass-sized « node_modules - github.com/npm/cli.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: a0c8acde487fce4d52127e850f94199eefd5845e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
const Minipass = require('minipass')

class SizeError extends Error {
  constructor (found, expect) {
    super(`Bad data size: expected ${expect} bytes, but got ${found}`)
    this.expect = expect
    this.found = found
    this.code = 'EBADSIZE'
	  Error.captureStackTrace(this, this.constructor)
  }
  get name () {
    return 'SizeError'
  }
}

class MinipassSized extends Minipass {
  constructor (options = {}) {
    super(options)

    if (options.objectMode)
      throw new TypeError(`${
        this.constructor.name
      } streams only work with string and buffer data`)

    this.found = 0
    this.expect = options.size
    if (typeof this.expect !== 'number' ||
        this.expect > Number.MAX_SAFE_INTEGER ||
        isNaN(this.expect) ||
        this.expect < 0 ||
        !isFinite(this.expect) ||
        this.expect !== Math.floor(this.expect))
      throw new Error('invalid expected size: ' + this.expect)
  }

  write (chunk, encoding, cb) {
    const buffer = Buffer.isBuffer(chunk) ? chunk
      : typeof chunk === 'string' ?
        Buffer.from(chunk, typeof encoding === 'string' ? encoding : 'utf8')
      : chunk

    if (!Buffer.isBuffer(buffer)) {
      this.emit('error', new TypeError(`${
        this.constructor.name
      } streams only work with string and buffer data`))
      return false
    }

    this.found += buffer.length
    if (this.found > this.expect)
      this.emit('error', new SizeError(this.found, this.expect))

    return super.write(chunk, encoding, cb)
  }

  emit (ev, ...data) {
    if (ev === 'end') {
      if (this.found !== this.expect)
        this.emit('error', new SizeError(this.found, this.expect))
    }
    return super.emit(ev, ...data)
  }
}

MinipassSized.SizeError = SizeError

module.exports = MinipassSized