Worker.js

Worker@Tesseract.js

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.cn-greasyfork.org/scripts/31381/205679/Workerjs.js

  1. (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. (function (process){
  3. /* Copyright (c) 2013 Rod Vagg, MIT License */
  4.  
  5. function AbstractChainedBatch (db) {
  6. this._db = db
  7. this._operations = []
  8. this._written = false
  9. }
  10.  
  11. AbstractChainedBatch.prototype._checkWritten = function () {
  12. if (this._written)
  13. throw new Error('write() already called on this batch')
  14. }
  15.  
  16. AbstractChainedBatch.prototype.put = function (key, value) {
  17. this._checkWritten()
  18.  
  19. var err = this._db._checkKeyValue(key, 'key', this._db._isBuffer)
  20. if (err) throw err
  21. err = this._db._checkKeyValue(value, 'value', this._db._isBuffer)
  22. if (err) throw err
  23.  
  24. if (!this._db._isBuffer(key)) key = String(key)
  25. if (!this._db._isBuffer(value)) value = String(value)
  26.  
  27. if (typeof this._put == 'function' )
  28. this._put(key, value)
  29. else
  30. this._operations.push({ type: 'put', key: key, value: value })
  31.  
  32. return this
  33. }
  34.  
  35. AbstractChainedBatch.prototype.del = function (key) {
  36. this._checkWritten()
  37.  
  38. var err = this._db._checkKeyValue(key, 'key', this._db._isBuffer)
  39. if (err) throw err
  40.  
  41. if (!this._db._isBuffer(key)) key = String(key)
  42.  
  43. if (typeof this._del == 'function' )
  44. this._del(key)
  45. else
  46. this._operations.push({ type: 'del', key: key })
  47.  
  48. return this
  49. }
  50.  
  51. AbstractChainedBatch.prototype.clear = function () {
  52. this._checkWritten()
  53.  
  54. this._operations = []
  55.  
  56. if (typeof this._clear == 'function' )
  57. this._clear()
  58.  
  59. return this
  60. }
  61.  
  62. AbstractChainedBatch.prototype.write = function (options, callback) {
  63. this._checkWritten()
  64.  
  65. if (typeof options == 'function')
  66. callback = options
  67. if (typeof callback != 'function')
  68. throw new Error('write() requires a callback argument')
  69. if (typeof options != 'object')
  70. options = {}
  71.  
  72. this._written = true
  73.  
  74. if (typeof this._write == 'function' )
  75. return this._write(callback)
  76.  
  77. if (typeof this._db._batch == 'function')
  78. return this._db._batch(this._operations, options, callback)
  79.  
  80. process.nextTick(callback)
  81. }
  82.  
  83. module.exports = AbstractChainedBatch
  84. }).call(this,require('_process'))
  85. },{"_process":32}],2:[function(require,module,exports){
  86. (function (process){
  87. /* Copyright (c) 2013 Rod Vagg, MIT License */
  88.  
  89. function AbstractIterator (db) {
  90. this.db = db
  91. this._ended = false
  92. this._nexting = false
  93. }
  94.  
  95. AbstractIterator.prototype.next = function (callback) {
  96. var self = this
  97.  
  98. if (typeof callback != 'function')
  99. throw new Error('next() requires a callback argument')
  100.  
  101. if (self._ended)
  102. return callback(new Error('cannot call next() after end()'))
  103. if (self._nexting)
  104. return callback(new Error('cannot call next() before previous next() has completed'))
  105.  
  106. self._nexting = true
  107. if (typeof self._next == 'function') {
  108. return self._next(function () {
  109. self._nexting = false
  110. callback.apply(null, arguments)
  111. })
  112. }
  113.  
  114. process.nextTick(function () {
  115. self._nexting = false
  116. callback()
  117. })
  118. }
  119.  
  120. AbstractIterator.prototype.end = function (callback) {
  121. if (typeof callback != 'function')
  122. throw new Error('end() requires a callback argument')
  123.  
  124. if (this._ended)
  125. return callback(new Error('end() already called on iterator'))
  126.  
  127. this._ended = true
  128.  
  129. if (typeof this._end == 'function')
  130. return this._end(callback)
  131.  
  132. process.nextTick(callback)
  133. }
  134.  
  135. module.exports = AbstractIterator
  136.  
  137. }).call(this,require('_process'))
  138. },{"_process":32}],3:[function(require,module,exports){
  139. (function (Buffer,process){
  140. /* Copyright (c) 2013 Rod Vagg, MIT License */
  141.  
  142. var xtend = require('xtend')
  143. , AbstractIterator = require('./abstract-iterator')
  144. , AbstractChainedBatch = require('./abstract-chained-batch')
  145.  
  146. function AbstractLevelDOWN (location) {
  147. if (!arguments.length || location === undefined)
  148. throw new Error('constructor requires at least a location argument')
  149.  
  150. if (typeof location != 'string')
  151. throw new Error('constructor requires a location string argument')
  152.  
  153. this.location = location
  154. }
  155.  
  156. AbstractLevelDOWN.prototype.open = function (options, callback) {
  157. if (typeof options == 'function')
  158. callback = options
  159.  
  160. if (typeof callback != 'function')
  161. throw new Error('open() requires a callback argument')
  162.  
  163. if (typeof options != 'object')
  164. options = {}
  165.  
  166. if (typeof this._open == 'function')
  167. return this._open(options, callback)
  168.  
  169. process.nextTick(callback)
  170. }
  171.  
  172. AbstractLevelDOWN.prototype.close = function (callback) {
  173. if (typeof callback != 'function')
  174. throw new Error('close() requires a callback argument')
  175.  
  176. if (typeof this._close == 'function')
  177. return this._close(callback)
  178.  
  179. process.nextTick(callback)
  180. }
  181.  
  182. AbstractLevelDOWN.prototype.get = function (key, options, callback) {
  183. var err
  184.  
  185. if (typeof options == 'function')
  186. callback = options
  187.  
  188. if (typeof callback != 'function')
  189. throw new Error('get() requires a callback argument')
  190.  
  191. if (err = this._checkKeyValue(key, 'key', this._isBuffer))
  192. return callback(err)
  193.  
  194. if (!this._isBuffer(key))
  195. key = String(key)
  196.  
  197. if (typeof options != 'object')
  198. options = {}
  199.  
  200. if (typeof this._get == 'function')
  201. return this._get(key, options, callback)
  202.  
  203. process.nextTick(function () { callback(new Error('NotFound')) })
  204. }
  205.  
  206. AbstractLevelDOWN.prototype.put = function (key, value, options, callback) {
  207. var err
  208.  
  209. if (typeof options == 'function')
  210. callback = options
  211.  
  212. if (typeof callback != 'function')
  213. throw new Error('put() requires a callback argument')
  214.  
  215. if (err = this._checkKeyValue(key, 'key', this._isBuffer))
  216. return callback(err)
  217.  
  218. if (err = this._checkKeyValue(value, 'value', this._isBuffer))
  219. return callback(err)
  220.  
  221. if (!this._isBuffer(key))
  222. key = String(key)
  223.  
  224. // coerce value to string in node, don't touch it in browser
  225. // (indexeddb can store any JS type)
  226. if (!this._isBuffer(value) && !process.browser)
  227. value = String(value)
  228.  
  229. if (typeof options != 'object')
  230. options = {}
  231.  
  232. if (typeof this._put == 'function')
  233. return this._put(key, value, options, callback)
  234.  
  235. process.nextTick(callback)
  236. }
  237.  
  238. AbstractLevelDOWN.prototype.del = function (key, options, callback) {
  239. var err
  240.  
  241. if (typeof options == 'function')
  242. callback = options
  243.  
  244. if (typeof callback != 'function')
  245. throw new Error('del() requires a callback argument')
  246.  
  247. if (err = this._checkKeyValue(key, 'key', this._isBuffer))
  248. return callback(err)
  249.  
  250. if (!this._isBuffer(key))
  251. key = String(key)
  252.  
  253. if (typeof options != 'object')
  254. options = {}
  255.  
  256. if (typeof this._del == 'function')
  257. return this._del(key, options, callback)
  258.  
  259. process.nextTick(callback)
  260. }
  261.  
  262. AbstractLevelDOWN.prototype.batch = function (array, options, callback) {
  263. if (!arguments.length)
  264. return this._chainedBatch()
  265.  
  266. if (typeof options == 'function')
  267. callback = options
  268.  
  269. if (typeof callback != 'function')
  270. throw new Error('batch(array) requires a callback argument')
  271.  
  272. if (!Array.isArray(array))
  273. return callback(new Error('batch(array) requires an array argument'))
  274.  
  275. if (typeof options != 'object')
  276. options = {}
  277.  
  278. var i = 0
  279. , l = array.length
  280. , e
  281. , err
  282.  
  283. for (; i < l; i++) {
  284. e = array[i]
  285. if (typeof e != 'object')
  286. continue
  287.  
  288. if (err = this._checkKeyValue(e.type, 'type', this._isBuffer))
  289. return callback(err)
  290.  
  291. if (err = this._checkKeyValue(e.key, 'key', this._isBuffer))
  292. return callback(err)
  293.  
  294. if (e.type == 'put') {
  295. if (err = this._checkKeyValue(e.value, 'value', this._isBuffer))
  296. return callback(err)
  297. }
  298. }
  299.  
  300. if (typeof this._batch == 'function')
  301. return this._batch(array, options, callback)
  302.  
  303. process.nextTick(callback)
  304. }
  305.  
  306. //TODO: remove from here, not a necessary primitive
  307. AbstractLevelDOWN.prototype.approximateSize = function (start, end, callback) {
  308. if ( start == null
  309. || end == null
  310. || typeof start == 'function'
  311. || typeof end == 'function') {
  312. throw new Error('approximateSize() requires valid `start`, `end` and `callback` arguments')
  313. }
  314.  
  315. if (typeof callback != 'function')
  316. throw new Error('approximateSize() requires a callback argument')
  317.  
  318. if (!this._isBuffer(start))
  319. start = String(start)
  320.  
  321. if (!this._isBuffer(end))
  322. end = String(end)
  323.  
  324. if (typeof this._approximateSize == 'function')
  325. return this._approximateSize(start, end, callback)
  326.  
  327. process.nextTick(function () {
  328. callback(null, 0)
  329. })
  330. }
  331.  
  332. AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) {
  333. var self = this
  334.  
  335. options = xtend(options)
  336.  
  337. ;[ 'start', 'end', 'gt', 'gte', 'lt', 'lte' ].forEach(function (o) {
  338. if (options[o] && self._isBuffer(options[o]) && options[o].length === 0)
  339. delete options[o]
  340. })
  341.  
  342. options.reverse = !!options.reverse
  343.  
  344. // fix `start` so it takes into account gt, gte, lt, lte as appropriate
  345. if (options.reverse && options.lt)
  346. options.start = options.lt
  347. if (options.reverse && options.lte)
  348. options.start = options.lte
  349. if (!options.reverse && options.gt)
  350. options.start = options.gt
  351. if (!options.reverse && options.gte)
  352. options.start = options.gte
  353.  
  354. if ((options.reverse && options.lt && !options.lte)
  355. || (!options.reverse && options.gt && !options.gte))
  356. options.exclusiveStart = true // start should *not* include matching key
  357.  
  358. return options
  359. }
  360.  
  361. AbstractLevelDOWN.prototype.iterator = function (options) {
  362. if (typeof options != 'object')
  363. options = {}
  364.  
  365. options = this._setupIteratorOptions(options)
  366.  
  367. if (typeof this._iterator == 'function')
  368. return this._iterator(options)
  369.  
  370. return new AbstractIterator(this)
  371. }
  372.  
  373. AbstractLevelDOWN.prototype._chainedBatch = function () {
  374. return new AbstractChainedBatch(this)
  375. }
  376.  
  377. AbstractLevelDOWN.prototype._isBuffer = function (obj) {
  378. return Buffer.isBuffer(obj)
  379. }
  380.  
  381. AbstractLevelDOWN.prototype._checkKeyValue = function (obj, type) {
  382.  
  383. if (obj === null || obj === undefined)
  384. return new Error(type + ' cannot be `null` or `undefined`')
  385.  
  386. if (this._isBuffer(obj)) {
  387. if (obj.length === 0)
  388. return new Error(type + ' cannot be an empty Buffer')
  389. } else if (String(obj) === '')
  390. return new Error(type + ' cannot be an empty String')
  391. }
  392.  
  393. module.exports.AbstractLevelDOWN = AbstractLevelDOWN
  394. module.exports.AbstractIterator = AbstractIterator
  395. module.exports.AbstractChainedBatch = AbstractChainedBatch
  396.  
  397. }).call(this,{"isBuffer":require("../is-buffer/index.js")},require('_process'))
  398. },{"../is-buffer/index.js":10,"./abstract-chained-batch":1,"./abstract-iterator":2,"_process":32,"xtend":4}],4:[function(require,module,exports){
  399. module.exports = extend
  400.  
  401. function extend() {
  402. var target = {}
  403.  
  404. for (var i = 0; i < arguments.length; i++) {
  405. var source = arguments[i]
  406.  
  407. for (var key in source) {
  408. if (source.hasOwnProperty(key)) {
  409. target[key] = source[key]
  410. }
  411. }
  412. }
  413.  
  414. return target
  415. }
  416.  
  417. },{}],5:[function(require,module,exports){
  418. 'use strict'
  419.  
  420. exports.byteLength = byteLength
  421. exports.toByteArray = toByteArray
  422. exports.fromByteArray = fromByteArray
  423.  
  424. var lookup = []
  425. var revLookup = []
  426. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  427.  
  428. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  429. for (var i = 0, len = code.length; i < len; ++i) {
  430. lookup[i] = code[i]
  431. revLookup[code.charCodeAt(i)] = i
  432. }
  433.  
  434. revLookup['-'.charCodeAt(0)] = 62
  435. revLookup['_'.charCodeAt(0)] = 63
  436.  
  437. function placeHoldersCount (b64) {
  438. var len = b64.length
  439. if (len % 4 > 0) {
  440. throw new Error('Invalid string. Length must be a multiple of 4')
  441. }
  442.  
  443. // the number of equal signs (place holders)
  444. // if there are two placeholders, than the two characters before it
  445. // represent one byte
  446. // if there is only one, then the three characters before it represent 2 bytes
  447. // this is just a cheap hack to not do indexOf twice
  448. return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
  449. }
  450.  
  451. function byteLength (b64) {
  452. // base64 is 4/3 + up to two characters of the original data
  453. return b64.length * 3 / 4 - placeHoldersCount(b64)
  454. }
  455.  
  456. function toByteArray (b64) {
  457. var i, j, l, tmp, placeHolders, arr
  458. var len = b64.length
  459. placeHolders = placeHoldersCount(b64)
  460.  
  461. arr = new Arr(len * 3 / 4 - placeHolders)
  462.  
  463. // if there are placeholders, only get up to the last complete 4 chars
  464. l = placeHolders > 0 ? len - 4 : len
  465.  
  466. var L = 0
  467.  
  468. for (i = 0, j = 0; i < l; i += 4, j += 3) {
  469. tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
  470. arr[L++] = (tmp >> 16) & 0xFF
  471. arr[L++] = (tmp >> 8) & 0xFF
  472. arr[L++] = tmp & 0xFF
  473. }
  474.  
  475. if (placeHolders === 2) {
  476. tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
  477. arr[L++] = tmp & 0xFF
  478. } else if (placeHolders === 1) {
  479. tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
  480. arr[L++] = (tmp >> 8) & 0xFF
  481. arr[L++] = tmp & 0xFF
  482. }
  483.  
  484. return arr
  485. }
  486.  
  487. function tripletToBase64 (num) {
  488. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
  489. }
  490.  
  491. function encodeChunk (uint8, start, end) {
  492. var tmp
  493. var output = []
  494. for (var i = start; i < end; i += 3) {
  495. tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
  496. output.push(tripletToBase64(tmp))
  497. }
  498. return output.join('')
  499. }
  500.  
  501. function fromByteArray (uint8) {
  502. var tmp
  503. var len = uint8.length
  504. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  505. var output = ''
  506. var parts = []
  507. var maxChunkLength = 16383 // must be multiple of 3
  508.  
  509. // go through the array every three bytes, we'll deal with trailing stuff later
  510. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  511. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
  512. }
  513.  
  514. // pad the end with zeros, but make sure to not forget the extra bytes
  515. if (extraBytes === 1) {
  516. tmp = uint8[len - 1]
  517. output += lookup[tmp >> 2]
  518. output += lookup[(tmp << 4) & 0x3F]
  519. output += '=='
  520. } else if (extraBytes === 2) {
  521. tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
  522. output += lookup[tmp >> 10]
  523. output += lookup[(tmp >> 4) & 0x3F]
  524. output += lookup[(tmp << 2) & 0x3F]
  525. output += '='
  526. }
  527.  
  528. parts.push(output)
  529.  
  530. return parts.join('')
  531. }
  532.  
  533. },{}],6:[function(require,module,exports){
  534. (function (global){
  535. /*!
  536. * The buffer module from node.js, for the browser.
  537. *
  538. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  539. * @license MIT
  540. */
  541. /* eslint-disable no-proto */
  542.  
  543. 'use strict'
  544.  
  545. var base64 = require('base64-js')
  546. var ieee754 = require('ieee754')
  547. var isArray = require('isarray')
  548.  
  549. exports.Buffer = Buffer
  550. exports.SlowBuffer = SlowBuffer
  551. exports.INSPECT_MAX_BYTES = 50
  552.  
  553. /**
  554. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  555. * === true Use Uint8Array implementation (fastest)
  556. * === false Use Object implementation (most compatible, even IE6)
  557. *
  558. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  559. * Opera 11.6+, iOS 4.2+.
  560. *
  561. * Due to various browser bugs, sometimes the Object implementation will be used even
  562. * when the browser supports typed arrays.
  563. *
  564. * Note:
  565. *
  566. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  567. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  568. *
  569. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  570. *
  571. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  572. * incorrect length in some situations.
  573.  
  574. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  575. * get the Object implementation, which is slower but behaves correctly.
  576. */
  577. Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
  578. ? global.TYPED_ARRAY_SUPPORT
  579. : typedArraySupport()
  580.  
  581. /*
  582. * Export kMaxLength after typed array support is determined.
  583. */
  584. exports.kMaxLength = kMaxLength()
  585.  
  586. function typedArraySupport () {
  587. try {
  588. var arr = new Uint8Array(1)
  589. arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
  590. return arr.foo() === 42 && // typed array instances can be augmented
  591. typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
  592. arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
  593. } catch (e) {
  594. return false
  595. }
  596. }
  597.  
  598. function kMaxLength () {
  599. return Buffer.TYPED_ARRAY_SUPPORT
  600. ? 0x7fffffff
  601. : 0x3fffffff
  602. }
  603.  
  604. function createBuffer (that, length) {
  605. if (kMaxLength() < length) {
  606. throw new RangeError('Invalid typed array length')
  607. }
  608. if (Buffer.TYPED_ARRAY_SUPPORT) {
  609. // Return an augmented `Uint8Array` instance, for best performance
  610. that = new Uint8Array(length)
  611. that.__proto__ = Buffer.prototype
  612. } else {
  613. // Fallback: Return an object instance of the Buffer class
  614. if (that === null) {
  615. that = new Buffer(length)
  616. }
  617. that.length = length
  618. }
  619.  
  620. return that
  621. }
  622.  
  623. /**
  624. * The Buffer constructor returns instances of `Uint8Array` that have their
  625. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  626. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  627. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  628. * returns a single octet.
  629. *
  630. * The `Uint8Array` prototype remains unmodified.
  631. */
  632.  
  633. function Buffer (arg, encodingOrOffset, length) {
  634. if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
  635. return new Buffer(arg, encodingOrOffset, length)
  636. }
  637.  
  638. // Common case.
  639. if (typeof arg === 'number') {
  640. if (typeof encodingOrOffset === 'string') {
  641. throw new Error(
  642. 'If encoding is specified then the first argument must be a string'
  643. )
  644. }
  645. return allocUnsafe(this, arg)
  646. }
  647. return from(this, arg, encodingOrOffset, length)
  648. }
  649.  
  650. Buffer.poolSize = 8192 // not used by this implementation
  651.  
  652. // TODO: Legacy, not needed anymore. Remove in next major version.
  653. Buffer._augment = function (arr) {
  654. arr.__proto__ = Buffer.prototype
  655. return arr
  656. }
  657.  
  658. function from (that, value, encodingOrOffset, length) {
  659. if (typeof value === 'number') {
  660. throw new TypeError('"value" argument must not be a number')
  661. }
  662.  
  663. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  664. return fromArrayBuffer(that, value, encodingOrOffset, length)
  665. }
  666.  
  667. if (typeof value === 'string') {
  668. return fromString(that, value, encodingOrOffset)
  669. }
  670.  
  671. return fromObject(that, value)
  672. }
  673.  
  674. /**
  675. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  676. * if value is a number.
  677. * Buffer.from(str[, encoding])
  678. * Buffer.from(array)
  679. * Buffer.from(buffer)
  680. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  681. **/
  682. Buffer.from = function (value, encodingOrOffset, length) {
  683. return from(null, value, encodingOrOffset, length)
  684. }
  685.  
  686. if (Buffer.TYPED_ARRAY_SUPPORT) {
  687. Buffer.prototype.__proto__ = Uint8Array.prototype
  688. Buffer.__proto__ = Uint8Array
  689. if (typeof Symbol !== 'undefined' && Symbol.species &&
  690. Buffer[Symbol.species] === Buffer) {
  691. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  692. Object.defineProperty(Buffer, Symbol.species, {
  693. value: null,
  694. configurable: true
  695. })
  696. }
  697. }
  698.  
  699. function assertSize (size) {
  700. if (typeof size !== 'number') {
  701. throw new TypeError('"size" argument must be a number')
  702. } else if (size < 0) {
  703. throw new RangeError('"size" argument must not be negative')
  704. }
  705. }
  706.  
  707. function alloc (that, size, fill, encoding) {
  708. assertSize(size)
  709. if (size <= 0) {
  710. return createBuffer(that, size)
  711. }
  712. if (fill !== undefined) {
  713. // Only pay attention to encoding if it's a string. This
  714. // prevents accidentally sending in a number that would
  715. // be interpretted as a start offset.
  716. return typeof encoding === 'string'
  717. ? createBuffer(that, size).fill(fill, encoding)
  718. : createBuffer(that, size).fill(fill)
  719. }
  720. return createBuffer(that, size)
  721. }
  722.  
  723. /**
  724. * Creates a new filled Buffer instance.
  725. * alloc(size[, fill[, encoding]])
  726. **/
  727. Buffer.alloc = function (size, fill, encoding) {
  728. return alloc(null, size, fill, encoding)
  729. }
  730.  
  731. function allocUnsafe (that, size) {
  732. assertSize(size)
  733. that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
  734. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  735. for (var i = 0; i < size; ++i) {
  736. that[i] = 0
  737. }
  738. }
  739. return that
  740. }
  741.  
  742. /**
  743. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  744. * */
  745. Buffer.allocUnsafe = function (size) {
  746. return allocUnsafe(null, size)
  747. }
  748. /**
  749. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  750. */
  751. Buffer.allocUnsafeSlow = function (size) {
  752. return allocUnsafe(null, size)
  753. }
  754.  
  755. function fromString (that, string, encoding) {
  756. if (typeof encoding !== 'string' || encoding === '') {
  757. encoding = 'utf8'
  758. }
  759.  
  760. if (!Buffer.isEncoding(encoding)) {
  761. throw new TypeError('"encoding" must be a valid string encoding')
  762. }
  763.  
  764. var length = byteLength(string, encoding) | 0
  765. that = createBuffer(that, length)
  766.  
  767. var actual = that.write(string, encoding)
  768.  
  769. if (actual !== length) {
  770. // Writing a hex string, for example, that contains invalid characters will
  771. // cause everything after the first invalid character to be ignored. (e.g.
  772. // 'abxxcd' will be treated as 'ab')
  773. that = that.slice(0, actual)
  774. }
  775.  
  776. return that
  777. }
  778.  
  779. function fromArrayLike (that, array) {
  780. var length = array.length < 0 ? 0 : checked(array.length) | 0
  781. that = createBuffer(that, length)
  782. for (var i = 0; i < length; i += 1) {
  783. that[i] = array[i] & 255
  784. }
  785. return that
  786. }
  787.  
  788. function fromArrayBuffer (that, array, byteOffset, length) {
  789. array.byteLength // this throws if `array` is not a valid ArrayBuffer
  790.  
  791. if (byteOffset < 0 || array.byteLength < byteOffset) {
  792. throw new RangeError('\'offset\' is out of bounds')
  793. }
  794.  
  795. if (array.byteLength < byteOffset + (length || 0)) {
  796. throw new RangeError('\'length\' is out of bounds')
  797. }
  798.  
  799. if (byteOffset === undefined && length === undefined) {
  800. array = new Uint8Array(array)
  801. } else if (length === undefined) {
  802. array = new Uint8Array(array, byteOffset)
  803. } else {
  804. array = new Uint8Array(array, byteOffset, length)
  805. }
  806.  
  807. if (Buffer.TYPED_ARRAY_SUPPORT) {
  808. // Return an augmented `Uint8Array` instance, for best performance
  809. that = array
  810. that.__proto__ = Buffer.prototype
  811. } else {
  812. // Fallback: Return an object instance of the Buffer class
  813. that = fromArrayLike(that, array)
  814. }
  815. return that
  816. }
  817.  
  818. function fromObject (that, obj) {
  819. if (Buffer.isBuffer(obj)) {
  820. var len = checked(obj.length) | 0
  821. that = createBuffer(that, len)
  822.  
  823. if (that.length === 0) {
  824. return that
  825. }
  826.  
  827. obj.copy(that, 0, 0, len)
  828. return that
  829. }
  830.  
  831. if (obj) {
  832. if ((typeof ArrayBuffer !== 'undefined' &&
  833. obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
  834. if (typeof obj.length !== 'number' || isnan(obj.length)) {
  835. return createBuffer(that, 0)
  836. }
  837. return fromArrayLike(that, obj)
  838. }
  839.  
  840. if (obj.type === 'Buffer' && isArray(obj.data)) {
  841. return fromArrayLike(that, obj.data)
  842. }
  843. }
  844.  
  845. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  846. }
  847.  
  848. function checked (length) {
  849. // Note: cannot use `length < kMaxLength()` here because that fails when
  850. // length is NaN (which is otherwise coerced to zero.)
  851. if (length >= kMaxLength()) {
  852. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  853. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  854. }
  855. return length | 0
  856. }
  857.  
  858. function SlowBuffer (length) {
  859. if (+length != length) { // eslint-disable-line eqeqeq
  860. length = 0
  861. }
  862. return Buffer.alloc(+length)
  863. }
  864.  
  865. Buffer.isBuffer = function isBuffer (b) {
  866. return !!(b != null && b._isBuffer)
  867. }
  868.  
  869. Buffer.compare = function compare (a, b) {
  870. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  871. throw new TypeError('Arguments must be Buffers')
  872. }
  873.  
  874. if (a === b) return 0
  875.  
  876. var x = a.length
  877. var y = b.length
  878.  
  879. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  880. if (a[i] !== b[i]) {
  881. x = a[i]
  882. y = b[i]
  883. break
  884. }
  885. }
  886.  
  887. if (x < y) return -1
  888. if (y < x) return 1
  889. return 0
  890. }
  891.  
  892. Buffer.isEncoding = function isEncoding (encoding) {
  893. switch (String(encoding).toLowerCase()) {
  894. case 'hex':
  895. case 'utf8':
  896. case 'utf-8':
  897. case 'ascii':
  898. case 'latin1':
  899. case 'binary':
  900. case 'base64':
  901. case 'ucs2':
  902. case 'ucs-2':
  903. case 'utf16le':
  904. case 'utf-16le':
  905. return true
  906. default:
  907. return false
  908. }
  909. }
  910.  
  911. Buffer.concat = function concat (list, length) {
  912. if (!isArray(list)) {
  913. throw new TypeError('"list" argument must be an Array of Buffers')
  914. }
  915.  
  916. if (list.length === 0) {
  917. return Buffer.alloc(0)
  918. }
  919.  
  920. var i
  921. if (length === undefined) {
  922. length = 0
  923. for (i = 0; i < list.length; ++i) {
  924. length += list[i].length
  925. }
  926. }
  927.  
  928. var buffer = Buffer.allocUnsafe(length)
  929. var pos = 0
  930. for (i = 0; i < list.length; ++i) {
  931. var buf = list[i]
  932. if (!Buffer.isBuffer(buf)) {
  933. throw new TypeError('"list" argument must be an Array of Buffers')
  934. }
  935. buf.copy(buffer, pos)
  936. pos += buf.length
  937. }
  938. return buffer
  939. }
  940.  
  941. function byteLength (string, encoding) {
  942. if (Buffer.isBuffer(string)) {
  943. return string.length
  944. }
  945. if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
  946. (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
  947. return string.byteLength
  948. }
  949. if (typeof string !== 'string') {
  950. string = '' + string
  951. }
  952.  
  953. var len = string.length
  954. if (len === 0) return 0
  955.  
  956. // Use a for loop to avoid recursion
  957. var loweredCase = false
  958. for (;;) {
  959. switch (encoding) {
  960. case 'ascii':
  961. case 'latin1':
  962. case 'binary':
  963. return len
  964. case 'utf8':
  965. case 'utf-8':
  966. case undefined:
  967. return utf8ToBytes(string).length
  968. case 'ucs2':
  969. case 'ucs-2':
  970. case 'utf16le':
  971. case 'utf-16le':
  972. return len * 2
  973. case 'hex':
  974. return len >>> 1
  975. case 'base64':
  976. return base64ToBytes(string).length
  977. default:
  978. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  979. encoding = ('' + encoding).toLowerCase()
  980. loweredCase = true
  981. }
  982. }
  983. }
  984. Buffer.byteLength = byteLength
  985.  
  986. function slowToString (encoding, start, end) {
  987. var loweredCase = false
  988.  
  989. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  990. // property of a typed array.
  991.  
  992. // This behaves neither like String nor Uint8Array in that we set start/end
  993. // to their upper/lower bounds if the value passed is out of range.
  994. // undefined is handled specially as per ECMA-262 6th Edition,
  995. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  996. if (start === undefined || start < 0) {
  997. start = 0
  998. }
  999. // Return early if start > this.length. Done here to prevent potential uint32
  1000. // coercion fail below.
  1001. if (start > this.length) {
  1002. return ''
  1003. }
  1004.  
  1005. if (end === undefined || end > this.length) {
  1006. end = this.length
  1007. }
  1008.  
  1009. if (end <= 0) {
  1010. return ''
  1011. }
  1012.  
  1013. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  1014. end >>>= 0
  1015. start >>>= 0
  1016.  
  1017. if (end <= start) {
  1018. return ''
  1019. }
  1020.  
  1021. if (!encoding) encoding = 'utf8'
  1022.  
  1023. while (true) {
  1024. switch (encoding) {
  1025. case 'hex':
  1026. return hexSlice(this, start, end)
  1027.  
  1028. case 'utf8':
  1029. case 'utf-8':
  1030. return utf8Slice(this, start, end)
  1031.  
  1032. case 'ascii':
  1033. return asciiSlice(this, start, end)
  1034.  
  1035. case 'latin1':
  1036. case 'binary':
  1037. return latin1Slice(this, start, end)
  1038.  
  1039. case 'base64':
  1040. return base64Slice(this, start, end)
  1041.  
  1042. case 'ucs2':
  1043. case 'ucs-2':
  1044. case 'utf16le':
  1045. case 'utf-16le':
  1046. return utf16leSlice(this, start, end)
  1047.  
  1048. default:
  1049. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  1050. encoding = (encoding + '').toLowerCase()
  1051. loweredCase = true
  1052. }
  1053. }
  1054. }
  1055.  
  1056. // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
  1057. // Buffer instances.
  1058. Buffer.prototype._isBuffer = true
  1059.  
  1060. function swap (b, n, m) {
  1061. var i = b[n]
  1062. b[n] = b[m]
  1063. b[m] = i
  1064. }
  1065.  
  1066. Buffer.prototype.swap16 = function swap16 () {
  1067. var len = this.length
  1068. if (len % 2 !== 0) {
  1069. throw new RangeError('Buffer size must be a multiple of 16-bits')
  1070. }
  1071. for (var i = 0; i < len; i += 2) {
  1072. swap(this, i, i + 1)
  1073. }
  1074. return this
  1075. }
  1076.  
  1077. Buffer.prototype.swap32 = function swap32 () {
  1078. var len = this.length
  1079. if (len % 4 !== 0) {
  1080. throw new RangeError('Buffer size must be a multiple of 32-bits')
  1081. }
  1082. for (var i = 0; i < len; i += 4) {
  1083. swap(this, i, i + 3)
  1084. swap(this, i + 1, i + 2)
  1085. }
  1086. return this
  1087. }
  1088.  
  1089. Buffer.prototype.swap64 = function swap64 () {
  1090. var len = this.length
  1091. if (len % 8 !== 0) {
  1092. throw new RangeError('Buffer size must be a multiple of 64-bits')
  1093. }
  1094. for (var i = 0; i < len; i += 8) {
  1095. swap(this, i, i + 7)
  1096. swap(this, i + 1, i + 6)
  1097. swap(this, i + 2, i + 5)
  1098. swap(this, i + 3, i + 4)
  1099. }
  1100. return this
  1101. }
  1102.  
  1103. Buffer.prototype.toString = function toString () {
  1104. var length = this.length | 0
  1105. if (length === 0) return ''
  1106. if (arguments.length === 0) return utf8Slice(this, 0, length)
  1107. return slowToString.apply(this, arguments)
  1108. }
  1109.  
  1110. Buffer.prototype.equals = function equals (b) {
  1111. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  1112. if (this === b) return true
  1113. return Buffer.compare(this, b) === 0
  1114. }
  1115.  
  1116. Buffer.prototype.inspect = function inspect () {
  1117. var str = ''
  1118. var max = exports.INSPECT_MAX_BYTES
  1119. if (this.length > 0) {
  1120. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
  1121. if (this.length > max) str += ' ... '
  1122. }
  1123. return '<Buffer ' + str + '>'
  1124. }
  1125.  
  1126. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  1127. if (!Buffer.isBuffer(target)) {
  1128. throw new TypeError('Argument must be a Buffer')
  1129. }
  1130.  
  1131. if (start === undefined) {
  1132. start = 0
  1133. }
  1134. if (end === undefined) {
  1135. end = target ? target.length : 0
  1136. }
  1137. if (thisStart === undefined) {
  1138. thisStart = 0
  1139. }
  1140. if (thisEnd === undefined) {
  1141. thisEnd = this.length
  1142. }
  1143.  
  1144. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  1145. throw new RangeError('out of range index')
  1146. }
  1147.  
  1148. if (thisStart >= thisEnd && start >= end) {
  1149. return 0
  1150. }
  1151. if (thisStart >= thisEnd) {
  1152. return -1
  1153. }
  1154. if (start >= end) {
  1155. return 1
  1156. }
  1157.  
  1158. start >>>= 0
  1159. end >>>= 0
  1160. thisStart >>>= 0
  1161. thisEnd >>>= 0
  1162.  
  1163. if (this === target) return 0
  1164.  
  1165. var x = thisEnd - thisStart
  1166. var y = end - start
  1167. var len = Math.min(x, y)
  1168.  
  1169. var thisCopy = this.slice(thisStart, thisEnd)
  1170. var targetCopy = target.slice(start, end)
  1171.  
  1172. for (var i = 0; i < len; ++i) {
  1173. if (thisCopy[i] !== targetCopy[i]) {
  1174. x = thisCopy[i]
  1175. y = targetCopy[i]
  1176. break
  1177. }
  1178. }
  1179.  
  1180. if (x < y) return -1
  1181. if (y < x) return 1
  1182. return 0
  1183. }
  1184.  
  1185. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  1186. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  1187. //
  1188. // Arguments:
  1189. // - buffer - a Buffer to search
  1190. // - val - a string, Buffer, or number
  1191. // - byteOffset - an index into `buffer`; will be clamped to an int32
  1192. // - encoding - an optional encoding, relevant is val is a string
  1193. // - dir - true for indexOf, false for lastIndexOf
  1194. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  1195. // Empty buffer means no match
  1196. if (buffer.length === 0) return -1
  1197.  
  1198. // Normalize byteOffset
  1199. if (typeof byteOffset === 'string') {
  1200. encoding = byteOffset
  1201. byteOffset = 0
  1202. } else if (byteOffset > 0x7fffffff) {
  1203. byteOffset = 0x7fffffff
  1204. } else if (byteOffset < -0x80000000) {
  1205. byteOffset = -0x80000000
  1206. }
  1207. byteOffset = +byteOffset // Coerce to Number.
  1208. if (isNaN(byteOffset)) {
  1209. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  1210. byteOffset = dir ? 0 : (buffer.length - 1)
  1211. }
  1212.  
  1213. // Normalize byteOffset: negative offsets start from the end of the buffer
  1214. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  1215. if (byteOffset >= buffer.length) {
  1216. if (dir) return -1
  1217. else byteOffset = buffer.length - 1
  1218. } else if (byteOffset < 0) {
  1219. if (dir) byteOffset = 0
  1220. else return -1
  1221. }
  1222.  
  1223. // Normalize val
  1224. if (typeof val === 'string') {
  1225. val = Buffer.from(val, encoding)
  1226. }
  1227.  
  1228. // Finally, search either indexOf (if dir is true) or lastIndexOf
  1229. if (Buffer.isBuffer(val)) {
  1230. // Special case: looking for empty string/buffer always fails
  1231. if (val.length === 0) {
  1232. return -1
  1233. }
  1234. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  1235. } else if (typeof val === 'number') {
  1236. val = val & 0xFF // Search for a byte value [0-255]
  1237. if (Buffer.TYPED_ARRAY_SUPPORT &&
  1238. typeof Uint8Array.prototype.indexOf === 'function') {
  1239. if (dir) {
  1240. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  1241. } else {
  1242. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  1243. }
  1244. }
  1245. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  1246. }
  1247.  
  1248. throw new TypeError('val must be string, number or Buffer')
  1249. }
  1250.  
  1251. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  1252. var indexSize = 1
  1253. var arrLength = arr.length
  1254. var valLength = val.length
  1255.  
  1256. if (encoding !== undefined) {
  1257. encoding = String(encoding).toLowerCase()
  1258. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  1259. encoding === 'utf16le' || encoding === 'utf-16le') {
  1260. if (arr.length < 2 || val.length < 2) {
  1261. return -1
  1262. }
  1263. indexSize = 2
  1264. arrLength /= 2
  1265. valLength /= 2
  1266. byteOffset /= 2
  1267. }
  1268. }
  1269.  
  1270. function read (buf, i) {
  1271. if (indexSize === 1) {
  1272. return buf[i]
  1273. } else {
  1274. return buf.readUInt16BE(i * indexSize)
  1275. }
  1276. }
  1277.  
  1278. var i
  1279. if (dir) {
  1280. var foundIndex = -1
  1281. for (i = byteOffset; i < arrLength; i++) {
  1282. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  1283. if (foundIndex === -1) foundIndex = i
  1284. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  1285. } else {
  1286. if (foundIndex !== -1) i -= i - foundIndex
  1287. foundIndex = -1
  1288. }
  1289. }
  1290. } else {
  1291. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  1292. for (i = byteOffset; i >= 0; i--) {
  1293. var found = true
  1294. for (var j = 0; j < valLength; j++) {
  1295. if (read(arr, i + j) !== read(val, j)) {
  1296. found = false
  1297. break
  1298. }
  1299. }
  1300. if (found) return i
  1301. }
  1302. }
  1303.  
  1304. return -1
  1305. }
  1306.  
  1307. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  1308. return this.indexOf(val, byteOffset, encoding) !== -1
  1309. }
  1310.  
  1311. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  1312. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  1313. }
  1314.  
  1315. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  1316. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  1317. }
  1318.  
  1319. function hexWrite (buf, string, offset, length) {
  1320. offset = Number(offset) || 0
  1321. var remaining = buf.length - offset
  1322. if (!length) {
  1323. length = remaining
  1324. } else {
  1325. length = Number(length)
  1326. if (length > remaining) {
  1327. length = remaining
  1328. }
  1329. }
  1330.  
  1331. // must be an even number of digits
  1332. var strLen = string.length
  1333. if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
  1334.  
  1335. if (length > strLen / 2) {
  1336. length = strLen / 2
  1337. }
  1338. for (var i = 0; i < length; ++i) {
  1339. var parsed = parseInt(string.substr(i * 2, 2), 16)
  1340. if (isNaN(parsed)) return i
  1341. buf[offset + i] = parsed
  1342. }
  1343. return i
  1344. }
  1345.  
  1346. function utf8Write (buf, string, offset, length) {
  1347. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  1348. }
  1349.  
  1350. function asciiWrite (buf, string, offset, length) {
  1351. return blitBuffer(asciiToBytes(string), buf, offset, length)
  1352. }
  1353.  
  1354. function latin1Write (buf, string, offset, length) {
  1355. return asciiWrite(buf, string, offset, length)
  1356. }
  1357.  
  1358. function base64Write (buf, string, offset, length) {
  1359. return blitBuffer(base64ToBytes(string), buf, offset, length)
  1360. }
  1361.  
  1362. function ucs2Write (buf, string, offset, length) {
  1363. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  1364. }
  1365.  
  1366. Buffer.prototype.write = function write (string, offset, length, encoding) {
  1367. // Buffer#write(string)
  1368. if (offset === undefined) {
  1369. encoding = 'utf8'
  1370. length = this.length
  1371. offset = 0
  1372. // Buffer#write(string, encoding)
  1373. } else if (length === undefined && typeof offset === 'string') {
  1374. encoding = offset
  1375. length = this.length
  1376. offset = 0
  1377. // Buffer#write(string, offset[, length][, encoding])
  1378. } else if (isFinite(offset)) {
  1379. offset = offset | 0
  1380. if (isFinite(length)) {
  1381. length = length | 0
  1382. if (encoding === undefined) encoding = 'utf8'
  1383. } else {
  1384. encoding = length
  1385. length = undefined
  1386. }
  1387. // legacy write(string, encoding, offset, length) - remove in v0.13
  1388. } else {
  1389. throw new Error(
  1390. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  1391. )
  1392. }
  1393.  
  1394. var remaining = this.length - offset
  1395. if (length === undefined || length > remaining) length = remaining
  1396.  
  1397. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  1398. throw new RangeError('Attempt to write outside buffer bounds')
  1399. }
  1400.  
  1401. if (!encoding) encoding = 'utf8'
  1402.  
  1403. var loweredCase = false
  1404. for (;;) {
  1405. switch (encoding) {
  1406. case 'hex':
  1407. return hexWrite(this, string, offset, length)
  1408.  
  1409. case 'utf8':
  1410. case 'utf-8':
  1411. return utf8Write(this, string, offset, length)
  1412.  
  1413. case 'ascii':
  1414. return asciiWrite(this, string, offset, length)
  1415.  
  1416. case 'latin1':
  1417. case 'binary':
  1418. return latin1Write(this, string, offset, length)
  1419.  
  1420. case 'base64':
  1421. // Warning: maxLength not taken into account in base64Write
  1422. return base64Write(this, string, offset, length)
  1423.  
  1424. case 'ucs2':
  1425. case 'ucs-2':
  1426. case 'utf16le':
  1427. case 'utf-16le':
  1428. return ucs2Write(this, string, offset, length)
  1429.  
  1430. default:
  1431. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  1432. encoding = ('' + encoding).toLowerCase()
  1433. loweredCase = true
  1434. }
  1435. }
  1436. }
  1437.  
  1438. Buffer.prototype.toJSON = function toJSON () {
  1439. return {
  1440. type: 'Buffer',
  1441. data: Array.prototype.slice.call(this._arr || this, 0)
  1442. }
  1443. }
  1444.  
  1445. function base64Slice (buf, start, end) {
  1446. if (start === 0 && end === buf.length) {
  1447. return base64.fromByteArray(buf)
  1448. } else {
  1449. return base64.fromByteArray(buf.slice(start, end))
  1450. }
  1451. }
  1452.  
  1453. function utf8Slice (buf, start, end) {
  1454. end = Math.min(buf.length, end)
  1455. var res = []
  1456.  
  1457. var i = start
  1458. while (i < end) {
  1459. var firstByte = buf[i]
  1460. var codePoint = null
  1461. var bytesPerSequence = (firstByte > 0xEF) ? 4
  1462. : (firstByte > 0xDF) ? 3
  1463. : (firstByte > 0xBF) ? 2
  1464. : 1
  1465.  
  1466. if (i + bytesPerSequence <= end) {
  1467. var secondByte, thirdByte, fourthByte, tempCodePoint
  1468.  
  1469. switch (bytesPerSequence) {
  1470. case 1:
  1471. if (firstByte < 0x80) {
  1472. codePoint = firstByte
  1473. }
  1474. break
  1475. case 2:
  1476. secondByte = buf[i + 1]
  1477. if ((secondByte & 0xC0) === 0x80) {
  1478. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  1479. if (tempCodePoint > 0x7F) {
  1480. codePoint = tempCodePoint
  1481. }
  1482. }
  1483. break
  1484. case 3:
  1485. secondByte = buf[i + 1]
  1486. thirdByte = buf[i + 2]
  1487. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  1488. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  1489. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  1490. codePoint = tempCodePoint
  1491. }
  1492. }
  1493. break
  1494. case 4:
  1495. secondByte = buf[i + 1]
  1496. thirdByte = buf[i + 2]
  1497. fourthByte = buf[i + 3]
  1498. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  1499. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  1500. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  1501. codePoint = tempCodePoint
  1502. }
  1503. }
  1504. }
  1505. }
  1506.  
  1507. if (codePoint === null) {
  1508. // we did not generate a valid codePoint so insert a
  1509. // replacement char (U+FFFD) and advance only 1 byte
  1510. codePoint = 0xFFFD
  1511. bytesPerSequence = 1
  1512. } else if (codePoint > 0xFFFF) {
  1513. // encode to utf16 (surrogate pair dance)
  1514. codePoint -= 0x10000
  1515. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  1516. codePoint = 0xDC00 | codePoint & 0x3FF
  1517. }
  1518.  
  1519. res.push(codePoint)
  1520. i += bytesPerSequence
  1521. }
  1522.  
  1523. return decodeCodePointsArray(res)
  1524. }
  1525.  
  1526. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  1527. // the lowest limit is Chrome, with 0x10000 args.
  1528. // We go 1 magnitude less, for safety
  1529. var MAX_ARGUMENTS_LENGTH = 0x1000
  1530.  
  1531. function decodeCodePointsArray (codePoints) {
  1532. var len = codePoints.length
  1533. if (len <= MAX_ARGUMENTS_LENGTH) {
  1534. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  1535. }
  1536.  
  1537. // Decode in chunks to avoid "call stack size exceeded".
  1538. var res = ''
  1539. var i = 0
  1540. while (i < len) {
  1541. res += String.fromCharCode.apply(
  1542. String,
  1543. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  1544. )
  1545. }
  1546. return res
  1547. }
  1548.  
  1549. function asciiSlice (buf, start, end) {
  1550. var ret = ''
  1551. end = Math.min(buf.length, end)
  1552.  
  1553. for (var i = start; i < end; ++i) {
  1554. ret += String.fromCharCode(buf[i] & 0x7F)
  1555. }
  1556. return ret
  1557. }
  1558.  
  1559. function latin1Slice (buf, start, end) {
  1560. var ret = ''
  1561. end = Math.min(buf.length, end)
  1562.  
  1563. for (var i = start; i < end; ++i) {
  1564. ret += String.fromCharCode(buf[i])
  1565. }
  1566. return ret
  1567. }
  1568.  
  1569. function hexSlice (buf, start, end) {
  1570. var len = buf.length
  1571.  
  1572. if (!start || start < 0) start = 0
  1573. if (!end || end < 0 || end > len) end = len
  1574.  
  1575. var out = ''
  1576. for (var i = start; i < end; ++i) {
  1577. out += toHex(buf[i])
  1578. }
  1579. return out
  1580. }
  1581.  
  1582. function utf16leSlice (buf, start, end) {
  1583. var bytes = buf.slice(start, end)
  1584. var res = ''
  1585. for (var i = 0; i < bytes.length; i += 2) {
  1586. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
  1587. }
  1588. return res
  1589. }
  1590.  
  1591. Buffer.prototype.slice = function slice (start, end) {
  1592. var len = this.length
  1593. start = ~~start
  1594. end = end === undefined ? len : ~~end
  1595.  
  1596. if (start < 0) {
  1597. start += len
  1598. if (start < 0) start = 0
  1599. } else if (start > len) {
  1600. start = len
  1601. }
  1602.  
  1603. if (end < 0) {
  1604. end += len
  1605. if (end < 0) end = 0
  1606. } else if (end > len) {
  1607. end = len
  1608. }
  1609.  
  1610. if (end < start) end = start
  1611.  
  1612. var newBuf
  1613. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1614. newBuf = this.subarray(start, end)
  1615. newBuf.__proto__ = Buffer.prototype
  1616. } else {
  1617. var sliceLen = end - start
  1618. newBuf = new Buffer(sliceLen, undefined)
  1619. for (var i = 0; i < sliceLen; ++i) {
  1620. newBuf[i] = this[i + start]
  1621. }
  1622. }
  1623.  
  1624. return newBuf
  1625. }
  1626.  
  1627. /*
  1628. * Need to make sure that buffer isn't trying to write out of bounds.
  1629. */
  1630. function checkOffset (offset, ext, length) {
  1631. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  1632. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  1633. }
  1634.  
  1635. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  1636. offset = offset | 0
  1637. byteLength = byteLength | 0
  1638. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1639.  
  1640. var val = this[offset]
  1641. var mul = 1
  1642. var i = 0
  1643. while (++i < byteLength && (mul *= 0x100)) {
  1644. val += this[offset + i] * mul
  1645. }
  1646.  
  1647. return val
  1648. }
  1649.  
  1650. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  1651. offset = offset | 0
  1652. byteLength = byteLength | 0
  1653. if (!noAssert) {
  1654. checkOffset(offset, byteLength, this.length)
  1655. }
  1656.  
  1657. var val = this[offset + --byteLength]
  1658. var mul = 1
  1659. while (byteLength > 0 && (mul *= 0x100)) {
  1660. val += this[offset + --byteLength] * mul
  1661. }
  1662.  
  1663. return val
  1664. }
  1665.  
  1666. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  1667. if (!noAssert) checkOffset(offset, 1, this.length)
  1668. return this[offset]
  1669. }
  1670.  
  1671. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  1672. if (!noAssert) checkOffset(offset, 2, this.length)
  1673. return this[offset] | (this[offset + 1] << 8)
  1674. }
  1675.  
  1676. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  1677. if (!noAssert) checkOffset(offset, 2, this.length)
  1678. return (this[offset] << 8) | this[offset + 1]
  1679. }
  1680.  
  1681. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  1682. if (!noAssert) checkOffset(offset, 4, this.length)
  1683.  
  1684. return ((this[offset]) |
  1685. (this[offset + 1] << 8) |
  1686. (this[offset + 2] << 16)) +
  1687. (this[offset + 3] * 0x1000000)
  1688. }
  1689.  
  1690. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  1691. if (!noAssert) checkOffset(offset, 4, this.length)
  1692.  
  1693. return (this[offset] * 0x1000000) +
  1694. ((this[offset + 1] << 16) |
  1695. (this[offset + 2] << 8) |
  1696. this[offset + 3])
  1697. }
  1698.  
  1699. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  1700. offset = offset | 0
  1701. byteLength = byteLength | 0
  1702. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1703.  
  1704. var val = this[offset]
  1705. var mul = 1
  1706. var i = 0
  1707. while (++i < byteLength && (mul *= 0x100)) {
  1708. val += this[offset + i] * mul
  1709. }
  1710. mul *= 0x80
  1711.  
  1712. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1713.  
  1714. return val
  1715. }
  1716.  
  1717. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  1718. offset = offset | 0
  1719. byteLength = byteLength | 0
  1720. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1721.  
  1722. var i = byteLength
  1723. var mul = 1
  1724. var val = this[offset + --i]
  1725. while (i > 0 && (mul *= 0x100)) {
  1726. val += this[offset + --i] * mul
  1727. }
  1728. mul *= 0x80
  1729.  
  1730. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1731.  
  1732. return val
  1733. }
  1734.  
  1735. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  1736. if (!noAssert) checkOffset(offset, 1, this.length)
  1737. if (!(this[offset] & 0x80)) return (this[offset])
  1738. return ((0xff - this[offset] + 1) * -1)
  1739. }
  1740.  
  1741. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  1742. if (!noAssert) checkOffset(offset, 2, this.length)
  1743. var val = this[offset] | (this[offset + 1] << 8)
  1744. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1745. }
  1746.  
  1747. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  1748. if (!noAssert) checkOffset(offset, 2, this.length)
  1749. var val = this[offset + 1] | (this[offset] << 8)
  1750. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1751. }
  1752.  
  1753. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  1754. if (!noAssert) checkOffset(offset, 4, this.length)
  1755.  
  1756. return (this[offset]) |
  1757. (this[offset + 1] << 8) |
  1758. (this[offset + 2] << 16) |
  1759. (this[offset + 3] << 24)
  1760. }
  1761.  
  1762. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  1763. if (!noAssert) checkOffset(offset, 4, this.length)
  1764.  
  1765. return (this[offset] << 24) |
  1766. (this[offset + 1] << 16) |
  1767. (this[offset + 2] << 8) |
  1768. (this[offset + 3])
  1769. }
  1770.  
  1771. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  1772. if (!noAssert) checkOffset(offset, 4, this.length)
  1773. return ieee754.read(this, offset, true, 23, 4)
  1774. }
  1775.  
  1776. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  1777. if (!noAssert) checkOffset(offset, 4, this.length)
  1778. return ieee754.read(this, offset, false, 23, 4)
  1779. }
  1780.  
  1781. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  1782. if (!noAssert) checkOffset(offset, 8, this.length)
  1783. return ieee754.read(this, offset, true, 52, 8)
  1784. }
  1785.  
  1786. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  1787. if (!noAssert) checkOffset(offset, 8, this.length)
  1788. return ieee754.read(this, offset, false, 52, 8)
  1789. }
  1790.  
  1791. function checkInt (buf, value, offset, ext, max, min) {
  1792. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  1793. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  1794. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1795. }
  1796.  
  1797. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  1798. value = +value
  1799. offset = offset | 0
  1800. byteLength = byteLength | 0
  1801. if (!noAssert) {
  1802. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1803. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1804. }
  1805.  
  1806. var mul = 1
  1807. var i = 0
  1808. this[offset] = value & 0xFF
  1809. while (++i < byteLength && (mul *= 0x100)) {
  1810. this[offset + i] = (value / mul) & 0xFF
  1811. }
  1812.  
  1813. return offset + byteLength
  1814. }
  1815.  
  1816. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  1817. value = +value
  1818. offset = offset | 0
  1819. byteLength = byteLength | 0
  1820. if (!noAssert) {
  1821. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1822. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1823. }
  1824.  
  1825. var i = byteLength - 1
  1826. var mul = 1
  1827. this[offset + i] = value & 0xFF
  1828. while (--i >= 0 && (mul *= 0x100)) {
  1829. this[offset + i] = (value / mul) & 0xFF
  1830. }
  1831.  
  1832. return offset + byteLength
  1833. }
  1834.  
  1835. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  1836. value = +value
  1837. offset = offset | 0
  1838. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  1839. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1840. this[offset] = (value & 0xff)
  1841. return offset + 1
  1842. }
  1843.  
  1844. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  1845. if (value < 0) value = 0xffff + value + 1
  1846. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
  1847. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  1848. (littleEndian ? i : 1 - i) * 8
  1849. }
  1850. }
  1851.  
  1852. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  1853. value = +value
  1854. offset = offset | 0
  1855. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1856. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1857. this[offset] = (value & 0xff)
  1858. this[offset + 1] = (value >>> 8)
  1859. } else {
  1860. objectWriteUInt16(this, value, offset, true)
  1861. }
  1862. return offset + 2
  1863. }
  1864.  
  1865. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  1866. value = +value
  1867. offset = offset | 0
  1868. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1869. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1870. this[offset] = (value >>> 8)
  1871. this[offset + 1] = (value & 0xff)
  1872. } else {
  1873. objectWriteUInt16(this, value, offset, false)
  1874. }
  1875. return offset + 2
  1876. }
  1877.  
  1878. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  1879. if (value < 0) value = 0xffffffff + value + 1
  1880. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
  1881. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
  1882. }
  1883. }
  1884.  
  1885. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  1886. value = +value
  1887. offset = offset | 0
  1888. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1889. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1890. this[offset + 3] = (value >>> 24)
  1891. this[offset + 2] = (value >>> 16)
  1892. this[offset + 1] = (value >>> 8)
  1893. this[offset] = (value & 0xff)
  1894. } else {
  1895. objectWriteUInt32(this, value, offset, true)
  1896. }
  1897. return offset + 4
  1898. }
  1899.  
  1900. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  1901. value = +value
  1902. offset = offset | 0
  1903. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1904. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1905. this[offset] = (value >>> 24)
  1906. this[offset + 1] = (value >>> 16)
  1907. this[offset + 2] = (value >>> 8)
  1908. this[offset + 3] = (value & 0xff)
  1909. } else {
  1910. objectWriteUInt32(this, value, offset, false)
  1911. }
  1912. return offset + 4
  1913. }
  1914.  
  1915. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  1916. value = +value
  1917. offset = offset | 0
  1918. if (!noAssert) {
  1919. var limit = Math.pow(2, 8 * byteLength - 1)
  1920.  
  1921. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1922. }
  1923.  
  1924. var i = 0
  1925. var mul = 1
  1926. var sub = 0
  1927. this[offset] = value & 0xFF
  1928. while (++i < byteLength && (mul *= 0x100)) {
  1929. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  1930. sub = 1
  1931. }
  1932. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1933. }
  1934.  
  1935. return offset + byteLength
  1936. }
  1937.  
  1938. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  1939. value = +value
  1940. offset = offset | 0
  1941. if (!noAssert) {
  1942. var limit = Math.pow(2, 8 * byteLength - 1)
  1943.  
  1944. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1945. }
  1946.  
  1947. var i = byteLength - 1
  1948. var mul = 1
  1949. var sub = 0
  1950. this[offset + i] = value & 0xFF
  1951. while (--i >= 0 && (mul *= 0x100)) {
  1952. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  1953. sub = 1
  1954. }
  1955. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1956. }
  1957.  
  1958. return offset + byteLength
  1959. }
  1960.  
  1961. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  1962. value = +value
  1963. offset = offset | 0
  1964. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  1965. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1966. if (value < 0) value = 0xff + value + 1
  1967. this[offset] = (value & 0xff)
  1968. return offset + 1
  1969. }
  1970.  
  1971. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  1972. value = +value
  1973. offset = offset | 0
  1974. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1975. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1976. this[offset] = (value & 0xff)
  1977. this[offset + 1] = (value >>> 8)
  1978. } else {
  1979. objectWriteUInt16(this, value, offset, true)
  1980. }
  1981. return offset + 2
  1982. }
  1983.  
  1984. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  1985. value = +value
  1986. offset = offset | 0
  1987. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1988. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1989. this[offset] = (value >>> 8)
  1990. this[offset + 1] = (value & 0xff)
  1991. } else {
  1992. objectWriteUInt16(this, value, offset, false)
  1993. }
  1994. return offset + 2
  1995. }
  1996.  
  1997. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  1998. value = +value
  1999. offset = offset | 0
  2000. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  2001. if (Buffer.TYPED_ARRAY_SUPPORT) {
  2002. this[offset] = (value & 0xff)
  2003. this[offset + 1] = (value >>> 8)
  2004. this[offset + 2] = (value >>> 16)
  2005. this[offset + 3] = (value >>> 24)
  2006. } else {
  2007. objectWriteUInt32(this, value, offset, true)
  2008. }
  2009. return offset + 4
  2010. }
  2011.  
  2012. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  2013. value = +value
  2014. offset = offset | 0
  2015. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  2016. if (value < 0) value = 0xffffffff + value + 1
  2017. if (Buffer.TYPED_ARRAY_SUPPORT) {
  2018. this[offset] = (value >>> 24)
  2019. this[offset + 1] = (value >>> 16)
  2020. this[offset + 2] = (value >>> 8)
  2021. this[offset + 3] = (value & 0xff)
  2022. } else {
  2023. objectWriteUInt32(this, value, offset, false)
  2024. }
  2025. return offset + 4
  2026. }
  2027.  
  2028. function checkIEEE754 (buf, value, offset, ext, max, min) {
  2029. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  2030. if (offset < 0) throw new RangeError('Index out of range')
  2031. }
  2032.  
  2033. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  2034. if (!noAssert) {
  2035. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  2036. }
  2037. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  2038. return offset + 4
  2039. }
  2040.  
  2041. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  2042. return writeFloat(this, value, offset, true, noAssert)
  2043. }
  2044.  
  2045. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  2046. return writeFloat(this, value, offset, false, noAssert)
  2047. }
  2048.  
  2049. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  2050. if (!noAssert) {
  2051. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  2052. }
  2053. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  2054. return offset + 8
  2055. }
  2056.  
  2057. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  2058. return writeDouble(this, value, offset, true, noAssert)
  2059. }
  2060.  
  2061. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  2062. return writeDouble(this, value, offset, false, noAssert)
  2063. }
  2064.  
  2065. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  2066. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  2067. if (!start) start = 0
  2068. if (!end && end !== 0) end = this.length
  2069. if (targetStart >= target.length) targetStart = target.length
  2070. if (!targetStart) targetStart = 0
  2071. if (end > 0 && end < start) end = start
  2072.  
  2073. // Copy 0 bytes; we're done
  2074. if (end === start) return 0
  2075. if (target.length === 0 || this.length === 0) return 0
  2076.  
  2077. // Fatal error conditions
  2078. if (targetStart < 0) {
  2079. throw new RangeError('targetStart out of bounds')
  2080. }
  2081. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  2082. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  2083.  
  2084. // Are we oob?
  2085. if (end > this.length) end = this.length
  2086. if (target.length - targetStart < end - start) {
  2087. end = target.length - targetStart + start
  2088. }
  2089.  
  2090. var len = end - start
  2091. var i
  2092.  
  2093. if (this === target && start < targetStart && targetStart < end) {
  2094. // descending copy from end
  2095. for (i = len - 1; i >= 0; --i) {
  2096. target[i + targetStart] = this[i + start]
  2097. }
  2098. } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  2099. // ascending copy from start
  2100. for (i = 0; i < len; ++i) {
  2101. target[i + targetStart] = this[i + start]
  2102. }
  2103. } else {
  2104. Uint8Array.prototype.set.call(
  2105. target,
  2106. this.subarray(start, start + len),
  2107. targetStart
  2108. )
  2109. }
  2110.  
  2111. return len
  2112. }
  2113.  
  2114. // Usage:
  2115. // buffer.fill(number[, offset[, end]])
  2116. // buffer.fill(buffer[, offset[, end]])
  2117. // buffer.fill(string[, offset[, end]][, encoding])
  2118. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  2119. // Handle string cases:
  2120. if (typeof val === 'string') {
  2121. if (typeof start === 'string') {
  2122. encoding = start
  2123. start = 0
  2124. end = this.length
  2125. } else if (typeof end === 'string') {
  2126. encoding = end
  2127. end = this.length
  2128. }
  2129. if (val.length === 1) {
  2130. var code = val.charCodeAt(0)
  2131. if (code < 256) {
  2132. val = code
  2133. }
  2134. }
  2135. if (encoding !== undefined && typeof encoding !== 'string') {
  2136. throw new TypeError('encoding must be a string')
  2137. }
  2138. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  2139. throw new TypeError('Unknown encoding: ' + encoding)
  2140. }
  2141. } else if (typeof val === 'number') {
  2142. val = val & 255
  2143. }
  2144.  
  2145. // Invalid ranges are not set to a default, so can range check early.
  2146. if (start < 0 || this.length < start || this.length < end) {
  2147. throw new RangeError('Out of range index')
  2148. }
  2149.  
  2150. if (end <= start) {
  2151. return this
  2152. }
  2153.  
  2154. start = start >>> 0
  2155. end = end === undefined ? this.length : end >>> 0
  2156.  
  2157. if (!val) val = 0
  2158.  
  2159. var i
  2160. if (typeof val === 'number') {
  2161. for (i = start; i < end; ++i) {
  2162. this[i] = val
  2163. }
  2164. } else {
  2165. var bytes = Buffer.isBuffer(val)
  2166. ? val
  2167. : utf8ToBytes(new Buffer(val, encoding).toString())
  2168. var len = bytes.length
  2169. for (i = 0; i < end - start; ++i) {
  2170. this[i + start] = bytes[i % len]
  2171. }
  2172. }
  2173.  
  2174. return this
  2175. }
  2176.  
  2177. // HELPER FUNCTIONS
  2178. // ================
  2179.  
  2180. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
  2181.  
  2182. function base64clean (str) {
  2183. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  2184. str = stringtrim(str).replace(INVALID_BASE64_RE, '')
  2185. // Node converts strings with length < 2 to ''
  2186. if (str.length < 2) return ''
  2187. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  2188. while (str.length % 4 !== 0) {
  2189. str = str + '='
  2190. }
  2191. return str
  2192. }
  2193.  
  2194. function stringtrim (str) {
  2195. if (str.trim) return str.trim()
  2196. return str.replace(/^\s+|\s+$/g, '')
  2197. }
  2198.  
  2199. function toHex (n) {
  2200. if (n < 16) return '0' + n.toString(16)
  2201. return n.toString(16)
  2202. }
  2203.  
  2204. function utf8ToBytes (string, units) {
  2205. units = units || Infinity
  2206. var codePoint
  2207. var length = string.length
  2208. var leadSurrogate = null
  2209. var bytes = []
  2210.  
  2211. for (var i = 0; i < length; ++i) {
  2212. codePoint = string.charCodeAt(i)
  2213.  
  2214. // is surrogate component
  2215. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  2216. // last char was a lead
  2217. if (!leadSurrogate) {
  2218. // no lead yet
  2219. if (codePoint > 0xDBFF) {
  2220. // unexpected trail
  2221. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  2222. continue
  2223. } else if (i + 1 === length) {
  2224. // unpaired lead
  2225. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  2226. continue
  2227. }
  2228.  
  2229. // valid lead
  2230. leadSurrogate = codePoint
  2231.  
  2232. continue
  2233. }
  2234.  
  2235. // 2 leads in a row
  2236. if (codePoint < 0xDC00) {
  2237. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  2238. leadSurrogate = codePoint
  2239. continue
  2240. }
  2241.  
  2242. // valid surrogate pair
  2243. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  2244. } else if (leadSurrogate) {
  2245. // valid bmp char, but last char was a lead
  2246. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  2247. }
  2248.  
  2249. leadSurrogate = null
  2250.  
  2251. // encode utf8
  2252. if (codePoint < 0x80) {
  2253. if ((units -= 1) < 0) break
  2254. bytes.push(codePoint)
  2255. } else if (codePoint < 0x800) {
  2256. if ((units -= 2) < 0) break
  2257. bytes.push(
  2258. codePoint >> 0x6 | 0xC0,
  2259. codePoint & 0x3F | 0x80
  2260. )
  2261. } else if (codePoint < 0x10000) {
  2262. if ((units -= 3) < 0) break
  2263. bytes.push(
  2264. codePoint >> 0xC | 0xE0,
  2265. codePoint >> 0x6 & 0x3F | 0x80,
  2266. codePoint & 0x3F | 0x80
  2267. )
  2268. } else if (codePoint < 0x110000) {
  2269. if ((units -= 4) < 0) break
  2270. bytes.push(
  2271. codePoint >> 0x12 | 0xF0,
  2272. codePoint >> 0xC & 0x3F | 0x80,
  2273. codePoint >> 0x6 & 0x3F | 0x80,
  2274. codePoint & 0x3F | 0x80
  2275. )
  2276. } else {
  2277. throw new Error('Invalid code point')
  2278. }
  2279. }
  2280.  
  2281. return bytes
  2282. }
  2283.  
  2284. function asciiToBytes (str) {
  2285. var byteArray = []
  2286. for (var i = 0; i < str.length; ++i) {
  2287. // Node's code seems to be doing this and not & 0x7F..
  2288. byteArray.push(str.charCodeAt(i) & 0xFF)
  2289. }
  2290. return byteArray
  2291. }
  2292.  
  2293. function utf16leToBytes (str, units) {
  2294. var c, hi, lo
  2295. var byteArray = []
  2296. for (var i = 0; i < str.length; ++i) {
  2297. if ((units -= 2) < 0) break
  2298.  
  2299. c = str.charCodeAt(i)
  2300. hi = c >> 8
  2301. lo = c % 256
  2302. byteArray.push(lo)
  2303. byteArray.push(hi)
  2304. }
  2305.  
  2306. return byteArray
  2307. }
  2308.  
  2309. function base64ToBytes (str) {
  2310. return base64.toByteArray(base64clean(str))
  2311. }
  2312.  
  2313. function blitBuffer (src, dst, offset, length) {
  2314. for (var i = 0; i < length; ++i) {
  2315. if ((i + offset >= dst.length) || (i >= src.length)) break
  2316. dst[i + offset] = src[i]
  2317. }
  2318. return i
  2319. }
  2320.  
  2321. function isnan (val) {
  2322. return val !== val // eslint-disable-line no-self-compare
  2323. }
  2324.  
  2325. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2326. },{"base64-js":5,"ieee754":8,"isarray":11}],7:[function(require,module,exports){
  2327. /*global window:false, self:false, define:false, module:false */
  2328.  
  2329. /**
  2330. * @license IDBWrapper - A cross-browser wrapper for IndexedDB
  2331. * Version 1.7.1
  2332. * Copyright (c) 2011 - 2016 Jens Arps
  2333. * http://jensarps.de/
  2334. *
  2335. * Licensed under the MIT (X11) license
  2336. */
  2337.  
  2338. (function (name, definition, global) {
  2339.  
  2340. 'use strict';
  2341.  
  2342. if (typeof define === 'function') {
  2343. define(definition);
  2344. } else if (typeof module !== 'undefined' && module.exports) {
  2345. module.exports = definition();
  2346. } else {
  2347. global[name] = definition();
  2348. }
  2349. })('IDBStore', function () {
  2350.  
  2351. 'use strict';
  2352.  
  2353. var defaultErrorHandler = function (error) {
  2354. throw error;
  2355. };
  2356. var defaultSuccessHandler = function () {
  2357. };
  2358.  
  2359. var defaults = {
  2360. storeName: 'Store',
  2361. storePrefix: 'IDBWrapper-',
  2362. dbVersion: 1,
  2363. keyPath: 'id',
  2364. autoIncrement: true,
  2365. onStoreReady: function () {
  2366. },
  2367. onError: defaultErrorHandler,
  2368. indexes: [],
  2369. implementationPreference: [
  2370. 'indexedDB',
  2371. 'webkitIndexedDB',
  2372. 'mozIndexedDB',
  2373. 'shimIndexedDB'
  2374. ]
  2375. };
  2376.  
  2377. /**
  2378. *
  2379. * The IDBStore constructor
  2380. *
  2381. * @constructor
  2382. * @name IDBStore
  2383. * @version 1.7.1
  2384. *
  2385. * @param {Object} [kwArgs] An options object used to configure the store and
  2386. * set callbacks
  2387. * @param {String} [kwArgs.storeName='Store'] The name of the store
  2388. * @param {String} [kwArgs.storePrefix='IDBWrapper-'] A prefix that is
  2389. * internally used to construct the name of the database, which will be
  2390. * kwArgs.storePrefix + kwArgs.storeName
  2391. * @param {Number} [kwArgs.dbVersion=1] The version of the store
  2392. * @param {String} [kwArgs.keyPath='id'] The key path to use. If you want to
  2393. * setup IDBWrapper to work with out-of-line keys, you need to set this to
  2394. * `null`
  2395. * @param {Boolean} [kwArgs.autoIncrement=true] If set to true, IDBStore will
  2396. * automatically make sure a unique keyPath value is present on each object
  2397. * that is stored.
  2398. * @param {Function} [kwArgs.onStoreReady] A callback to be called when the
  2399. * store is ready to be used.
  2400. * @param {Function} [kwArgs.onError=throw] A callback to be called when an
  2401. * error occurred during instantiation of the store.
  2402. * @param {Array} [kwArgs.indexes=[]] An array of indexData objects
  2403. * defining the indexes to use with the store. For every index to be used
  2404. * one indexData object needs to be passed in the array.
  2405. * An indexData object is defined as follows:
  2406. * @param {Object} [kwArgs.indexes.indexData] An object defining the index to
  2407. * use
  2408. * @param {String} kwArgs.indexes.indexData.name The name of the index
  2409. * @param {String} [kwArgs.indexes.indexData.keyPath] The key path of the index
  2410. * @param {Boolean} [kwArgs.indexes.indexData.unique] Whether the index is unique
  2411. * @param {Boolean} [kwArgs.indexes.indexData.multiEntry] Whether the index is multi entry
  2412. * @param {Array} [kwArgs.implementationPreference=['indexedDB','webkitIndexedDB','mozIndexedDB','shimIndexedDB']] An array of strings naming implementations to be used, in order or preference
  2413. * @param {Function} [onStoreReady] A callback to be called when the store
  2414. * is ready to be used.
  2415. * @example
  2416. // create a store for customers with an additional index over the
  2417. // `lastname` property.
  2418. var myCustomerStore = new IDBStore({
  2419. dbVersion: 1,
  2420. storeName: 'customer-index',
  2421. keyPath: 'customerid',
  2422. autoIncrement: true,
  2423. onStoreReady: populateTable,
  2424. indexes: [
  2425. { name: 'lastname', keyPath: 'lastname', unique: false, multiEntry: false }
  2426. ]
  2427. });
  2428. * @example
  2429. // create a generic store
  2430. var myCustomerStore = new IDBStore({
  2431. storeName: 'my-data-store',
  2432. onStoreReady: function(){
  2433. // start working with the store.
  2434. }
  2435. });
  2436. */
  2437. var IDBStore = function (kwArgs, onStoreReady) {
  2438.  
  2439. if (typeof onStoreReady == 'undefined' && typeof kwArgs == 'function') {
  2440. onStoreReady = kwArgs;
  2441. }
  2442. if (Object.prototype.toString.call(kwArgs) != '[object Object]') {
  2443. kwArgs = {};
  2444. }
  2445.  
  2446. for (var key in defaults) {
  2447. this[key] = typeof kwArgs[key] != 'undefined' ? kwArgs[key] : defaults[key];
  2448. }
  2449.  
  2450. this.dbName = this.storePrefix + this.storeName;
  2451. this.dbVersion = parseInt(this.dbVersion, 10) || 1;
  2452.  
  2453. onStoreReady && (this.onStoreReady = onStoreReady);
  2454.  
  2455. var env = typeof window == 'object' ? window : self;
  2456. var availableImplementations = this.implementationPreference.filter(function (implName) {
  2457. return implName in env;
  2458. });
  2459. this.implementation = availableImplementations[0];
  2460. this.idb = env[this.implementation];
  2461. this.keyRange = env.IDBKeyRange || env.webkitIDBKeyRange || env.mozIDBKeyRange;
  2462.  
  2463. this.consts = {
  2464. 'READ_ONLY': 'readonly',
  2465. 'READ_WRITE': 'readwrite',
  2466. 'VERSION_CHANGE': 'versionchange',
  2467. 'NEXT': 'next',
  2468. 'NEXT_NO_DUPLICATE': 'nextunique',
  2469. 'PREV': 'prev',
  2470. 'PREV_NO_DUPLICATE': 'prevunique'
  2471. };
  2472.  
  2473. this.openDB();
  2474. };
  2475.  
  2476. /** @lends IDBStore.prototype */
  2477. var proto = {
  2478.  
  2479. /**
  2480. * A pointer to the IDBStore ctor
  2481. *
  2482. * @private
  2483. * @type {Function}
  2484. * @constructs
  2485. */
  2486. constructor: IDBStore,
  2487.  
  2488. /**
  2489. * The version of IDBStore
  2490. *
  2491. * @type {String}
  2492. */
  2493. version: '1.7.1',
  2494.  
  2495. /**
  2496. * A reference to the IndexedDB object
  2497. *
  2498. * @type {IDBDatabase}
  2499. */
  2500. db: null,
  2501.  
  2502. /**
  2503. * The full name of the IndexedDB used by IDBStore, composed of
  2504. * this.storePrefix + this.storeName
  2505. *
  2506. * @type {String}
  2507. */
  2508. dbName: null,
  2509.  
  2510. /**
  2511. * The version of the IndexedDB used by IDBStore
  2512. *
  2513. * @type {Number}
  2514. */
  2515. dbVersion: null,
  2516.  
  2517. /**
  2518. * A reference to the objectStore used by IDBStore
  2519. *
  2520. * @type {IDBObjectStore}
  2521. */
  2522. store: null,
  2523.  
  2524. /**
  2525. * The store name
  2526. *
  2527. * @type {String}
  2528. */
  2529. storeName: null,
  2530.  
  2531. /**
  2532. * The prefix to prepend to the store name
  2533. *
  2534. * @type {String}
  2535. */
  2536. storePrefix: null,
  2537.  
  2538. /**
  2539. * The key path
  2540. *
  2541. * @type {String}
  2542. */
  2543. keyPath: null,
  2544.  
  2545. /**
  2546. * Whether IDBStore uses autoIncrement
  2547. *
  2548. * @type {Boolean}
  2549. */
  2550. autoIncrement: null,
  2551.  
  2552. /**
  2553. * The indexes used by IDBStore
  2554. *
  2555. * @type {Array}
  2556. */
  2557. indexes: null,
  2558.  
  2559. /**
  2560. * The implemantations to try to use, in order of preference
  2561. *
  2562. * @type {Array}
  2563. */
  2564. implementationPreference: null,
  2565.  
  2566. /**
  2567. * The actual implementation being used
  2568. *
  2569. * @type {String}
  2570. */
  2571. implementation: '',
  2572.  
  2573. /**
  2574. * The callback to be called when the store is ready to be used
  2575. *
  2576. * @type {Function}
  2577. */
  2578. onStoreReady: null,
  2579.  
  2580. /**
  2581. * The callback to be called if an error occurred during instantiation
  2582. * of the store
  2583. *
  2584. * @type {Function}
  2585. */
  2586. onError: null,
  2587.  
  2588. /**
  2589. * The internal insertID counter
  2590. *
  2591. * @type {Number}
  2592. * @private
  2593. */
  2594. _insertIdCount: 0,
  2595.  
  2596. /**
  2597. * Opens an IndexedDB; called by the constructor.
  2598. *
  2599. * Will check if versions match and compare provided index configuration
  2600. * with existing ones, and update indexes if necessary.
  2601. *
  2602. * Will call this.onStoreReady() if everything went well and the store
  2603. * is ready to use, and this.onError() is something went wrong.
  2604. *
  2605. * @private
  2606. *
  2607. */
  2608. openDB: function () {
  2609.  
  2610. var openRequest = this.idb.open(this.dbName, this.dbVersion);
  2611. var preventSuccessCallback = false;
  2612.  
  2613. openRequest.onerror = function (errorEvent) {
  2614.  
  2615. if (hasVersionError(errorEvent)) {
  2616. this.onError(new Error('The version number provided is lower than the existing one.'));
  2617. } else {
  2618. var error;
  2619.  
  2620. if (errorEvent.target.error) {
  2621. error = errorEvent.target.error;
  2622. } else {
  2623. var errorMessage = 'IndexedDB unknown error occurred when opening DB ' + this.dbName + ' version ' + this.dbVersion;
  2624. if ('errorCode' in errorEvent.target) {
  2625. errorMessage += ' with error code ' + errorEvent.target.errorCode;
  2626. }
  2627. error = new Error(errorMessage);
  2628. }
  2629.  
  2630. this.onError(error);
  2631. }
  2632. }.bind(this);
  2633.  
  2634. openRequest.onsuccess = function (event) {
  2635.  
  2636. if (preventSuccessCallback) {
  2637. return;
  2638. }
  2639.  
  2640. if (this.db) {
  2641. this.onStoreReady();
  2642. return;
  2643. }
  2644.  
  2645. this.db = event.target.result;
  2646.  
  2647. if (typeof this.db.version == 'string') {
  2648. this.onError(new Error('The IndexedDB implementation in this browser is outdated. Please upgrade your browser.'));
  2649. return;
  2650. }
  2651.  
  2652. if (!this.db.objectStoreNames.contains(this.storeName)) {
  2653. // We should never ever get here.
  2654. // Lets notify the user anyway.
  2655. this.onError(new Error('Object store couldn\'t be created.'));
  2656. return;
  2657. }
  2658.  
  2659. var emptyTransaction = this.db.transaction([this.storeName], this.consts.READ_ONLY);
  2660. this.store = emptyTransaction.objectStore(this.storeName);
  2661.  
  2662. // check indexes
  2663. var existingIndexes = Array.prototype.slice.call(this.getIndexList());
  2664. this.indexes.forEach(function (indexData) {
  2665. var indexName = indexData.name;
  2666.  
  2667. if (!indexName) {
  2668. preventSuccessCallback = true;
  2669. this.onError(new Error('Cannot create index: No index name given.'));
  2670. return;
  2671. }
  2672.  
  2673. this.normalizeIndexData(indexData);
  2674.  
  2675. if (this.hasIndex(indexName)) {
  2676. // check if it complies
  2677. var actualIndex = this.store.index(indexName);
  2678. var complies = this.indexComplies(actualIndex, indexData);
  2679. if (!complies) {
  2680. preventSuccessCallback = true;
  2681. this.onError(new Error('Cannot modify index "' + indexName + '" for current version. Please bump version number to ' + ( this.dbVersion + 1 ) + '.'));
  2682. }
  2683.  
  2684. existingIndexes.splice(existingIndexes.indexOf(indexName), 1);
  2685. } else {
  2686. preventSuccessCallback = true;
  2687. this.onError(new Error('Cannot create new index "' + indexName + '" for current version. Please bump version number to ' + ( this.dbVersion + 1 ) + '.'));
  2688. }
  2689.  
  2690. }, this);
  2691.  
  2692. if (existingIndexes.length) {
  2693. preventSuccessCallback = true;
  2694. this.onError(new Error('Cannot delete index(es) "' + existingIndexes.toString() + '" for current version. Please bump version number to ' + ( this.dbVersion + 1 ) + '.'));
  2695. }
  2696.  
  2697. preventSuccessCallback || this.onStoreReady();
  2698. }.bind(this);
  2699.  
  2700. openRequest.onupgradeneeded = function (/* IDBVersionChangeEvent */ event) {
  2701.  
  2702. this.db = event.target.result;
  2703.  
  2704. if (this.db.objectStoreNames.contains(this.storeName)) {
  2705. this.store = event.target.transaction.objectStore(this.storeName);
  2706. } else {
  2707. var optionalParameters = {autoIncrement: this.autoIncrement};
  2708. if (this.keyPath !== null) {
  2709. optionalParameters.keyPath = this.keyPath;
  2710. }
  2711. this.store = this.db.createObjectStore(this.storeName, optionalParameters);
  2712. }
  2713.  
  2714. var existingIndexes = Array.prototype.slice.call(this.getIndexList());
  2715. this.indexes.forEach(function (indexData) {
  2716. var indexName = indexData.name;
  2717.  
  2718. if (!indexName) {
  2719. preventSuccessCallback = true;
  2720. this.onError(new Error('Cannot create index: No index name given.'));
  2721. }
  2722.  
  2723. this.normalizeIndexData(indexData);
  2724.  
  2725. if (this.hasIndex(indexName)) {
  2726. // check if it complies
  2727. var actualIndex = this.store.index(indexName);
  2728. var complies = this.indexComplies(actualIndex, indexData);
  2729. if (!complies) {
  2730. // index differs, need to delete and re-create
  2731. this.store.deleteIndex(indexName);
  2732. this.store.createIndex(indexName, indexData.keyPath, {
  2733. unique: indexData.unique,
  2734. multiEntry: indexData.multiEntry
  2735. });
  2736. }
  2737.  
  2738. existingIndexes.splice(existingIndexes.indexOf(indexName), 1);
  2739. } else {
  2740. this.store.createIndex(indexName, indexData.keyPath, {
  2741. unique: indexData.unique,
  2742. multiEntry: indexData.multiEntry
  2743. });
  2744. }
  2745.  
  2746. }, this);
  2747.  
  2748. if (existingIndexes.length) {
  2749. existingIndexes.forEach(function (_indexName) {
  2750. this.store.deleteIndex(_indexName);
  2751. }, this);
  2752. }
  2753.  
  2754. }.bind(this);
  2755. },
  2756.  
  2757. /**
  2758. * Deletes the database used for this store if the IDB implementations
  2759. * provides that functionality.
  2760. *
  2761. * @param {Function} [onSuccess] A callback that is called if deletion
  2762. * was successful.
  2763. * @param {Function} [onError] A callback that is called if deletion
  2764. * failed.
  2765. */
  2766. deleteDatabase: function (onSuccess, onError) {
  2767. if (this.idb.deleteDatabase) {
  2768. this.db.close();
  2769. var deleteRequest = this.idb.deleteDatabase(this.dbName);
  2770. deleteRequest.onsuccess = onSuccess;
  2771. deleteRequest.onerror = onError;
  2772. } else {
  2773. onError(new Error('Browser does not support IndexedDB deleteDatabase!'));
  2774. }
  2775. },
  2776.  
  2777. /*********************
  2778. * data manipulation *
  2779. *********************/
  2780.  
  2781. /**
  2782. * Puts an object into the store. If an entry with the given id exists,
  2783. * it will be overwritten. This method has a different signature for inline
  2784. * keys and out-of-line keys; please see the examples below.
  2785. *
  2786. * @param {*} [key] The key to store. This is only needed if IDBWrapper
  2787. * is set to use out-of-line keys. For inline keys - the default scenario -
  2788. * this can be omitted.
  2789. * @param {Object} value The data object to store.
  2790. * @param {Function} [onSuccess] A callback that is called if insertion
  2791. * was successful.
  2792. * @param {Function} [onError] A callback that is called if insertion
  2793. * failed.
  2794. * @returns {IDBTransaction} The transaction used for this operation.
  2795. * @example
  2796. // Storing an object, using inline keys (the default scenario):
  2797. var myCustomer = {
  2798. customerid: 2346223,
  2799. lastname: 'Doe',
  2800. firstname: 'John'
  2801. };
  2802. myCustomerStore.put(myCustomer, mySuccessHandler, myErrorHandler);
  2803. // Note that passing success- and error-handlers is optional.
  2804. * @example
  2805. // Storing an object, using out-of-line keys:
  2806. var myCustomer = {
  2807. lastname: 'Doe',
  2808. firstname: 'John'
  2809. };
  2810. myCustomerStore.put(2346223, myCustomer, mySuccessHandler, myErrorHandler);
  2811. // Note that passing success- and error-handlers is optional.
  2812. */
  2813. put: function (key, value, onSuccess, onError) {
  2814. if (this.keyPath !== null) {
  2815. onError = onSuccess;
  2816. onSuccess = value;
  2817. value = key;
  2818. }
  2819. onError || (onError = defaultErrorHandler);
  2820. onSuccess || (onSuccess = defaultSuccessHandler);
  2821.  
  2822. var hasSuccess = false,
  2823. result = null,
  2824. putRequest;
  2825.  
  2826. var putTransaction = this.db.transaction([this.storeName], this.consts.READ_WRITE);
  2827. putTransaction.oncomplete = function () {
  2828. var callback = hasSuccess ? onSuccess : onError;
  2829. callback(result);
  2830. };
  2831. putTransaction.onabort = onError;
  2832. putTransaction.onerror = onError;
  2833.  
  2834. if (this.keyPath !== null) { // in-line keys
  2835. this._addIdPropertyIfNeeded(value);
  2836. putRequest = putTransaction.objectStore(this.storeName).put(value);
  2837. } else { // out-of-line keys
  2838. putRequest = putTransaction.objectStore(this.storeName).put(value, key);
  2839. }
  2840. putRequest.onsuccess = function (event) {
  2841. hasSuccess = true;
  2842. result = event.target.result;
  2843. };
  2844. putRequest.onerror = onError;
  2845.  
  2846. return putTransaction;
  2847. },
  2848.  
  2849. /**
  2850. * Retrieves an object from the store. If no entry exists with the given id,
  2851. * the success handler will be called with null as first and only argument.
  2852. *
  2853. * @param {*} key The id of the object to fetch.
  2854. * @param {Function} [onSuccess] A callback that is called if fetching
  2855. * was successful. Will receive the object as only argument.
  2856. * @param {Function} [onError] A callback that will be called if an error
  2857. * occurred during the operation.
  2858. * @returns {IDBTransaction} The transaction used for this operation.
  2859. */
  2860. get: function (key, onSuccess, onError) {
  2861. onError || (onError = defaultErrorHandler);
  2862. onSuccess || (onSuccess = defaultSuccessHandler);
  2863.  
  2864. var hasSuccess = false,
  2865. result = null;
  2866.  
  2867. var getTransaction = this.db.transaction([this.storeName], this.consts.READ_ONLY);
  2868. getTransaction.oncomplete = function () {
  2869. var callback = hasSuccess ? onSuccess : onError;
  2870. callback(result);
  2871. };
  2872. getTransaction.onabort = onError;
  2873. getTransaction.onerror = onError;
  2874. var getRequest = getTransaction.objectStore(this.storeName).get(key);
  2875. getRequest.onsuccess = function (event) {
  2876. hasSuccess = true;
  2877. result = event.target.result;
  2878. };
  2879. getRequest.onerror = onError;
  2880.  
  2881. return getTransaction;
  2882. },
  2883.  
  2884. /**
  2885. * Removes an object from the store.
  2886. *
  2887. * @param {*} key The id of the object to remove.
  2888. * @param {Function} [onSuccess] A callback that is called if the removal
  2889. * was successful.
  2890. * @param {Function} [onError] A callback that will be called if an error
  2891. * occurred during the operation.
  2892. * @returns {IDBTransaction} The transaction used for this operation.
  2893. */
  2894. remove: function (key, onSuccess, onError) {
  2895. onError || (onError = defaultErrorHandler);
  2896. onSuccess || (onSuccess = defaultSuccessHandler);
  2897.  
  2898. var hasSuccess = false,
  2899. result = null;
  2900.  
  2901. var removeTransaction = this.db.transaction([this.storeName], this.consts.READ_WRITE);
  2902. removeTransaction.oncomplete = function () {
  2903. var callback = hasSuccess ? onSuccess : onError;
  2904. callback(result);
  2905. };
  2906. removeTransaction.onabort = onError;
  2907. removeTransaction.onerror = onError;
  2908.  
  2909. var deleteRequest = removeTransaction.objectStore(this.storeName)['delete'](key);
  2910. deleteRequest.onsuccess = function (event) {
  2911. hasSuccess = true;
  2912. result = event.target.result;
  2913. };
  2914. deleteRequest.onerror = onError;
  2915.  
  2916. return removeTransaction;
  2917. },
  2918.  
  2919. /**
  2920. * Runs a batch of put and/or remove operations on the store.
  2921. *
  2922. * @param {Array} dataArray An array of objects containing the operation to run
  2923. * and the data object (for put operations).
  2924. * @param {Function} [onSuccess] A callback that is called if all operations
  2925. * were successful.
  2926. * @param {Function} [onError] A callback that is called if an error
  2927. * occurred during one of the operations.
  2928. * @returns {IDBTransaction} The transaction used for this operation.
  2929. */
  2930. batch: function (dataArray, onSuccess, onError) {
  2931. onError || (onError = defaultErrorHandler);
  2932. onSuccess || (onSuccess = defaultSuccessHandler);
  2933.  
  2934. if (Object.prototype.toString.call(dataArray) != '[object Array]') {
  2935. onError(new Error('dataArray argument must be of type Array.'));
  2936. } else if (dataArray.length === 0) {
  2937. return onSuccess(true);
  2938. }
  2939.  
  2940. var count = dataArray.length;
  2941. var called = false;
  2942. var hasSuccess = false;
  2943.  
  2944. var batchTransaction = this.db.transaction([this.storeName], this.consts.READ_WRITE);
  2945. batchTransaction.oncomplete = function () {
  2946. var callback = hasSuccess ? onSuccess : onError;
  2947. callback(hasSuccess);
  2948. };
  2949. batchTransaction.onabort = onError;
  2950. batchTransaction.onerror = onError;
  2951.  
  2952.  
  2953. var onItemSuccess = function () {
  2954. count--;
  2955. if (count === 0 && !called) {
  2956. called = true;
  2957. hasSuccess = true;
  2958. }
  2959. };
  2960.  
  2961. dataArray.forEach(function (operation) {
  2962. var type = operation.type;
  2963. var key = operation.key;
  2964. var value = operation.value;
  2965.  
  2966. var onItemError = function (err) {
  2967. batchTransaction.abort();
  2968. if (!called) {
  2969. called = true;
  2970. onError(err, type, key);
  2971. }
  2972. };
  2973.  
  2974. if (type == 'remove') {
  2975. var deleteRequest = batchTransaction.objectStore(this.storeName)['delete'](key);
  2976. deleteRequest.onsuccess = onItemSuccess;
  2977. deleteRequest.onerror = onItemError;
  2978. } else if (type == 'put') {
  2979. var putRequest;
  2980. if (this.keyPath !== null) { // in-line keys
  2981. this._addIdPropertyIfNeeded(value);
  2982. putRequest = batchTransaction.objectStore(this.storeName).put(value);
  2983. } else { // out-of-line keys
  2984. putRequest = batchTransaction.objectStore(this.storeName).put(value, key);
  2985. }
  2986. putRequest.onsuccess = onItemSuccess;
  2987. putRequest.onerror = onItemError;
  2988. }
  2989. }, this);
  2990.  
  2991. return batchTransaction;
  2992. },
  2993.  
  2994. /**
  2995. * Takes an array of objects and stores them in a single transaction.
  2996. *
  2997. * @param {Array} dataArray An array of objects to store
  2998. * @param {Function} [onSuccess] A callback that is called if all operations
  2999. * were successful.
  3000. * @param {Function} [onError] A callback that is called if an error
  3001. * occurred during one of the operations.
  3002. * @returns {IDBTransaction} The transaction used for this operation.
  3003. */
  3004. putBatch: function (dataArray, onSuccess, onError) {
  3005. var batchData = dataArray.map(function (item) {
  3006. return {type: 'put', value: item};
  3007. });
  3008.  
  3009. return this.batch(batchData, onSuccess, onError);
  3010. },
  3011.  
  3012. /**
  3013. * Like putBatch, takes an array of objects and stores them in a single
  3014. * transaction, but allows processing of the result values. Returns the
  3015. * processed records containing the key for newly created records to the
  3016. * onSuccess calllback instead of only returning true or false for success.
  3017. * In addition, added the option for the caller to specify a key field that
  3018. * should be set to the newly created key.
  3019. *
  3020. * @param {Array} dataArray An array of objects to store
  3021. * @param {Object} [options] An object containing optional options
  3022. * @param {String} [options.keyField=this.keyPath] Specifies a field in the record to update
  3023. * with the auto-incrementing key. Defaults to the store's keyPath.
  3024. * @param {Function} [onSuccess] A callback that is called if all operations
  3025. * were successful.
  3026. * @param {Function} [onError] A callback that is called if an error
  3027. * occurred during one of the operations.
  3028. * @returns {IDBTransaction} The transaction used for this operation.
  3029. *
  3030. */
  3031. upsertBatch: function (dataArray, options, onSuccess, onError) {
  3032. // handle `dataArray, onSuccess, onError` signature
  3033. if (typeof options == 'function') {
  3034. onSuccess = options;
  3035. onError = onSuccess;
  3036. options = {};
  3037. }
  3038.  
  3039. onError || (onError = defaultErrorHandler);
  3040. onSuccess || (onSuccess = defaultSuccessHandler);
  3041. options || (options = {});
  3042.  
  3043. if (Object.prototype.toString.call(dataArray) != '[object Array]') {
  3044. onError(new Error('dataArray argument must be of type Array.'));
  3045. }
  3046.  
  3047. var keyField = options.keyField || this.keyPath;
  3048. var count = dataArray.length;
  3049. var called = false;
  3050. var hasSuccess = false;
  3051. var index = 0; // assume success callbacks are executed in order
  3052.  
  3053. var batchTransaction = this.db.transaction([this.storeName], this.consts.READ_WRITE);
  3054. batchTransaction.oncomplete = function () {
  3055. if (hasSuccess) {
  3056. onSuccess(dataArray);
  3057. } else {
  3058. onError(false);
  3059. }
  3060. };
  3061. batchTransaction.onabort = onError;
  3062. batchTransaction.onerror = onError;
  3063.  
  3064. var onItemSuccess = function (event) {
  3065. var record = dataArray[index++];
  3066. record[keyField] = event.target.result;
  3067.  
  3068. count--;
  3069. if (count === 0 && !called) {
  3070. called = true;
  3071. hasSuccess = true;
  3072. }
  3073. };
  3074.  
  3075. dataArray.forEach(function (record) {
  3076. var key = record.key;
  3077.  
  3078. var onItemError = function (err) {
  3079. batchTransaction.abort();
  3080. if (!called) {
  3081. called = true;
  3082. onError(err);
  3083. }
  3084. };
  3085.  
  3086. var putRequest;
  3087. if (this.keyPath !== null) { // in-line keys
  3088. this._addIdPropertyIfNeeded(record);
  3089. putRequest = batchTransaction.objectStore(this.storeName).put(record);
  3090. } else { // out-of-line keys
  3091. putRequest = batchTransaction.objectStore(this.storeName).put(record, key);
  3092. }
  3093. putRequest.onsuccess = onItemSuccess;
  3094. putRequest.onerror = onItemError;
  3095. }, this);
  3096.  
  3097. return batchTransaction;
  3098. },
  3099.  
  3100. /**
  3101. * Takes an array of keys and removes matching objects in a single
  3102. * transaction.
  3103. *
  3104. * @param {Array} keyArray An array of keys to remove
  3105. * @param {Function} [onSuccess] A callback that is called if all operations
  3106. * were successful.
  3107. * @param {Function} [onError] A callback that is called if an error
  3108. * occurred during one of the operations.
  3109. * @returns {IDBTransaction} The transaction used for this operation.
  3110. */
  3111. removeBatch: function (keyArray, onSuccess, onError) {
  3112. var batchData = keyArray.map(function (key) {
  3113. return {type: 'remove', key: key};
  3114. });
  3115.  
  3116. return this.batch(batchData, onSuccess, onError);
  3117. },
  3118.  
  3119. /**
  3120. * Takes an array of keys and fetches matching objects
  3121. *
  3122. * @param {Array} keyArray An array of keys identifying the objects to fetch
  3123. * @param {Function} [onSuccess] A callback that is called if all operations
  3124. * were successful.
  3125. * @param {Function} [onError] A callback that is called if an error
  3126. * occurred during one of the operations.
  3127. * @param {String} [arrayType='sparse'] The type of array to pass to the
  3128. * success handler. May be one of 'sparse', 'dense' or 'skip'. Defaults to
  3129. * 'sparse'. This parameter specifies how to handle the situation if a get
  3130. * operation did not throw an error, but there was no matching object in
  3131. * the database. In most cases, 'sparse' provides the most desired
  3132. * behavior. See the examples for details.
  3133. * @returns {IDBTransaction} The transaction used for this operation.
  3134. * @example
  3135. // given that there are two objects in the database with the keypath
  3136. // values 1 and 2, and the call looks like this:
  3137. myStore.getBatch([1, 5, 2], onError, function (data) { … }, arrayType);
  3138.  
  3139. // this is what the `data` array will be like:
  3140.  
  3141. // arrayType == 'sparse':
  3142. // data is a sparse array containing two entries and having a length of 3:
  3143. [Object, 2: Object]
  3144. 0: Object
  3145. 2: Object
  3146. length: 3
  3147. // calling forEach on data will result in the callback being called two
  3148. // times, with the index parameter matching the index of the key in the
  3149. // keyArray.
  3150.  
  3151. // arrayType == 'dense':
  3152. // data is a dense array containing three entries and having a length of 3,
  3153. // where data[1] is of type undefined:
  3154. [Object, undefined, Object]
  3155. 0: Object
  3156. 1: undefined
  3157. 2: Object
  3158. length: 3
  3159. // calling forEach on data will result in the callback being called three
  3160. // times, with the index parameter matching the index of the key in the
  3161. // keyArray, but the second call will have undefined as first argument.
  3162.  
  3163. // arrayType == 'skip':
  3164. // data is a dense array containing two entries and having a length of 2:
  3165. [Object, Object]
  3166. 0: Object
  3167. 1: Object
  3168. length: 2
  3169. // calling forEach on data will result in the callback being called two
  3170. // times, with the index parameter not matching the index of the key in the
  3171. // keyArray.
  3172. */
  3173. getBatch: function (keyArray, onSuccess, onError, arrayType) {
  3174. onError || (onError = defaultErrorHandler);
  3175. onSuccess || (onSuccess = defaultSuccessHandler);
  3176. arrayType || (arrayType = 'sparse');
  3177.  
  3178. if (Object.prototype.toString.call(keyArray) != '[object Array]') {
  3179. onError(new Error('keyArray argument must be of type Array.'));
  3180. } else if (keyArray.length === 0) {
  3181. return onSuccess([]);
  3182. }
  3183.  
  3184. var data = [];
  3185. var count = keyArray.length;
  3186. var called = false;
  3187. var hasSuccess = false;
  3188. var result = null;
  3189.  
  3190. var batchTransaction = this.db.transaction([this.storeName], this.consts.READ_ONLY);
  3191. batchTransaction.oncomplete = function () {
  3192. var callback = hasSuccess ? onSuccess : onError;
  3193. callback(result);
  3194. };
  3195. batchTransaction.onabort = onError;
  3196. batchTransaction.onerror = onError;
  3197.  
  3198. var onItemSuccess = function (event) {
  3199. if (event.target.result || arrayType == 'dense') {
  3200. data.push(event.target.result);
  3201. } else if (arrayType == 'sparse') {
  3202. data.length++;
  3203. }
  3204. count--;
  3205. if (count === 0) {
  3206. called = true;
  3207. hasSuccess = true;
  3208. result = data;
  3209. }
  3210. };
  3211.  
  3212. keyArray.forEach(function (key) {
  3213.  
  3214. var onItemError = function (err) {
  3215. called = true;
  3216. result = err;
  3217. onError(err);
  3218. batchTransaction.abort();
  3219. };
  3220.  
  3221. var getRequest = batchTransaction.objectStore(this.storeName).get(key);
  3222. getRequest.onsuccess = onItemSuccess;
  3223. getRequest.onerror = onItemError;
  3224.  
  3225. }, this);
  3226.  
  3227. return batchTransaction;
  3228. },
  3229.  
  3230. /**
  3231. * Fetches all entries in the store.
  3232. *
  3233. * @param {Function} [onSuccess] A callback that is called if the operation
  3234. * was successful. Will receive an array of objects.
  3235. * @param {Function} [onError] A callback that will be called if an error
  3236. * occurred during the operation.
  3237. * @returns {IDBTransaction} The transaction used for this operation.
  3238. */
  3239. getAll: function (onSuccess, onError) {
  3240. onError || (onError = defaultErrorHandler);
  3241. onSuccess || (onSuccess = defaultSuccessHandler);
  3242. var getAllTransaction = this.db.transaction([this.storeName], this.consts.READ_ONLY);
  3243. var store = getAllTransaction.objectStore(this.storeName);
  3244. if (store.getAll) {
  3245. this._getAllNative(getAllTransaction, store, onSuccess, onError);
  3246. } else {
  3247. this._getAllCursor(getAllTransaction, store, onSuccess, onError);
  3248. }
  3249.  
  3250. return getAllTransaction;
  3251. },
  3252.  
  3253. /**
  3254. * Implements getAll for IDB implementations that have a non-standard
  3255. * getAll() method.
  3256. *
  3257. * @param {IDBTransaction} getAllTransaction An open READ transaction.
  3258. * @param {IDBObjectStore} store A reference to the store.
  3259. * @param {Function} onSuccess A callback that will be called if the
  3260. * operation was successful.
  3261. * @param {Function} onError A callback that will be called if an
  3262. * error occurred during the operation.
  3263. * @private
  3264. */
  3265. _getAllNative: function (getAllTransaction, store, onSuccess, onError) {
  3266. var hasSuccess = false,
  3267. result = null;
  3268.  
  3269. getAllTransaction.oncomplete = function () {
  3270. var callback = hasSuccess ? onSuccess : onError;
  3271. callback(result);
  3272. };
  3273. getAllTransaction.onabort = onError;
  3274. getAllTransaction.onerror = onError;
  3275.  
  3276. var getAllRequest = store.getAll();
  3277. getAllRequest.onsuccess = function (event) {
  3278. hasSuccess = true;
  3279. result = event.target.result;
  3280. };
  3281. getAllRequest.onerror = onError;
  3282. },
  3283.  
  3284. /**
  3285. * Implements getAll for IDB implementations that do not have a getAll()
  3286. * method.
  3287. *
  3288. * @param {IDBTransaction} getAllTransaction An open READ transaction.
  3289. * @param {IDBObjectStore} store A reference to the store.
  3290. * @param {Function} onSuccess A callback that will be called if the
  3291. * operation was successful.
  3292. * @param {Function} onError A callback that will be called if an
  3293. * error occurred during the operation.
  3294. * @private
  3295. */
  3296. _getAllCursor: function (getAllTransaction, store, onSuccess, onError) {
  3297. var all = [],
  3298. hasSuccess = false,
  3299. result = null;
  3300.  
  3301. getAllTransaction.oncomplete = function () {
  3302. var callback = hasSuccess ? onSuccess : onError;
  3303. callback(result);
  3304. };
  3305. getAllTransaction.onabort = onError;
  3306. getAllTransaction.onerror = onError;
  3307.  
  3308. var cursorRequest = store.openCursor();
  3309. cursorRequest.onsuccess = function (event) {
  3310. var cursor = event.target.result;
  3311. if (cursor) {
  3312. all.push(cursor.value);
  3313. cursor['continue']();
  3314. }
  3315. else {
  3316. hasSuccess = true;
  3317. result = all;
  3318. }
  3319. };
  3320. cursorRequest.onError = onError;
  3321. },
  3322.  
  3323. /**
  3324. * Clears the store, i.e. deletes all entries in the store.
  3325. *
  3326. * @param {Function} [onSuccess] A callback that will be called if the
  3327. * operation was successful.
  3328. * @param {Function} [onError] A callback that will be called if an
  3329. * error occurred during the operation.
  3330. * @returns {IDBTransaction} The transaction used for this operation.
  3331. */
  3332. clear: function (onSuccess, onError) {
  3333. onError || (onError = defaultErrorHandler);
  3334. onSuccess || (onSuccess = defaultSuccessHandler);
  3335.  
  3336. var hasSuccess = false,
  3337. result = null;
  3338.  
  3339. var clearTransaction = this.db.transaction([this.storeName], this.consts.READ_WRITE);
  3340. clearTransaction.oncomplete = function () {
  3341. var callback = hasSuccess ? onSuccess : onError;
  3342. callback(result);
  3343. };
  3344. clearTransaction.onabort = onError;
  3345. clearTransaction.onerror = onError;
  3346.  
  3347. var clearRequest = clearTransaction.objectStore(this.storeName).clear();
  3348. clearRequest.onsuccess = function (event) {
  3349. hasSuccess = true;
  3350. result = event.target.result;
  3351. };
  3352. clearRequest.onerror = onError;
  3353.  
  3354. return clearTransaction;
  3355. },
  3356.  
  3357. /**
  3358. * Checks if an id property needs to present on a object and adds one if
  3359. * necessary.
  3360. *
  3361. * @param {Object} dataObj The data object that is about to be stored
  3362. * @private
  3363. */
  3364. _addIdPropertyIfNeeded: function (dataObj) {
  3365. if (typeof dataObj[this.keyPath] == 'undefined') {
  3366. dataObj[this.keyPath] = this._insertIdCount++ + Date.now();
  3367. }
  3368. },
  3369.  
  3370. /************
  3371. * indexing *
  3372. ************/
  3373.  
  3374. /**
  3375. * Returns a DOMStringList of index names of the store.
  3376. *
  3377. * @return {DOMStringList} The list of index names
  3378. */
  3379. getIndexList: function () {
  3380. return this.store.indexNames;
  3381. },
  3382.  
  3383. /**
  3384. * Checks if an index with the given name exists in the store.
  3385. *
  3386. * @param {String} indexName The name of the index to look for
  3387. * @return {Boolean} Whether the store contains an index with the given name
  3388. */
  3389. hasIndex: function (indexName) {
  3390. return this.store.indexNames.contains(indexName);
  3391. },
  3392.  
  3393. /**
  3394. * Normalizes an object containing index data and assures that all
  3395. * properties are set.
  3396. *
  3397. * @param {Object} indexData The index data object to normalize
  3398. * @param {String} indexData.name The name of the index
  3399. * @param {String} [indexData.keyPath] The key path of the index
  3400. * @param {Boolean} [indexData.unique] Whether the index is unique
  3401. * @param {Boolean} [indexData.multiEntry] Whether the index is multi entry
  3402. */
  3403. normalizeIndexData: function (indexData) {
  3404. indexData.keyPath = indexData.keyPath || indexData.name;
  3405. indexData.unique = !!indexData.unique;
  3406. indexData.multiEntry = !!indexData.multiEntry;
  3407. },
  3408.  
  3409. /**
  3410. * Checks if an actual index complies with an expected index.
  3411. *
  3412. * @param {IDBIndex} actual The actual index found in the store
  3413. * @param {Object} expected An Object describing an expected index
  3414. * @return {Boolean} Whether both index definitions are identical
  3415. */
  3416. indexComplies: function (actual, expected) {
  3417. var complies = ['keyPath', 'unique', 'multiEntry'].every(function (key) {
  3418. // IE10 returns undefined for no multiEntry
  3419. if (key == 'multiEntry' && actual[key] === undefined && expected[key] === false) {
  3420. return true;
  3421. }
  3422. // Compound keys
  3423. if (key == 'keyPath' && Object.prototype.toString.call(expected[key]) == '[object Array]') {
  3424. var exp = expected.keyPath;
  3425. var act = actual.keyPath;
  3426.  
  3427. // IE10 can't handle keyPath sequences and stores them as a string.
  3428. // The index will be unusable there, but let's still return true if
  3429. // the keyPath sequence matches.
  3430. if (typeof act == 'string') {
  3431. return exp.toString() == act;
  3432. }
  3433.  
  3434. // Chrome/Opera stores keyPath squences as DOMStringList, Firefox
  3435. // as Array
  3436. if (!(typeof act.contains == 'function' || typeof act.indexOf == 'function')) {
  3437. return false;
  3438. }
  3439.  
  3440. if (act.length !== exp.length) {
  3441. return false;
  3442. }
  3443.  
  3444. for (var i = 0, m = exp.length; i < m; i++) {
  3445. if (!( (act.contains && act.contains(exp[i])) || act.indexOf(exp[i] !== -1) )) {
  3446. return false;
  3447. }
  3448. }
  3449. return true;
  3450. }
  3451. return expected[key] == actual[key];
  3452. });
  3453. return complies;
  3454. },
  3455.  
  3456. /**********
  3457. * cursor *
  3458. **********/
  3459.  
  3460. /**
  3461. * Iterates over the store using the given options and calling onItem
  3462. * for each entry matching the options.
  3463. *
  3464. * @param {Function} onItem A callback to be called for each match
  3465. * @param {Object} [options] An object defining specific options
  3466. * @param {String} [options.index=null] A name of an IDBIndex to operate on
  3467. * @param {String} [options.order=ASC] The order in which to provide the
  3468. * results, can be 'DESC' or 'ASC'
  3469. * @param {Boolean} [options.autoContinue=true] Whether to automatically
  3470. * iterate the cursor to the next result
  3471. * @param {Boolean} [options.filterDuplicates=false] Whether to exclude
  3472. * duplicate matches
  3473. * @param {IDBKeyRange} [options.keyRange=null] An IDBKeyRange to use
  3474. * @param {Boolean} [options.writeAccess=false] Whether grant write access
  3475. * to the store in the onItem callback
  3476. * @param {Function} [options.onEnd=null] A callback to be called after
  3477. * iteration has ended
  3478. * @param {Function} [options.onError=throw] A callback to be called
  3479. * if an error occurred during the operation.
  3480. * @param {Number} [options.limit=Infinity] Limit the number of returned
  3481. * results to this number
  3482. * @param {Number} [options.offset=0] Skip the provided number of results
  3483. * in the resultset
  3484. * @param {Boolean} [options.allowItemRejection=false] Allows the onItem
  3485. * function to return a Boolean to accept or reject the current item
  3486. * @returns {IDBTransaction} The transaction used for this operation.
  3487. */
  3488. iterate: function (onItem, options) {
  3489. options = mixin({
  3490. index: null,
  3491. order: 'ASC',
  3492. autoContinue: true,
  3493. filterDuplicates: false,
  3494. keyRange: null,
  3495. writeAccess: false,
  3496. onEnd: null,
  3497. onError: defaultErrorHandler,
  3498. limit: Infinity,
  3499. offset: 0,
  3500. allowItemRejection: false
  3501. }, options || {});
  3502.  
  3503. var directionType = options.order.toLowerCase() == 'desc' ? 'PREV' : 'NEXT';
  3504. if (options.filterDuplicates) {
  3505. directionType += '_NO_DUPLICATE';
  3506. }
  3507.  
  3508. var hasSuccess = false;
  3509. var cursorTransaction = this.db.transaction([this.storeName], this.consts[options.writeAccess ? 'READ_WRITE' : 'READ_ONLY']);
  3510. var cursorTarget = cursorTransaction.objectStore(this.storeName);
  3511. if (options.index) {
  3512. cursorTarget = cursorTarget.index(options.index);
  3513. }
  3514. var recordCount = 0;
  3515.  
  3516. cursorTransaction.oncomplete = function () {
  3517. if (!hasSuccess) {
  3518. options.onError(null);
  3519. return;
  3520. }
  3521. if (options.onEnd) {
  3522. options.onEnd();
  3523. } else {
  3524. onItem(null);
  3525. }
  3526. };
  3527. cursorTransaction.onabort = options.onError;
  3528. cursorTransaction.onerror = options.onError;
  3529.  
  3530. var cursorRequest = cursorTarget.openCursor(options.keyRange, this.consts[directionType]);
  3531. cursorRequest.onerror = options.onError;
  3532. cursorRequest.onsuccess = function (event) {
  3533. var cursor = event.target.result;
  3534. if (cursor) {
  3535. if (options.offset) {
  3536. cursor.advance(options.offset);
  3537. options.offset = 0;
  3538. } else {
  3539. var onItemReturn = onItem(cursor.value, cursor, cursorTransaction);
  3540. if (!options.allowItemRejection || onItemReturn !== false) {
  3541. recordCount++;
  3542. }
  3543. if (options.autoContinue) {
  3544. if (recordCount + options.offset < options.limit) {
  3545. cursor['continue']();
  3546. } else {
  3547. hasSuccess = true;
  3548. }
  3549. }
  3550. }
  3551. } else {
  3552. hasSuccess = true;
  3553. }
  3554. };
  3555.  
  3556. return cursorTransaction;
  3557. },
  3558.  
  3559. /**
  3560. * Runs a query against the store and passes an array containing matched
  3561. * objects to the success handler.
  3562. *
  3563. * @param {Function} onSuccess A callback to be called when the operation
  3564. * was successful.
  3565. * @param {Object} [options] An object defining specific options
  3566. * @param {String} [options.index=null] A name of an IDBIndex to operate on
  3567. * @param {String} [options.order=ASC] The order in which to provide the
  3568. * results, can be 'DESC' or 'ASC'
  3569. * @param {Boolean} [options.filterDuplicates=false] Whether to exclude
  3570. * duplicate matches
  3571. * @param {IDBKeyRange} [options.keyRange=null] An IDBKeyRange to use
  3572. * @param {Function} [options.onError=throw] A callback to be called
  3573. * if an error occurred during the operation.
  3574. * @param {Number} [options.limit=Infinity] Limit the number of returned
  3575. * results to this number
  3576. * @param {Number} [options.offset=0] Skip the provided number of results
  3577. * in the resultset
  3578. * @param {Function} [options.filter=null] A custom filter function to
  3579. * apply to query resuts before returning. Must return `false` to reject
  3580. * an item. Can be combined with keyRanges.
  3581. * @returns {IDBTransaction} The transaction used for this operation.
  3582. */
  3583. query: function (onSuccess, options) {
  3584. var result = [],
  3585. processedItems = 0;
  3586. options = options || {};
  3587. options.autoContinue = true;
  3588. options.writeAccess = false;
  3589. options.allowItemRejection = !!options.filter;
  3590. options.onEnd = function () {
  3591. onSuccess(result, processedItems);
  3592. };
  3593. return this.iterate(function (item) {
  3594. processedItems++;
  3595. var accept = options.filter ? options.filter(item) : true;
  3596. if (accept !== false) {
  3597. result.push(item);
  3598. }
  3599. return accept;
  3600. }, options);
  3601. },
  3602.  
  3603. /**
  3604. *
  3605. * Runs a query against the store, but only returns the number of matches
  3606. * instead of the matches itself.
  3607. *
  3608. * @param {Function} onSuccess A callback to be called if the opration
  3609. * was successful.
  3610. * @param {Object} [options] An object defining specific options
  3611. * @param {String} [options.index=null] A name of an IDBIndex to operate on
  3612. * @param {IDBKeyRange} [options.keyRange=null] An IDBKeyRange to use
  3613. * @param {Function} [options.onError=throw] A callback to be called if an error
  3614. * occurred during the operation.
  3615. * @returns {IDBTransaction} The transaction used for this operation.
  3616. */
  3617. count: function (onSuccess, options) {
  3618.  
  3619. options = mixin({
  3620. index: null,
  3621. keyRange: null
  3622. }, options || {});
  3623.  
  3624. var onError = options.onError || defaultErrorHandler;
  3625.  
  3626. var hasSuccess = false,
  3627. result = null;
  3628.  
  3629. var cursorTransaction = this.db.transaction([this.storeName], this.consts.READ_ONLY);
  3630. cursorTransaction.oncomplete = function () {
  3631. var callback = hasSuccess ? onSuccess : onError;
  3632. callback(result);
  3633. };
  3634. cursorTransaction.onabort = onError;
  3635. cursorTransaction.onerror = onError;
  3636.  
  3637. var cursorTarget = cursorTransaction.objectStore(this.storeName);
  3638. if (options.index) {
  3639. cursorTarget = cursorTarget.index(options.index);
  3640. }
  3641. var countRequest = cursorTarget.count(options.keyRange);
  3642. countRequest.onsuccess = function (evt) {
  3643. hasSuccess = true;
  3644. result = evt.target.result;
  3645. };
  3646. countRequest.onError = onError;
  3647.  
  3648. return cursorTransaction;
  3649. },
  3650.  
  3651. /**************/
  3652. /* key ranges */
  3653. /**************/
  3654.  
  3655. /**
  3656. * Creates a key range using specified options. This key range can be
  3657. * handed over to the count() and iterate() methods.
  3658. *
  3659. * Note: You must provide at least one or both of "lower" or "upper" value.
  3660. *
  3661. * @param {Object} options The options for the key range to create
  3662. * @param {*} [options.lower] The lower bound
  3663. * @param {Boolean} [options.excludeLower] Whether to exclude the lower
  3664. * bound passed in options.lower from the key range
  3665. * @param {*} [options.upper] The upper bound
  3666. * @param {Boolean} [options.excludeUpper] Whether to exclude the upper
  3667. * bound passed in options.upper from the key range
  3668. * @param {*} [options.only] A single key value. Use this if you need a key
  3669. * range that only includes one value for a key. Providing this
  3670. * property invalidates all other properties.
  3671. * @return {IDBKeyRange} The IDBKeyRange representing the specified options
  3672. */
  3673. makeKeyRange: function (options) {
  3674. /*jshint onecase:true */
  3675. var keyRange,
  3676. hasLower = typeof options.lower != 'undefined',
  3677. hasUpper = typeof options.upper != 'undefined',
  3678. isOnly = typeof options.only != 'undefined';
  3679.  
  3680. switch (true) {
  3681. case isOnly:
  3682. keyRange = this.keyRange.only(options.only);
  3683. break;
  3684. case hasLower && hasUpper:
  3685. keyRange = this.keyRange.bound(options.lower, options.upper, options.excludeLower, options.excludeUpper);
  3686. break;
  3687. case hasLower:
  3688. keyRange = this.keyRange.lowerBound(options.lower, options.excludeLower);
  3689. break;
  3690. case hasUpper:
  3691. keyRange = this.keyRange.upperBound(options.upper, options.excludeUpper);
  3692. break;
  3693. default:
  3694. throw new Error('Cannot create KeyRange. Provide one or both of "lower" or "upper" value, or an "only" value.');
  3695. }
  3696.  
  3697. return keyRange;
  3698.  
  3699. }
  3700.  
  3701. };
  3702.  
  3703. /** helpers **/
  3704. var empty = {};
  3705.  
  3706. function mixin (target, source) {
  3707. var name, s;
  3708. for (name in source) {
  3709. s = source[name];
  3710. if (s !== empty[name] && s !== target[name]) {
  3711. target[name] = s;
  3712. }
  3713. }
  3714. return target;
  3715. }
  3716.  
  3717. function hasVersionError(errorEvent) {
  3718. if ('error' in errorEvent.target) {
  3719. return errorEvent.target.error.name == 'VersionError';
  3720. } else if ('errorCode' in errorEvent.target) {
  3721. return errorEvent.target.errorCode == 12;
  3722. }
  3723. return false;
  3724. }
  3725.  
  3726. IDBStore.prototype = proto;
  3727. IDBStore.version = proto.version;
  3728.  
  3729. return IDBStore;
  3730.  
  3731. }, this);
  3732.  
  3733. },{}],8:[function(require,module,exports){
  3734. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  3735. var e, m
  3736. var eLen = nBytes * 8 - mLen - 1
  3737. var eMax = (1 << eLen) - 1
  3738. var eBias = eMax >> 1
  3739. var nBits = -7
  3740. var i = isLE ? (nBytes - 1) : 0
  3741. var d = isLE ? -1 : 1
  3742. var s = buffer[offset + i]
  3743.  
  3744. i += d
  3745.  
  3746. e = s & ((1 << (-nBits)) - 1)
  3747. s >>= (-nBits)
  3748. nBits += eLen
  3749. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  3750.  
  3751. m = e & ((1 << (-nBits)) - 1)
  3752. e >>= (-nBits)
  3753. nBits += mLen
  3754. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  3755.  
  3756. if (e === 0) {
  3757. e = 1 - eBias
  3758. } else if (e === eMax) {
  3759. return m ? NaN : ((s ? -1 : 1) * Infinity)
  3760. } else {
  3761. m = m + Math.pow(2, mLen)
  3762. e = e - eBias
  3763. }
  3764. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  3765. }
  3766.  
  3767. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  3768. var e, m, c
  3769. var eLen = nBytes * 8 - mLen - 1
  3770. var eMax = (1 << eLen) - 1
  3771. var eBias = eMax >> 1
  3772. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  3773. var i = isLE ? 0 : (nBytes - 1)
  3774. var d = isLE ? 1 : -1
  3775. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  3776.  
  3777. value = Math.abs(value)
  3778.  
  3779. if (isNaN(value) || value === Infinity) {
  3780. m = isNaN(value) ? 1 : 0
  3781. e = eMax
  3782. } else {
  3783. e = Math.floor(Math.log(value) / Math.LN2)
  3784. if (value * (c = Math.pow(2, -e)) < 1) {
  3785. e--
  3786. c *= 2
  3787. }
  3788. if (e + eBias >= 1) {
  3789. value += rt / c
  3790. } else {
  3791. value += rt * Math.pow(2, 1 - eBias)
  3792. }
  3793. if (value * c >= 2) {
  3794. e++
  3795. c /= 2
  3796. }
  3797.  
  3798. if (e + eBias >= eMax) {
  3799. m = 0
  3800. e = eMax
  3801. } else if (e + eBias >= 1) {
  3802. m = (value * c - 1) * Math.pow(2, mLen)
  3803. e = e + eBias
  3804. } else {
  3805. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  3806. e = 0
  3807. }
  3808. }
  3809.  
  3810. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  3811.  
  3812. e = (e << mLen) | m
  3813. eLen += mLen
  3814. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  3815.  
  3816. buffer[offset + i - d] |= s * 128
  3817. }
  3818.  
  3819. },{}],9:[function(require,module,exports){
  3820. if (typeof Object.create === 'function') {
  3821. // implementation from standard node.js 'util' module
  3822. module.exports = function inherits(ctor, superCtor) {
  3823. ctor.super_ = superCtor
  3824. ctor.prototype = Object.create(superCtor.prototype, {
  3825. constructor: {
  3826. value: ctor,
  3827. enumerable: false,
  3828. writable: true,
  3829. configurable: true
  3830. }
  3831. });
  3832. };
  3833. } else {
  3834. // old school shim for old browsers
  3835. module.exports = function inherits(ctor, superCtor) {
  3836. ctor.super_ = superCtor
  3837. var TempCtor = function () {}
  3838. TempCtor.prototype = superCtor.prototype
  3839. ctor.prototype = new TempCtor()
  3840. ctor.prototype.constructor = ctor
  3841. }
  3842. }
  3843.  
  3844. },{}],10:[function(require,module,exports){
  3845. /*!
  3846. * Determine if an object is a Buffer
  3847. *
  3848. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  3849. * @license MIT
  3850. */
  3851.  
  3852. // The _isBuffer check is for Safari 5-7 support, because it's missing
  3853. // Object.prototype.constructor. Remove this eventually
  3854. module.exports = function (obj) {
  3855. return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
  3856. }
  3857.  
  3858. function isBuffer (obj) {
  3859. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  3860. }
  3861.  
  3862. // For Node v0.10 support. Remove this eventually.
  3863. function isSlowBuffer (obj) {
  3864. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
  3865. }
  3866.  
  3867. },{}],11:[function(require,module,exports){
  3868. var toString = {}.toString;
  3869.  
  3870. module.exports = Array.isArray || function (arr) {
  3871. return toString.call(arr) == '[object Array]';
  3872. };
  3873.  
  3874. },{}],12:[function(require,module,exports){
  3875. var Buffer = require('buffer').Buffer;
  3876.  
  3877. module.exports = isBuffer;
  3878.  
  3879. function isBuffer (o) {
  3880. return Buffer.isBuffer(o)
  3881. || /\[object (.+Array|Array.+)\]/.test(Object.prototype.toString.call(o));
  3882. }
  3883.  
  3884. },{"buffer":6}],13:[function(require,module,exports){
  3885. (function (Buffer){
  3886. module.exports = Level
  3887.  
  3888. var IDB = require('idb-wrapper')
  3889. var AbstractLevelDOWN = require('abstract-leveldown').AbstractLevelDOWN
  3890. var util = require('util')
  3891. var Iterator = require('./iterator')
  3892. var isBuffer = require('isbuffer')
  3893. var xtend = require('xtend')
  3894. var toBuffer = require('typedarray-to-buffer')
  3895.  
  3896. function Level(location) {
  3897. if (!(this instanceof Level)) return new Level(location)
  3898. if (!location) throw new Error("constructor requires at least a location argument")
  3899. this.IDBOptions = {}
  3900. this.location = location
  3901. }
  3902.  
  3903. util.inherits(Level, AbstractLevelDOWN)
  3904.  
  3905. Level.prototype._open = function(options, callback) {
  3906. var self = this
  3907. var idbOpts = {
  3908. storeName: this.location,
  3909. autoIncrement: false,
  3910. keyPath: null,
  3911. onStoreReady: function () {
  3912. callback && callback(null, self.idb)
  3913. },
  3914. onError: function(err) {
  3915. callback && callback(err)
  3916. }
  3917. }
  3918. xtend(idbOpts, options)
  3919. this.IDBOptions = idbOpts
  3920. this.idb = new IDB(idbOpts)
  3921. }
  3922.  
  3923. Level.prototype._get = function (key, options, callback) {
  3924. this.idb.get(key, function (value) {
  3925. if (value === undefined) {
  3926. // 'NotFound' error, consistent with LevelDOWN API
  3927. return callback(new Error('NotFound'))
  3928. }
  3929. // by default return buffers, unless explicitly told not to
  3930. var asBuffer = true
  3931. if (options.asBuffer === false) asBuffer = false
  3932. if (options.raw) asBuffer = false
  3933. if (asBuffer) {
  3934. if (value instanceof Uint8Array) value = toBuffer(value)
  3935. else value = new Buffer(String(value))
  3936. }
  3937. return callback(null, value, key)
  3938. }, callback)
  3939. }
  3940.  
  3941. Level.prototype._del = function(id, options, callback) {
  3942. this.idb.remove(id, callback, callback)
  3943. }
  3944.  
  3945. Level.prototype._put = function (key, value, options, callback) {
  3946. if (value instanceof ArrayBuffer) {
  3947. value = toBuffer(new Uint8Array(value))
  3948. }
  3949. var obj = this.convertEncoding(key, value, options)
  3950. if (Buffer.isBuffer(obj.value)) {
  3951. if (typeof value.toArrayBuffer === 'function') {
  3952. obj.value = new Uint8Array(value.toArrayBuffer())
  3953. } else {
  3954. obj.value = new Uint8Array(value)
  3955. }
  3956. }
  3957. this.idb.put(obj.key, obj.value, function() { callback() }, callback)
  3958. }
  3959.  
  3960. Level.prototype.convertEncoding = function(key, value, options) {
  3961. if (options.raw) return {key: key, value: value}
  3962. if (value) {
  3963. var stringed = value.toString()
  3964. if (stringed === 'NaN') value = 'NaN'
  3965. }
  3966. var valEnc = options.valueEncoding
  3967. var obj = {key: key, value: value}
  3968. if (value && (!valEnc || valEnc !== 'binary')) {
  3969. if (typeof obj.value !== 'object') {
  3970. obj.value = stringed
  3971. }
  3972. }
  3973. return obj
  3974. }
  3975.  
  3976. Level.prototype.iterator = function (options) {
  3977. if (typeof options !== 'object') options = {}
  3978. return new Iterator(this.idb, options)
  3979. }
  3980.  
  3981. Level.prototype._batch = function (array, options, callback) {
  3982. var op
  3983. var i
  3984. var k
  3985. var copiedOp
  3986. var currentOp
  3987. var modified = []
  3988. if (array.length === 0) return setTimeout(callback, 0)
  3989. for (i = 0; i < array.length; i++) {
  3990. copiedOp = {}
  3991. currentOp = array[i]
  3992. modified[i] = copiedOp
  3993. var converted = this.convertEncoding(currentOp.key, currentOp.value, options)
  3994. currentOp.key = converted.key
  3995. currentOp.value = converted.value
  3996.  
  3997. for (k in currentOp) {
  3998. if (k === 'type' && currentOp[k] == 'del') {
  3999. copiedOp[k] = 'remove'
  4000. } else {
  4001. copiedOp[k] = currentOp[k]
  4002. }
  4003. }
  4004. }
  4005.  
  4006. return this.idb.batch(modified, function(){ callback() }, callback)
  4007. }
  4008.  
  4009. Level.prototype._close = function (callback) {
  4010. this.idb.db.close()
  4011. callback()
  4012. }
  4013.  
  4014. Level.prototype._approximateSize = function (start, end, callback) {
  4015. var err = new Error('Not implemented')
  4016. if (callback)
  4017. return callback(err)
  4018.  
  4019. throw err
  4020. }
  4021.  
  4022. Level.prototype._isBuffer = function (obj) {
  4023. return Buffer.isBuffer(obj)
  4024. }
  4025.  
  4026. Level.destroy = function (db, callback) {
  4027. if (typeof db === 'object') {
  4028. var prefix = db.IDBOptions.storePrefix || 'IDBWrapper-'
  4029. var dbname = db.location
  4030. } else {
  4031. var prefix = 'IDBWrapper-'
  4032. var dbname = db
  4033. }
  4034. var request = indexedDB.deleteDatabase(prefix + dbname)
  4035. request.onsuccess = function() {
  4036. callback()
  4037. }
  4038. request.onerror = function(err) {
  4039. callback(err)
  4040. }
  4041. }
  4042.  
  4043. var checkKeyValue = Level.prototype._checkKeyValue = function (obj, type) {
  4044. if (obj === null || obj === undefined)
  4045. return new Error(type + ' cannot be `null` or `undefined`')
  4046. if (obj === null || obj === undefined)
  4047. return new Error(type + ' cannot be `null` or `undefined`')
  4048. if (isBuffer(obj) && obj.byteLength === 0)
  4049. return new Error(type + ' cannot be an empty ArrayBuffer')
  4050. if (String(obj) === '')
  4051. return new Error(type + ' cannot be an empty String')
  4052. if (obj.length === 0)
  4053. return new Error(type + ' cannot be an empty Array')
  4054. }
  4055.  
  4056. }).call(this,require("buffer").Buffer)
  4057. },{"./iterator":14,"abstract-leveldown":3,"buffer":6,"idb-wrapper":7,"isbuffer":12,"typedarray-to-buffer":33,"util":35,"xtend":37}],14:[function(require,module,exports){
  4058. var util = require('util')
  4059. var AbstractIterator = require('abstract-leveldown').AbstractIterator
  4060. var ltgt = require('ltgt')
  4061.  
  4062. module.exports = Iterator
  4063.  
  4064. function Iterator (db, options) {
  4065. if (!options) options = {}
  4066. this.options = options
  4067. AbstractIterator.call(this, db)
  4068. this._order = options.reverse ? 'DESC': 'ASC'
  4069. this._limit = options.limit
  4070. this._count = 0
  4071. this._done = false
  4072. var lower = ltgt.lowerBound(options)
  4073. var upper = ltgt.upperBound(options)
  4074. try {
  4075. this._keyRange = lower || upper ? this.db.makeKeyRange({
  4076. lower: lower,
  4077. upper: upper,
  4078. excludeLower: ltgt.lowerBoundExclusive(options),
  4079. excludeUpper: ltgt.upperBoundExclusive(options)
  4080. }) : null
  4081. } catch (e) {
  4082. // The lower key is greater than the upper key.
  4083. // IndexedDB throws an error, but we'll just return 0 results.
  4084. this._keyRangeError = true
  4085. }
  4086. this.callback = null
  4087. }
  4088.  
  4089. util.inherits(Iterator, AbstractIterator)
  4090.  
  4091. Iterator.prototype.createIterator = function() {
  4092. var self = this
  4093.  
  4094. self.iterator = self.db.iterate(function () {
  4095. self.onItem.apply(self, arguments)
  4096. }, {
  4097. keyRange: self._keyRange,
  4098. autoContinue: false,
  4099. order: self._order,
  4100. onError: function(err) { console.log('horrible error', err) },
  4101. })
  4102. }
  4103.  
  4104. // TODO the limit implementation here just ignores all reads after limit has been reached
  4105. // it should cancel the iterator instead but I don't know how
  4106. Iterator.prototype.onItem = function (value, cursor, cursorTransaction) {
  4107. if (!cursor && this.callback) {
  4108. this.callback()
  4109. this.callback = false
  4110. return
  4111. }
  4112. var shouldCall = true
  4113.  
  4114. if (!!this._limit && this._limit > 0 && this._count++ >= this._limit)
  4115. shouldCall = false
  4116.  
  4117. if (shouldCall) this.callback(false, cursor.key, cursor.value)
  4118. if (cursor) cursor['continue']()
  4119. }
  4120.  
  4121. Iterator.prototype._next = function (callback) {
  4122. if (!callback) return new Error('next() requires a callback argument')
  4123. if (this._keyRangeError) return callback()
  4124. if (!this._started) {
  4125. this.createIterator()
  4126. this._started = true
  4127. }
  4128. this.callback = callback
  4129. }
  4130.  
  4131. },{"abstract-leveldown":3,"ltgt":15,"util":35}],15:[function(require,module,exports){
  4132. (function (Buffer){
  4133.  
  4134. exports.compare = function (a, b) {
  4135.  
  4136. if(Buffer.isBuffer(a)) {
  4137. var l = Math.min(a.length, b.length)
  4138. for(var i = 0; i < l; i++) {
  4139. var cmp = a[i] - b[i]
  4140. if(cmp) return cmp
  4141. }
  4142. return a.length - b.length
  4143. }
  4144.  
  4145. return a < b ? -1 : a > b ? 1 : 0
  4146. }
  4147.  
  4148. function has(obj, key) {
  4149. return Object.hasOwnProperty.call(obj, key)
  4150. }
  4151.  
  4152. // to be compatible with the current abstract-leveldown tests
  4153. // nullish or empty strings.
  4154. // I could use !!val but I want to permit numbers and booleans,
  4155. // if possible.
  4156.  
  4157. function isDef (val) {
  4158. return val !== undefined && val !== ''
  4159. }
  4160.  
  4161. function has (range, name) {
  4162. return Object.hasOwnProperty.call(range, name)
  4163. }
  4164.  
  4165. function hasKey(range, name) {
  4166. return Object.hasOwnProperty.call(range, name) && name
  4167. }
  4168.  
  4169. var lowerBoundKey = exports.lowerBoundKey = function (range) {
  4170. return (
  4171. hasKey(range, 'gt')
  4172. || hasKey(range, 'gte')
  4173. || hasKey(range, 'min')
  4174. || (range.reverse ? hasKey(range, 'end') : hasKey(range, 'start'))
  4175. || undefined
  4176. )
  4177. }
  4178.  
  4179. var lowerBound = exports.lowerBound = function (range) {
  4180. var k = lowerBoundKey(range)
  4181. return k && range[k]
  4182. }
  4183.  
  4184. exports.lowerBoundInclusive = function (range) {
  4185. return has(range, 'gt') ? false : true
  4186. }
  4187.  
  4188. exports.upperBoundInclusive =
  4189. function (range) {
  4190. return has(range, 'lt') || !range.minEx ? false : true
  4191. }
  4192.  
  4193. var lowerBoundExclusive = exports.lowerBoundExclusive =
  4194. function (range) {
  4195. return has(range, 'gt') || range.minEx ? true : false
  4196. }
  4197.  
  4198. var upperBoundExclusive = exports.upperBoundExclusive =
  4199. function (range) {
  4200. return has(range, 'lt') ? true : false
  4201. }
  4202.  
  4203. var upperBoundKey = exports.upperBoundKey = function (range) {
  4204. return (
  4205. hasKey(range, 'lt')
  4206. || hasKey(range, 'lte')
  4207. || hasKey(range, 'max')
  4208. || (range.reverse ? hasKey(range, 'start') : hasKey(range, 'end'))
  4209. || undefined
  4210. )
  4211. }
  4212.  
  4213. var upperBound = exports.upperBound = function (range) {
  4214. var k = upperBoundKey(range)
  4215. return k && range[k]
  4216. }
  4217.  
  4218. function id (e) { return e }
  4219.  
  4220. exports.toLtgt = function (range, _range, map, lower, upper) {
  4221. _range = _range || {}
  4222. map = map || id
  4223. var defaults = arguments.length > 3
  4224. var lb = exports.lowerBoundKey(range)
  4225. var ub = exports.upperBoundKey(range)
  4226. if(lb) {
  4227. if(lb === 'gt') _range.gt = map(range.gt, false)
  4228. else _range.gte = map(range[lb], false)
  4229. }
  4230. else if(defaults)
  4231. _range.gte = map(lower, false)
  4232.  
  4233. if(ub) {
  4234. if(ub === 'lt') _range.lt = map(range.lt, true)
  4235. else _range.lte = map(range[ub], true)
  4236. }
  4237. else if(defaults)
  4238. _range.lte = map(upper, true)
  4239.  
  4240. if(range.reverse != null)
  4241. _range.reverse = !!range.reverse
  4242.  
  4243. //if range was used mutably
  4244. //(in level-sublevel it's part of an options object
  4245. //that has more properties on it.)
  4246. if(has(_range, 'max')) delete _range.max
  4247. if(has(_range, 'min')) delete _range.min
  4248. if(has(_range, 'start')) delete _range.start
  4249. if(has(_range, 'end')) delete _range.end
  4250.  
  4251. return _range
  4252. }
  4253.  
  4254. exports.contains = function (range, key, compare) {
  4255. compare = compare || exports.compare
  4256.  
  4257. var lb = lowerBound(range)
  4258. if(isDef(lb)) {
  4259. var cmp = compare(key, lb)
  4260. if(cmp < 0 || (cmp === 0 && lowerBoundExclusive(range)))
  4261. return false
  4262. }
  4263.  
  4264. var ub = upperBound(range)
  4265. if(isDef(ub)) {
  4266. var cmp = compare(key, ub)
  4267. if(cmp > 0 || (cmp === 0) && upperBoundExclusive(range))
  4268. return false
  4269. }
  4270.  
  4271. return true
  4272. }
  4273.  
  4274. exports.filter = function (range, compare) {
  4275. return function (key) {
  4276. return exports.contains(range, key, compare)
  4277. }
  4278. }
  4279.  
  4280. }).call(this,{"isBuffer":require("../is-buffer/index.js")})
  4281. },{"../is-buffer/index.js":10}],16:[function(require,module,exports){
  4282. var hasOwn = Object.prototype.hasOwnProperty;
  4283. var toString = Object.prototype.toString;
  4284.  
  4285. var isFunction = function (fn) {
  4286. var isFunc = (typeof fn === 'function' && !(fn instanceof RegExp)) || toString.call(fn) === '[object Function]';
  4287. if (!isFunc && typeof window !== 'undefined') {
  4288. isFunc = fn === window.setTimeout || fn === window.alert || fn === window.confirm || fn === window.prompt;
  4289. }
  4290. return isFunc;
  4291. };
  4292.  
  4293. module.exports = function forEach(obj, fn) {
  4294. if (!isFunction(fn)) {
  4295. throw new TypeError('iterator must be a function');
  4296. }
  4297. var i, k,
  4298. isString = typeof obj === 'string',
  4299. l = obj.length,
  4300. context = arguments.length > 2 ? arguments[2] : null;
  4301. if (l === +l) {
  4302. for (i = 0; i < l; i++) {
  4303. if (context === null) {
  4304. fn(isString ? obj.charAt(i) : obj[i], i, obj);
  4305. } else {
  4306. fn.call(context, isString ? obj.charAt(i) : obj[i], i, obj);
  4307. }
  4308. }
  4309. } else {
  4310. for (k in obj) {
  4311. if (hasOwn.call(obj, k)) {
  4312. if (context === null) {
  4313. fn(obj[k], k, obj);
  4314. } else {
  4315. fn.call(context, obj[k], k, obj);
  4316. }
  4317. }
  4318. }
  4319. }
  4320. };
  4321.  
  4322.  
  4323. },{}],17:[function(require,module,exports){
  4324. module.exports = Object.keys || require('./shim');
  4325.  
  4326.  
  4327. },{"./shim":19}],18:[function(require,module,exports){
  4328. var toString = Object.prototype.toString;
  4329.  
  4330. module.exports = function isArguments(value) {
  4331. var str = toString.call(value);
  4332. var isArguments = str === '[object Arguments]';
  4333. if (!isArguments) {
  4334. isArguments = str !== '[object Array]'
  4335. && value !== null
  4336. && typeof value === 'object'
  4337. && typeof value.length === 'number'
  4338. && value.length >= 0
  4339. && toString.call(value.callee) === '[object Function]';
  4340. }
  4341. return isArguments;
  4342. };
  4343.  
  4344.  
  4345. },{}],19:[function(require,module,exports){
  4346. (function () {
  4347. "use strict";
  4348.  
  4349. // modified from https://github.com/kriskowal/es5-shim
  4350. var has = Object.prototype.hasOwnProperty,
  4351. toString = Object.prototype.toString,
  4352. forEach = require('./foreach'),
  4353. isArgs = require('./isArguments'),
  4354. hasDontEnumBug = !({'toString': null}).propertyIsEnumerable('toString'),
  4355. hasProtoEnumBug = (function () {}).propertyIsEnumerable('prototype'),
  4356. dontEnums = [
  4357. "toString",
  4358. "toLocaleString",
  4359. "valueOf",
  4360. "hasOwnProperty",
  4361. "isPrototypeOf",
  4362. "propertyIsEnumerable",
  4363. "constructor"
  4364. ],
  4365. keysShim;
  4366.  
  4367. keysShim = function keys(object) {
  4368. var isObject = object !== null && typeof object === 'object',
  4369. isFunction = toString.call(object) === '[object Function]',
  4370. isArguments = isArgs(object),
  4371. theKeys = [];
  4372.  
  4373. if (!isObject && !isFunction && !isArguments) {
  4374. throw new TypeError("Object.keys called on a non-object");
  4375. }
  4376.  
  4377. if (isArguments) {
  4378. forEach(object, function (value) {
  4379. theKeys.push(value);
  4380. });
  4381. } else {
  4382. var name,
  4383. skipProto = hasProtoEnumBug && isFunction;
  4384.  
  4385. for (name in object) {
  4386. if (!(skipProto && name === 'prototype') && has.call(object, name)) {
  4387. theKeys.push(name);
  4388. }
  4389. }
  4390. }
  4391.  
  4392. if (hasDontEnumBug) {
  4393. var ctor = object.constructor,
  4394. skipConstructor = ctor && ctor.prototype === object;
  4395.  
  4396. forEach(dontEnums, function (dontEnum) {
  4397. if (!(skipConstructor && dontEnum === 'constructor') && has.call(object, dontEnum)) {
  4398. theKeys.push(dontEnum);
  4399. }
  4400. });
  4401. }
  4402. return theKeys;
  4403. };
  4404.  
  4405. module.exports = keysShim;
  4406. }());
  4407.  
  4408.  
  4409. },{"./foreach":16,"./isArguments":18}],20:[function(require,module,exports){
  4410. 'use strict';
  4411.  
  4412.  
  4413. var zlib_inflate = require('./zlib/inflate');
  4414. var utils = require('./utils/common');
  4415. var strings = require('./utils/strings');
  4416. var c = require('./zlib/constants');
  4417. var msg = require('./zlib/messages');
  4418. var ZStream = require('./zlib/zstream');
  4419. var GZheader = require('./zlib/gzheader');
  4420.  
  4421. var toString = Object.prototype.toString;
  4422.  
  4423. /**
  4424. * class Inflate
  4425. *
  4426. * Generic JS-style wrapper for zlib calls. If you don't need
  4427. * streaming behaviour - use more simple functions: [[inflate]]
  4428. * and [[inflateRaw]].
  4429. **/
  4430.  
  4431. /* internal
  4432. * inflate.chunks -> Array
  4433. *
  4434. * Chunks of output data, if [[Inflate#onData]] not overriden.
  4435. **/
  4436.  
  4437. /**
  4438. * Inflate.result -> Uint8Array|Array|String
  4439. *
  4440. * Uncompressed result, generated by default [[Inflate#onData]]
  4441. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  4442. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  4443. * push a chunk with explicit flush (call [[Inflate#push]] with
  4444. * `Z_SYNC_FLUSH` param).
  4445. **/
  4446.  
  4447. /**
  4448. * Inflate.err -> Number
  4449. *
  4450. * Error code after inflate finished. 0 (Z_OK) on success.
  4451. * Should be checked if broken data possible.
  4452. **/
  4453.  
  4454. /**
  4455. * Inflate.msg -> String
  4456. *
  4457. * Error message, if [[Inflate.err]] != 0
  4458. **/
  4459.  
  4460.  
  4461. /**
  4462. * new Inflate(options)
  4463. * - options (Object): zlib inflate options.
  4464. *
  4465. * Creates new inflator instance with specified params. Throws exception
  4466. * on bad params. Supported options:
  4467. *
  4468. * - `windowBits`
  4469. * - `dictionary`
  4470. *
  4471. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  4472. * for more information on these.
  4473. *
  4474. * Additional options, for internal needs:
  4475. *
  4476. * - `chunkSize` - size of generated data chunks (16K by default)
  4477. * - `raw` (Boolean) - do raw inflate
  4478. * - `to` (String) - if equal to 'string', then result will be converted
  4479. * from utf8 to utf16 (javascript) string. When string output requested,
  4480. * chunk length can differ from `chunkSize`, depending on content.
  4481. *
  4482. * By default, when no options set, autodetect deflate/gzip data format via
  4483. * wrapper header.
  4484. *
  4485. * ##### Example:
  4486. *
  4487. * ```javascript
  4488. * var pako = require('pako')
  4489. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  4490. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  4491. *
  4492. * var inflate = new pako.Inflate({ level: 3});
  4493. *
  4494. * inflate.push(chunk1, false);
  4495. * inflate.push(chunk2, true); // true -> last chunk
  4496. *
  4497. * if (inflate.err) { throw new Error(inflate.err); }
  4498. *
  4499. * console.log(inflate.result);
  4500. * ```
  4501. **/
  4502. function Inflate(options) {
  4503. if (!(this instanceof Inflate)) return new Inflate(options);
  4504.  
  4505. this.options = utils.assign({
  4506. chunkSize: 16384,
  4507. windowBits: 0,
  4508. to: ''
  4509. }, options || {});
  4510.  
  4511. var opt = this.options;
  4512.  
  4513. // Force window size for `raw` data, if not set directly,
  4514. // because we have no header for autodetect.
  4515. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  4516. opt.windowBits = -opt.windowBits;
  4517. if (opt.windowBits === 0) { opt.windowBits = -15; }
  4518. }
  4519.  
  4520. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  4521. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  4522. !(options && options.windowBits)) {
  4523. opt.windowBits += 32;
  4524. }
  4525.  
  4526. // Gzip header has no info about windows size, we can do autodetect only
  4527. // for deflate. So, if window size not set, force it to max when gzip possible
  4528. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  4529. // bit 3 (16) -> gzipped data
  4530. // bit 4 (32) -> autodetect gzip/deflate
  4531. if ((opt.windowBits & 15) === 0) {
  4532. opt.windowBits |= 15;
  4533. }
  4534. }
  4535.  
  4536. this.err = 0; // error code, if happens (0 = Z_OK)
  4537. this.msg = ''; // error message
  4538. this.ended = false; // used to avoid multiple onEnd() calls
  4539. this.chunks = []; // chunks of compressed data
  4540.  
  4541. this.strm = new ZStream();
  4542. this.strm.avail_out = 0;
  4543.  
  4544. var status = zlib_inflate.inflateInit2(
  4545. this.strm,
  4546. opt.windowBits
  4547. );
  4548.  
  4549. if (status !== c.Z_OK) {
  4550. throw new Error(msg[status]);
  4551. }
  4552.  
  4553. this.header = new GZheader();
  4554.  
  4555. zlib_inflate.inflateGetHeader(this.strm, this.header);
  4556. }
  4557.  
  4558. /**
  4559. * Inflate#push(data[, mode]) -> Boolean
  4560. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  4561. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  4562. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  4563. *
  4564. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  4565. * new output chunks. Returns `true` on success. The last data block must have
  4566. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  4567. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  4568. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  4569. *
  4570. * On fail call [[Inflate#onEnd]] with error code and return false.
  4571. *
  4572. * We strongly recommend to use `Uint8Array` on input for best speed (output
  4573. * format is detected automatically). Also, don't skip last param and always
  4574. * use the same type in your code (boolean or number). That will improve JS speed.
  4575. *
  4576. * For regular `Array`-s make sure all elements are [0..255].
  4577. *
  4578. * ##### Example
  4579. *
  4580. * ```javascript
  4581. * push(chunk, false); // push one of data chunks
  4582. * ...
  4583. * push(chunk, true); // push last chunk
  4584. * ```
  4585. **/
  4586. Inflate.prototype.push = function (data, mode) {
  4587. var strm = this.strm;
  4588. var chunkSize = this.options.chunkSize;
  4589. var dictionary = this.options.dictionary;
  4590. var status, _mode;
  4591. var next_out_utf8, tail, utf8str;
  4592. var dict;
  4593.  
  4594. // Flag to properly process Z_BUF_ERROR on testing inflate call
  4595. // when we check that all output data was flushed.
  4596. var allowBufError = false;
  4597.  
  4598. if (this.ended) { return false; }
  4599. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  4600.  
  4601. // Convert data if needed
  4602. if (typeof data === 'string') {
  4603. // Only binary strings can be decompressed on practice
  4604. strm.input = strings.binstring2buf(data);
  4605. } else if (toString.call(data) === '[object ArrayBuffer]') {
  4606. strm.input = new Uint8Array(data);
  4607. } else {
  4608. strm.input = data;
  4609. }
  4610.  
  4611. strm.next_in = 0;
  4612. strm.avail_in = strm.input.length;
  4613.  
  4614. do {
  4615. if (strm.avail_out === 0) {
  4616. strm.output = new utils.Buf8(chunkSize);
  4617. strm.next_out = 0;
  4618. strm.avail_out = chunkSize;
  4619. }
  4620.  
  4621. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  4622.  
  4623. if (status === c.Z_NEED_DICT && dictionary) {
  4624. // Convert data if needed
  4625. if (typeof dictionary === 'string') {
  4626. dict = strings.string2buf(dictionary);
  4627. } else if (toString.call(dictionary) === '[object ArrayBuffer]') {
  4628. dict = new Uint8Array(dictionary);
  4629. } else {
  4630. dict = dictionary;
  4631. }
  4632.  
  4633. status = zlib_inflate.inflateSetDictionary(this.strm, dict);
  4634.  
  4635. }
  4636.  
  4637. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  4638. status = c.Z_OK;
  4639. allowBufError = false;
  4640. }
  4641.  
  4642. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  4643. this.onEnd(status);
  4644. this.ended = true;
  4645. return false;
  4646. }
  4647.  
  4648. if (strm.next_out) {
  4649. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  4650.  
  4651. if (this.options.to === 'string') {
  4652.  
  4653. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  4654.  
  4655. tail = strm.next_out - next_out_utf8;
  4656. utf8str = strings.buf2string(strm.output, next_out_utf8);
  4657.  
  4658. // move tail
  4659. strm.next_out = tail;
  4660. strm.avail_out = chunkSize - tail;
  4661. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  4662.  
  4663. this.onData(utf8str);
  4664.  
  4665. } else {
  4666. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  4667. }
  4668. }
  4669. }
  4670.  
  4671. // When no more input data, we should check that internal inflate buffers
  4672. // are flushed. The only way to do it when avail_out = 0 - run one more
  4673. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  4674. // Here we set flag to process this error properly.
  4675. //
  4676. // NOTE. Deflate does not return error in this case and does not needs such
  4677. // logic.
  4678. if (strm.avail_in === 0 && strm.avail_out === 0) {
  4679. allowBufError = true;
  4680. }
  4681.  
  4682. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  4683.  
  4684. if (status === c.Z_STREAM_END) {
  4685. _mode = c.Z_FINISH;
  4686. }
  4687.  
  4688. // Finalize on the last chunk.
  4689. if (_mode === c.Z_FINISH) {
  4690. status = zlib_inflate.inflateEnd(this.strm);
  4691. this.onEnd(status);
  4692. this.ended = true;
  4693. return status === c.Z_OK;
  4694. }
  4695.  
  4696. // callback interim results if Z_SYNC_FLUSH.
  4697. if (_mode === c.Z_SYNC_FLUSH) {
  4698. this.onEnd(c.Z_OK);
  4699. strm.avail_out = 0;
  4700. return true;
  4701. }
  4702.  
  4703. return true;
  4704. };
  4705.  
  4706.  
  4707. /**
  4708. * Inflate#onData(chunk) -> Void
  4709. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  4710. * on js engine support. When string output requested, each chunk
  4711. * will be string.
  4712. *
  4713. * By default, stores data blocks in `chunks[]` property and glue
  4714. * those in `onEnd`. Override this handler, if you need another behaviour.
  4715. **/
  4716. Inflate.prototype.onData = function (chunk) {
  4717. this.chunks.push(chunk);
  4718. };
  4719.  
  4720.  
  4721. /**
  4722. * Inflate#onEnd(status) -> Void
  4723. * - status (Number): inflate status. 0 (Z_OK) on success,
  4724. * other if not.
  4725. *
  4726. * Called either after you tell inflate that the input stream is
  4727. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  4728. * or if an error happened. By default - join collected chunks,
  4729. * free memory and fill `results` / `err` properties.
  4730. **/
  4731. Inflate.prototype.onEnd = function (status) {
  4732. // On success - join
  4733. if (status === c.Z_OK) {
  4734. if (this.options.to === 'string') {
  4735. // Glue & convert here, until we teach pako to send
  4736. // utf8 alligned strings to onData
  4737. this.result = this.chunks.join('');
  4738. } else {
  4739. this.result = utils.flattenChunks(this.chunks);
  4740. }
  4741. }
  4742. this.chunks = [];
  4743. this.err = status;
  4744. this.msg = this.strm.msg;
  4745. };
  4746.  
  4747.  
  4748. /**
  4749. * inflate(data[, options]) -> Uint8Array|Array|String
  4750. * - data (Uint8Array|Array|String): input data to decompress.
  4751. * - options (Object): zlib inflate options.
  4752. *
  4753. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  4754. * format via wrapper header by default. That's why we don't provide
  4755. * separate `ungzip` method.
  4756. *
  4757. * Supported options are:
  4758. *
  4759. * - windowBits
  4760. *
  4761. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  4762. * for more information.
  4763. *
  4764. * Sugar (options):
  4765. *
  4766. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  4767. * negative windowBits implicitly.
  4768. * - `to` (String) - if equal to 'string', then result will be converted
  4769. * from utf8 to utf16 (javascript) string. When string output requested,
  4770. * chunk length can differ from `chunkSize`, depending on content.
  4771. *
  4772. *
  4773. * ##### Example:
  4774. *
  4775. * ```javascript
  4776. * var pako = require('pako')
  4777. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  4778. * , output;
  4779. *
  4780. * try {
  4781. * output = pako.inflate(input);
  4782. * } catch (err)
  4783. * console.log(err);
  4784. * }
  4785. * ```
  4786. **/
  4787. function inflate(input, options) {
  4788. var inflator = new Inflate(options);
  4789.  
  4790. inflator.push(input, true);
  4791.  
  4792. // That will never happens, if you don't cheat with options :)
  4793. if (inflator.err) { throw inflator.msg; }
  4794.  
  4795. return inflator.result;
  4796. }
  4797.  
  4798.  
  4799. /**
  4800. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  4801. * - data (Uint8Array|Array|String): input data to decompress.
  4802. * - options (Object): zlib inflate options.
  4803. *
  4804. * The same as [[inflate]], but creates raw data, without wrapper
  4805. * (header and adler32 crc).
  4806. **/
  4807. function inflateRaw(input, options) {
  4808. options = options || {};
  4809. options.raw = true;
  4810. return inflate(input, options);
  4811. }
  4812.  
  4813.  
  4814. /**
  4815. * ungzip(data[, options]) -> Uint8Array|Array|String
  4816. * - data (Uint8Array|Array|String): input data to decompress.
  4817. * - options (Object): zlib inflate options.
  4818. *
  4819. * Just shortcut to [[inflate]], because it autodetects format
  4820. * by header.content. Done for convenience.
  4821. **/
  4822.  
  4823.  
  4824. exports.Inflate = Inflate;
  4825. exports.inflate = inflate;
  4826. exports.inflateRaw = inflateRaw;
  4827. exports.ungzip = inflate;
  4828.  
  4829. },{"./utils/common":21,"./utils/strings":22,"./zlib/constants":24,"./zlib/gzheader":26,"./zlib/inflate":28,"./zlib/messages":30,"./zlib/zstream":31}],21:[function(require,module,exports){
  4830. 'use strict';
  4831.  
  4832.  
  4833. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  4834. (typeof Uint16Array !== 'undefined') &&
  4835. (typeof Int32Array !== 'undefined');
  4836.  
  4837.  
  4838. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  4839. var sources = Array.prototype.slice.call(arguments, 1);
  4840. while (sources.length) {
  4841. var source = sources.shift();
  4842. if (!source) { continue; }
  4843.  
  4844. if (typeof source !== 'object') {
  4845. throw new TypeError(source + 'must be non-object');
  4846. }
  4847.  
  4848. for (var p in source) {
  4849. if (source.hasOwnProperty(p)) {
  4850. obj[p] = source[p];
  4851. }
  4852. }
  4853. }
  4854.  
  4855. return obj;
  4856. };
  4857.  
  4858.  
  4859. // reduce buffer size, avoiding mem copy
  4860. exports.shrinkBuf = function (buf, size) {
  4861. if (buf.length === size) { return buf; }
  4862. if (buf.subarray) { return buf.subarray(0, size); }
  4863. buf.length = size;
  4864. return buf;
  4865. };
  4866.  
  4867.  
  4868. var fnTyped = {
  4869. arraySet: function (dest, src, src_offs, len, dest_offs) {
  4870. if (src.subarray && dest.subarray) {
  4871. dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
  4872. return;
  4873. }
  4874. // Fallback to ordinary array
  4875. for (var i = 0; i < len; i++) {
  4876. dest[dest_offs + i] = src[src_offs + i];
  4877. }
  4878. },
  4879. // Join array of chunks to single array.
  4880. flattenChunks: function (chunks) {
  4881. var i, l, len, pos, chunk, result;
  4882.  
  4883. // calculate data length
  4884. len = 0;
  4885. for (i = 0, l = chunks.length; i < l; i++) {
  4886. len += chunks[i].length;
  4887. }
  4888.  
  4889. // join chunks
  4890. result = new Uint8Array(len);
  4891. pos = 0;
  4892. for (i = 0, l = chunks.length; i < l; i++) {
  4893. chunk = chunks[i];
  4894. result.set(chunk, pos);
  4895. pos += chunk.length;
  4896. }
  4897.  
  4898. return result;
  4899. }
  4900. };
  4901.  
  4902. var fnUntyped = {
  4903. arraySet: function (dest, src, src_offs, len, dest_offs) {
  4904. for (var i = 0; i < len; i++) {
  4905. dest[dest_offs + i] = src[src_offs + i];
  4906. }
  4907. },
  4908. // Join array of chunks to single array.
  4909. flattenChunks: function (chunks) {
  4910. return [].concat.apply([], chunks);
  4911. }
  4912. };
  4913.  
  4914.  
  4915. // Enable/Disable typed arrays use, for testing
  4916. //
  4917. exports.setTyped = function (on) {
  4918. if (on) {
  4919. exports.Buf8 = Uint8Array;
  4920. exports.Buf16 = Uint16Array;
  4921. exports.Buf32 = Int32Array;
  4922. exports.assign(exports, fnTyped);
  4923. } else {
  4924. exports.Buf8 = Array;
  4925. exports.Buf16 = Array;
  4926. exports.Buf32 = Array;
  4927. exports.assign(exports, fnUntyped);
  4928. }
  4929. };
  4930.  
  4931. exports.setTyped(TYPED_OK);
  4932.  
  4933. },{}],22:[function(require,module,exports){
  4934. // String encode/decode helpers
  4935. 'use strict';
  4936.  
  4937.  
  4938. var utils = require('./common');
  4939.  
  4940.  
  4941. // Quick check if we can use fast array to bin string conversion
  4942. //
  4943. // - apply(Array) can fail on Android 2.2
  4944. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  4945. //
  4946. var STR_APPLY_OK = true;
  4947. var STR_APPLY_UIA_OK = true;
  4948.  
  4949. try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; }
  4950. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }
  4951.  
  4952.  
  4953. // Table with utf8 lengths (calculated by first byte of sequence)
  4954. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  4955. // because max possible codepoint is 0x10ffff
  4956. var _utf8len = new utils.Buf8(256);
  4957. for (var q = 0; q < 256; q++) {
  4958. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  4959. }
  4960. _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
  4961.  
  4962.  
  4963. // convert string to array (typed, when possible)
  4964. exports.string2buf = function (str) {
  4965. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  4966.  
  4967. // count binary size
  4968. for (m_pos = 0; m_pos < str_len; m_pos++) {
  4969. c = str.charCodeAt(m_pos);
  4970. if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
  4971. c2 = str.charCodeAt(m_pos + 1);
  4972. if ((c2 & 0xfc00) === 0xdc00) {
  4973. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  4974. m_pos++;
  4975. }
  4976. }
  4977. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  4978. }
  4979.  
  4980. // allocate buffer
  4981. buf = new utils.Buf8(buf_len);
  4982.  
  4983. // convert
  4984. for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
  4985. c = str.charCodeAt(m_pos);
  4986. if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
  4987. c2 = str.charCodeAt(m_pos + 1);
  4988. if ((c2 & 0xfc00) === 0xdc00) {
  4989. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  4990. m_pos++;
  4991. }
  4992. }
  4993. if (c < 0x80) {
  4994. /* one byte */
  4995. buf[i++] = c;
  4996. } else if (c < 0x800) {
  4997. /* two bytes */
  4998. buf[i++] = 0xC0 | (c >>> 6);
  4999. buf[i++] = 0x80 | (c & 0x3f);
  5000. } else if (c < 0x10000) {
  5001. /* three bytes */
  5002. buf[i++] = 0xE0 | (c >>> 12);
  5003. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  5004. buf[i++] = 0x80 | (c & 0x3f);
  5005. } else {
  5006. /* four bytes */
  5007. buf[i++] = 0xf0 | (c >>> 18);
  5008. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  5009. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  5010. buf[i++] = 0x80 | (c & 0x3f);
  5011. }
  5012. }
  5013.  
  5014. return buf;
  5015. };
  5016.  
  5017. // Helper (used in 2 places)
  5018. function buf2binstring(buf, len) {
  5019. // use fallback for big arrays to avoid stack overflow
  5020. if (len < 65537) {
  5021. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  5022. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  5023. }
  5024. }
  5025.  
  5026. var result = '';
  5027. for (var i = 0; i < len; i++) {
  5028. result += String.fromCharCode(buf[i]);
  5029. }
  5030. return result;
  5031. }
  5032.  
  5033.  
  5034. // Convert byte array to binary string
  5035. exports.buf2binstring = function (buf) {
  5036. return buf2binstring(buf, buf.length);
  5037. };
  5038.  
  5039.  
  5040. // Convert binary string (typed, when possible)
  5041. exports.binstring2buf = function (str) {
  5042. var buf = new utils.Buf8(str.length);
  5043. for (var i = 0, len = buf.length; i < len; i++) {
  5044. buf[i] = str.charCodeAt(i);
  5045. }
  5046. return buf;
  5047. };
  5048.  
  5049.  
  5050. // convert array to string
  5051. exports.buf2string = function (buf, max) {
  5052. var i, out, c, c_len;
  5053. var len = max || buf.length;
  5054.  
  5055. // Reserve max possible length (2 words per char)
  5056. // NB: by unknown reasons, Array is significantly faster for
  5057. // String.fromCharCode.apply than Uint16Array.
  5058. var utf16buf = new Array(len * 2);
  5059.  
  5060. for (out = 0, i = 0; i < len;) {
  5061. c = buf[i++];
  5062. // quick process ascii
  5063. if (c < 0x80) { utf16buf[out++] = c; continue; }
  5064.  
  5065. c_len = _utf8len[c];
  5066. // skip 5 & 6 byte codes
  5067. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }
  5068.  
  5069. // apply mask on first byte
  5070. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  5071. // join the rest
  5072. while (c_len > 1 && i < len) {
  5073. c = (c << 6) | (buf[i++] & 0x3f);
  5074. c_len--;
  5075. }
  5076.  
  5077. // terminated by end of string?
  5078. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  5079.  
  5080. if (c < 0x10000) {
  5081. utf16buf[out++] = c;
  5082. } else {
  5083. c -= 0x10000;
  5084. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  5085. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  5086. }
  5087. }
  5088.  
  5089. return buf2binstring(utf16buf, out);
  5090. };
  5091.  
  5092.  
  5093. // Calculate max possible position in utf8 buffer,
  5094. // that will not break sequence. If that's not possible
  5095. // - (very small limits) return max size as is.
  5096. //
  5097. // buf[] - utf8 bytes array
  5098. // max - length limit (mandatory);
  5099. exports.utf8border = function (buf, max) {
  5100. var pos;
  5101.  
  5102. max = max || buf.length;
  5103. if (max > buf.length) { max = buf.length; }
  5104.  
  5105. // go back from last position, until start of sequence found
  5106. pos = max - 1;
  5107. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  5108.  
  5109. // Fuckup - very small and broken sequence,
  5110. // return max, because we should return something anyway.
  5111. if (pos < 0) { return max; }
  5112.  
  5113. // If we came to start of buffer - that means vuffer is too small,
  5114. // return max too.
  5115. if (pos === 0) { return max; }
  5116.  
  5117. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  5118. };
  5119.  
  5120. },{"./common":21}],23:[function(require,module,exports){
  5121. 'use strict';
  5122.  
  5123. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  5124. // It doesn't worth to make additional optimizationa as in original.
  5125. // Small size is preferable.
  5126.  
  5127. function adler32(adler, buf, len, pos) {
  5128. var s1 = (adler & 0xffff) |0,
  5129. s2 = ((adler >>> 16) & 0xffff) |0,
  5130. n = 0;
  5131.  
  5132. while (len !== 0) {
  5133. // Set limit ~ twice less than 5552, to keep
  5134. // s2 in 31-bits, because we force signed ints.
  5135. // in other case %= will fail.
  5136. n = len > 2000 ? 2000 : len;
  5137. len -= n;
  5138.  
  5139. do {
  5140. s1 = (s1 + buf[pos++]) |0;
  5141. s2 = (s2 + s1) |0;
  5142. } while (--n);
  5143.  
  5144. s1 %= 65521;
  5145. s2 %= 65521;
  5146. }
  5147.  
  5148. return (s1 | (s2 << 16)) |0;
  5149. }
  5150.  
  5151.  
  5152. module.exports = adler32;
  5153.  
  5154. },{}],24:[function(require,module,exports){
  5155. 'use strict';
  5156.  
  5157.  
  5158. module.exports = {
  5159.  
  5160. /* Allowed flush values; see deflate() and inflate() below for details */
  5161. Z_NO_FLUSH: 0,
  5162. Z_PARTIAL_FLUSH: 1,
  5163. Z_SYNC_FLUSH: 2,
  5164. Z_FULL_FLUSH: 3,
  5165. Z_FINISH: 4,
  5166. Z_BLOCK: 5,
  5167. Z_TREES: 6,
  5168.  
  5169. /* Return codes for the compression/decompression functions. Negative values
  5170. * are errors, positive values are used for special but normal events.
  5171. */
  5172. Z_OK: 0,
  5173. Z_STREAM_END: 1,
  5174. Z_NEED_DICT: 2,
  5175. Z_ERRNO: -1,
  5176. Z_STREAM_ERROR: -2,
  5177. Z_DATA_ERROR: -3,
  5178. //Z_MEM_ERROR: -4,
  5179. Z_BUF_ERROR: -5,
  5180. //Z_VERSION_ERROR: -6,
  5181.  
  5182. /* compression levels */
  5183. Z_NO_COMPRESSION: 0,
  5184. Z_BEST_SPEED: 1,
  5185. Z_BEST_COMPRESSION: 9,
  5186. Z_DEFAULT_COMPRESSION: -1,
  5187.  
  5188.  
  5189. Z_FILTERED: 1,
  5190. Z_HUFFMAN_ONLY: 2,
  5191. Z_RLE: 3,
  5192. Z_FIXED: 4,
  5193. Z_DEFAULT_STRATEGY: 0,
  5194.  
  5195. /* Possible values of the data_type field (though see inflate()) */
  5196. Z_BINARY: 0,
  5197. Z_TEXT: 1,
  5198. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  5199. Z_UNKNOWN: 2,
  5200.  
  5201. /* The deflate compression method */
  5202. Z_DEFLATED: 8
  5203. //Z_NULL: null // Use -1 or null inline, depending on var type
  5204. };
  5205.  
  5206. },{}],25:[function(require,module,exports){
  5207. 'use strict';
  5208.  
  5209. // Note: we can't get significant speed boost here.
  5210. // So write code to minimize size - no pregenerated tables
  5211. // and array tools dependencies.
  5212.  
  5213.  
  5214. // Use ordinary array, since untyped makes no boost here
  5215. function makeTable() {
  5216. var c, table = [];
  5217.  
  5218. for (var n = 0; n < 256; n++) {
  5219. c = n;
  5220. for (var k = 0; k < 8; k++) {
  5221. c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  5222. }
  5223. table[n] = c;
  5224. }
  5225.  
  5226. return table;
  5227. }
  5228.  
  5229. // Create table on load. Just 255 signed longs. Not a problem.
  5230. var crcTable = makeTable();
  5231.  
  5232.  
  5233. function crc32(crc, buf, len, pos) {
  5234. var t = crcTable,
  5235. end = pos + len;
  5236.  
  5237. crc ^= -1;
  5238.  
  5239. for (var i = pos; i < end; i++) {
  5240. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  5241. }
  5242.  
  5243. return (crc ^ (-1)); // >>> 0;
  5244. }
  5245.  
  5246.  
  5247. module.exports = crc32;
  5248.  
  5249. },{}],26:[function(require,module,exports){
  5250. 'use strict';
  5251.  
  5252.  
  5253. function GZheader() {
  5254. /* true if compressed data believed to be text */
  5255. this.text = 0;
  5256. /* modification time */
  5257. this.time = 0;
  5258. /* extra flags (not used when writing a gzip file) */
  5259. this.xflags = 0;
  5260. /* operating system */
  5261. this.os = 0;
  5262. /* pointer to extra field or Z_NULL if none */
  5263. this.extra = null;
  5264. /* extra field length (valid if extra != Z_NULL) */
  5265. this.extra_len = 0; // Actually, we don't need it in JS,
  5266. // but leave for few code modifications
  5267.  
  5268. //
  5269. // Setup limits is not necessary because in js we should not preallocate memory
  5270. // for inflate use constant limit in 65536 bytes
  5271. //
  5272.  
  5273. /* space at extra (only when reading header) */
  5274. // this.extra_max = 0;
  5275. /* pointer to zero-terminated file name or Z_NULL */
  5276. this.name = '';
  5277. /* space at name (only when reading header) */
  5278. // this.name_max = 0;
  5279. /* pointer to zero-terminated comment or Z_NULL */
  5280. this.comment = '';
  5281. /* space at comment (only when reading header) */
  5282. // this.comm_max = 0;
  5283. /* true if there was or will be a header crc */
  5284. this.hcrc = 0;
  5285. /* true when done reading gzip header (not used when writing a gzip file) */
  5286. this.done = false;
  5287. }
  5288.  
  5289. module.exports = GZheader;
  5290.  
  5291. },{}],27:[function(require,module,exports){
  5292. 'use strict';
  5293.  
  5294. // See state defs from inflate.js
  5295. var BAD = 30; /* got a data error -- remain here until reset */
  5296. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  5297.  
  5298. /*
  5299. Decode literal, length, and distance codes and write out the resulting
  5300. literal and match bytes until either not enough input or output is
  5301. available, an end-of-block is encountered, or a data error is encountered.
  5302. When large enough input and output buffers are supplied to inflate(), for
  5303. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  5304. inflate execution time is spent in this routine.
  5305.  
  5306. Entry assumptions:
  5307.  
  5308. state.mode === LEN
  5309. strm.avail_in >= 6
  5310. strm.avail_out >= 258
  5311. start >= strm.avail_out
  5312. state.bits < 8
  5313.  
  5314. On return, state.mode is one of:
  5315.  
  5316. LEN -- ran out of enough output space or enough available input
  5317. TYPE -- reached end of block code, inflate() to interpret next block
  5318. BAD -- error in block data
  5319.  
  5320. Notes:
  5321.  
  5322. - The maximum input bits used by a length/distance pair is 15 bits for the
  5323. length code, 5 bits for the length extra, 15 bits for the distance code,
  5324. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  5325. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  5326. checking for available input while decoding.
  5327.  
  5328. - The maximum bytes that a single length/distance pair can output is 258
  5329. bytes, which is the maximum length that can be coded. inflate_fast()
  5330. requires strm.avail_out >= 258 for each loop to avoid checking for
  5331. output space.
  5332. */
  5333. module.exports = function inflate_fast(strm, start) {
  5334. var state;
  5335. var _in; /* local strm.input */
  5336. var last; /* have enough input while in < last */
  5337. var _out; /* local strm.output */
  5338. var beg; /* inflate()'s initial strm.output */
  5339. var end; /* while out < end, enough space available */
  5340. //#ifdef INFLATE_STRICT
  5341. var dmax; /* maximum distance from zlib header */
  5342. //#endif
  5343. var wsize; /* window size or zero if not using window */
  5344. var whave; /* valid bytes in the window */
  5345. var wnext; /* window write index */
  5346. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  5347. var s_window; /* allocated sliding window, if wsize != 0 */
  5348. var hold; /* local strm.hold */
  5349. var bits; /* local strm.bits */
  5350. var lcode; /* local strm.lencode */
  5351. var dcode; /* local strm.distcode */
  5352. var lmask; /* mask for first level of length codes */
  5353. var dmask; /* mask for first level of distance codes */
  5354. var here; /* retrieved table entry */
  5355. var op; /* code bits, operation, extra bits, or */
  5356. /* window position, window bytes to copy */
  5357. var len; /* match length, unused bytes */
  5358. var dist; /* match distance */
  5359. var from; /* where to copy match from */
  5360. var from_source;
  5361.  
  5362.  
  5363. var input, output; // JS specific, because we have no pointers
  5364.  
  5365. /* copy state to local variables */
  5366. state = strm.state;
  5367. //here = state.here;
  5368. _in = strm.next_in;
  5369. input = strm.input;
  5370. last = _in + (strm.avail_in - 5);
  5371. _out = strm.next_out;
  5372. output = strm.output;
  5373. beg = _out - (start - strm.avail_out);
  5374. end = _out + (strm.avail_out - 257);
  5375. //#ifdef INFLATE_STRICT
  5376. dmax = state.dmax;
  5377. //#endif
  5378. wsize = state.wsize;
  5379. whave = state.whave;
  5380. wnext = state.wnext;
  5381. s_window = state.window;
  5382. hold = state.hold;
  5383. bits = state.bits;
  5384. lcode = state.lencode;
  5385. dcode = state.distcode;
  5386. lmask = (1 << state.lenbits) - 1;
  5387. dmask = (1 << state.distbits) - 1;
  5388.  
  5389.  
  5390. /* decode literals and length/distances until end-of-block or not enough
  5391. input data or output space */
  5392.  
  5393. top:
  5394. do {
  5395. if (bits < 15) {
  5396. hold += input[_in++] << bits;
  5397. bits += 8;
  5398. hold += input[_in++] << bits;
  5399. bits += 8;
  5400. }
  5401.  
  5402. here = lcode[hold & lmask];
  5403.  
  5404. dolen:
  5405. for (;;) { // Goto emulation
  5406. op = here >>> 24/*here.bits*/;
  5407. hold >>>= op;
  5408. bits -= op;
  5409. op = (here >>> 16) & 0xff/*here.op*/;
  5410. if (op === 0) { /* literal */
  5411. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  5412. // "inflate: literal '%c'\n" :
  5413. // "inflate: literal 0x%02x\n", here.val));
  5414. output[_out++] = here & 0xffff/*here.val*/;
  5415. }
  5416. else if (op & 16) { /* length base */
  5417. len = here & 0xffff/*here.val*/;
  5418. op &= 15; /* number of extra bits */
  5419. if (op) {
  5420. if (bits < op) {
  5421. hold += input[_in++] << bits;
  5422. bits += 8;
  5423. }
  5424. len += hold & ((1 << op) - 1);
  5425. hold >>>= op;
  5426. bits -= op;
  5427. }
  5428. //Tracevv((stderr, "inflate: length %u\n", len));
  5429. if (bits < 15) {
  5430. hold += input[_in++] << bits;
  5431. bits += 8;
  5432. hold += input[_in++] << bits;
  5433. bits += 8;
  5434. }
  5435. here = dcode[hold & dmask];
  5436.  
  5437. dodist:
  5438. for (;;) { // goto emulation
  5439. op = here >>> 24/*here.bits*/;
  5440. hold >>>= op;
  5441. bits -= op;
  5442. op = (here >>> 16) & 0xff/*here.op*/;
  5443.  
  5444. if (op & 16) { /* distance base */
  5445. dist = here & 0xffff/*here.val*/;
  5446. op &= 15; /* number of extra bits */
  5447. if (bits < op) {
  5448. hold += input[_in++] << bits;
  5449. bits += 8;
  5450. if (bits < op) {
  5451. hold += input[_in++] << bits;
  5452. bits += 8;
  5453. }
  5454. }
  5455. dist += hold & ((1 << op) - 1);
  5456. //#ifdef INFLATE_STRICT
  5457. if (dist > dmax) {
  5458. strm.msg = 'invalid distance too far back';
  5459. state.mode = BAD;
  5460. break top;
  5461. }
  5462. //#endif
  5463. hold >>>= op;
  5464. bits -= op;
  5465. //Tracevv((stderr, "inflate: distance %u\n", dist));
  5466. op = _out - beg; /* max distance in output */
  5467. if (dist > op) { /* see if copy from window */
  5468. op = dist - op; /* distance back in window */
  5469. if (op > whave) {
  5470. if (state.sane) {
  5471. strm.msg = 'invalid distance too far back';
  5472. state.mode = BAD;
  5473. break top;
  5474. }
  5475.  
  5476. // (!) This block is disabled in zlib defailts,
  5477. // don't enable it for binary compatibility
  5478. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  5479. // if (len <= op - whave) {
  5480. // do {
  5481. // output[_out++] = 0;
  5482. // } while (--len);
  5483. // continue top;
  5484. // }
  5485. // len -= op - whave;
  5486. // do {
  5487. // output[_out++] = 0;
  5488. // } while (--op > whave);
  5489. // if (op === 0) {
  5490. // from = _out - dist;
  5491. // do {
  5492. // output[_out++] = output[from++];
  5493. // } while (--len);
  5494. // continue top;
  5495. // }
  5496. //#endif
  5497. }
  5498. from = 0; // window index
  5499. from_source = s_window;
  5500. if (wnext === 0) { /* very common case */
  5501. from += wsize - op;
  5502. if (op < len) { /* some from window */
  5503. len -= op;
  5504. do {
  5505. output[_out++] = s_window[from++];
  5506. } while (--op);
  5507. from = _out - dist; /* rest from output */
  5508. from_source = output;
  5509. }
  5510. }
  5511. else if (wnext < op) { /* wrap around window */
  5512. from += wsize + wnext - op;
  5513. op -= wnext;
  5514. if (op < len) { /* some from end of window */
  5515. len -= op;
  5516. do {
  5517. output[_out++] = s_window[from++];
  5518. } while (--op);
  5519. from = 0;
  5520. if (wnext < len) { /* some from start of window */
  5521. op = wnext;
  5522. len -= op;
  5523. do {
  5524. output[_out++] = s_window[from++];
  5525. } while (--op);
  5526. from = _out - dist; /* rest from output */
  5527. from_source = output;
  5528. }
  5529. }
  5530. }
  5531. else { /* contiguous in window */
  5532. from += wnext - op;
  5533. if (op < len) { /* some from window */
  5534. len -= op;
  5535. do {
  5536. output[_out++] = s_window[from++];
  5537. } while (--op);
  5538. from = _out - dist; /* rest from output */
  5539. from_source = output;
  5540. }
  5541. }
  5542. while (len > 2) {
  5543. output[_out++] = from_source[from++];
  5544. output[_out++] = from_source[from++];
  5545. output[_out++] = from_source[from++];
  5546. len -= 3;
  5547. }
  5548. if (len) {
  5549. output[_out++] = from_source[from++];
  5550. if (len > 1) {
  5551. output[_out++] = from_source[from++];
  5552. }
  5553. }
  5554. }
  5555. else {
  5556. from = _out - dist; /* copy direct from output */
  5557. do { /* minimum length is three */
  5558. output[_out++] = output[from++];
  5559. output[_out++] = output[from++];
  5560. output[_out++] = output[from++];
  5561. len -= 3;
  5562. } while (len > 2);
  5563. if (len) {
  5564. output[_out++] = output[from++];
  5565. if (len > 1) {
  5566. output[_out++] = output[from++];
  5567. }
  5568. }
  5569. }
  5570. }
  5571. else if ((op & 64) === 0) { /* 2nd level distance code */
  5572. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  5573. continue dodist;
  5574. }
  5575. else {
  5576. strm.msg = 'invalid distance code';
  5577. state.mode = BAD;
  5578. break top;
  5579. }
  5580.  
  5581. break; // need to emulate goto via "continue"
  5582. }
  5583. }
  5584. else if ((op & 64) === 0) { /* 2nd level length code */
  5585. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  5586. continue dolen;
  5587. }
  5588. else if (op & 32) { /* end-of-block */
  5589. //Tracevv((stderr, "inflate: end of block\n"));
  5590. state.mode = TYPE;
  5591. break top;
  5592. }
  5593. else {
  5594. strm.msg = 'invalid literal/length code';
  5595. state.mode = BAD;
  5596. break top;
  5597. }
  5598.  
  5599. break; // need to emulate goto via "continue"
  5600. }
  5601. } while (_in < last && _out < end);
  5602.  
  5603. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  5604. len = bits >> 3;
  5605. _in -= len;
  5606. bits -= len << 3;
  5607. hold &= (1 << bits) - 1;
  5608.  
  5609. /* update state and return */
  5610. strm.next_in = _in;
  5611. strm.next_out = _out;
  5612. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  5613. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  5614. state.hold = hold;
  5615. state.bits = bits;
  5616. return;
  5617. };
  5618.  
  5619. },{}],28:[function(require,module,exports){
  5620. 'use strict';
  5621.  
  5622.  
  5623. var utils = require('../utils/common');
  5624. var adler32 = require('./adler32');
  5625. var crc32 = require('./crc32');
  5626. var inflate_fast = require('./inffast');
  5627. var inflate_table = require('./inftrees');
  5628.  
  5629. var CODES = 0;
  5630. var LENS = 1;
  5631. var DISTS = 2;
  5632.  
  5633. /* Public constants ==========================================================*/
  5634. /* ===========================================================================*/
  5635.  
  5636.  
  5637. /* Allowed flush values; see deflate() and inflate() below for details */
  5638. //var Z_NO_FLUSH = 0;
  5639. //var Z_PARTIAL_FLUSH = 1;
  5640. //var Z_SYNC_FLUSH = 2;
  5641. //var Z_FULL_FLUSH = 3;
  5642. var Z_FINISH = 4;
  5643. var Z_BLOCK = 5;
  5644. var Z_TREES = 6;
  5645.  
  5646.  
  5647. /* Return codes for the compression/decompression functions. Negative values
  5648. * are errors, positive values are used for special but normal events.
  5649. */
  5650. var Z_OK = 0;
  5651. var Z_STREAM_END = 1;
  5652. var Z_NEED_DICT = 2;
  5653. //var Z_ERRNO = -1;
  5654. var Z_STREAM_ERROR = -2;
  5655. var Z_DATA_ERROR = -3;
  5656. var Z_MEM_ERROR = -4;
  5657. var Z_BUF_ERROR = -5;
  5658. //var Z_VERSION_ERROR = -6;
  5659.  
  5660. /* The deflate compression method */
  5661. var Z_DEFLATED = 8;
  5662.  
  5663.  
  5664. /* STATES ====================================================================*/
  5665. /* ===========================================================================*/
  5666.  
  5667.  
  5668. var HEAD = 1; /* i: waiting for magic header */
  5669. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  5670. var TIME = 3; /* i: waiting for modification time (gzip) */
  5671. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  5672. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  5673. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  5674. var NAME = 7; /* i: waiting for end of file name (gzip) */
  5675. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  5676. var HCRC = 9; /* i: waiting for header crc (gzip) */
  5677. var DICTID = 10; /* i: waiting for dictionary check value */
  5678. var DICT = 11; /* waiting for inflateSetDictionary() call */
  5679. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  5680. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  5681. var STORED = 14; /* i: waiting for stored size (length and complement) */
  5682. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  5683. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  5684. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  5685. var LENLENS = 18; /* i: waiting for code length code lengths */
  5686. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  5687. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  5688. var LEN = 21; /* i: waiting for length/lit/eob code */
  5689. var LENEXT = 22; /* i: waiting for length extra bits */
  5690. var DIST = 23; /* i: waiting for distance code */
  5691. var DISTEXT = 24; /* i: waiting for distance extra bits */
  5692. var MATCH = 25; /* o: waiting for output space to copy string */
  5693. var LIT = 26; /* o: waiting for output space to write literal */
  5694. var CHECK = 27; /* i: waiting for 32-bit check value */
  5695. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  5696. var DONE = 29; /* finished check, done -- remain here until reset */
  5697. var BAD = 30; /* got a data error -- remain here until reset */
  5698. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  5699. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  5700.  
  5701. /* ===========================================================================*/
  5702.  
  5703.  
  5704.  
  5705. var ENOUGH_LENS = 852;
  5706. var ENOUGH_DISTS = 592;
  5707. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  5708.  
  5709. var MAX_WBITS = 15;
  5710. /* 32K LZ77 window */
  5711. var DEF_WBITS = MAX_WBITS;
  5712.  
  5713.  
  5714. function zswap32(q) {
  5715. return (((q >>> 24) & 0xff) +
  5716. ((q >>> 8) & 0xff00) +
  5717. ((q & 0xff00) << 8) +
  5718. ((q & 0xff) << 24));
  5719. }
  5720.  
  5721.  
  5722. function InflateState() {
  5723. this.mode = 0; /* current inflate mode */
  5724. this.last = false; /* true if processing last block */
  5725. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  5726. this.havedict = false; /* true if dictionary provided */
  5727. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  5728. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  5729. this.check = 0; /* protected copy of check value */
  5730. this.total = 0; /* protected copy of output count */
  5731. // TODO: may be {}
  5732. this.head = null; /* where to save gzip header information */
  5733.  
  5734. /* sliding window */
  5735. this.wbits = 0; /* log base 2 of requested window size */
  5736. this.wsize = 0; /* window size or zero if not using window */
  5737. this.whave = 0; /* valid bytes in the window */
  5738. this.wnext = 0; /* window write index */
  5739. this.window = null; /* allocated sliding window, if needed */
  5740.  
  5741. /* bit accumulator */
  5742. this.hold = 0; /* input bit accumulator */
  5743. this.bits = 0; /* number of bits in "in" */
  5744.  
  5745. /* for string and stored block copying */
  5746. this.length = 0; /* literal or length of data to copy */
  5747. this.offset = 0; /* distance back to copy string from */
  5748.  
  5749. /* for table and code decoding */
  5750. this.extra = 0; /* extra bits needed */
  5751.  
  5752. /* fixed and dynamic code tables */
  5753. this.lencode = null; /* starting table for length/literal codes */
  5754. this.distcode = null; /* starting table for distance codes */
  5755. this.lenbits = 0; /* index bits for lencode */
  5756. this.distbits = 0; /* index bits for distcode */
  5757.  
  5758. /* dynamic table building */
  5759. this.ncode = 0; /* number of code length code lengths */
  5760. this.nlen = 0; /* number of length code lengths */
  5761. this.ndist = 0; /* number of distance code lengths */
  5762. this.have = 0; /* number of code lengths in lens[] */
  5763. this.next = null; /* next available space in codes[] */
  5764.  
  5765. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  5766. this.work = new utils.Buf16(288); /* work area for code table building */
  5767.  
  5768. /*
  5769. because we don't have pointers in js, we use lencode and distcode directly
  5770. as buffers so we don't need codes
  5771. */
  5772. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  5773. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  5774. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  5775. this.sane = 0; /* if false, allow invalid distance too far */
  5776. this.back = 0; /* bits back of last unprocessed length/lit */
  5777. this.was = 0; /* initial length of match */
  5778. }
  5779.  
  5780. function inflateResetKeep(strm) {
  5781. var state;
  5782.  
  5783. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  5784. state = strm.state;
  5785. strm.total_in = strm.total_out = state.total = 0;
  5786. strm.msg = ''; /*Z_NULL*/
  5787. if (state.wrap) { /* to support ill-conceived Java test suite */
  5788. strm.adler = state.wrap & 1;
  5789. }
  5790. state.mode = HEAD;
  5791. state.last = 0;
  5792. state.havedict = 0;
  5793. state.dmax = 32768;
  5794. state.head = null/*Z_NULL*/;
  5795. state.hold = 0;
  5796. state.bits = 0;
  5797. //state.lencode = state.distcode = state.next = state.codes;
  5798. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  5799. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  5800.  
  5801. state.sane = 1;
  5802. state.back = -1;
  5803. //Tracev((stderr, "inflate: reset\n"));
  5804. return Z_OK;
  5805. }
  5806.  
  5807. function inflateReset(strm) {
  5808. var state;
  5809.  
  5810. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  5811. state = strm.state;
  5812. state.wsize = 0;
  5813. state.whave = 0;
  5814. state.wnext = 0;
  5815. return inflateResetKeep(strm);
  5816.  
  5817. }
  5818.  
  5819. function inflateReset2(strm, windowBits) {
  5820. var wrap;
  5821. var state;
  5822.  
  5823. /* get the state */
  5824. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  5825. state = strm.state;
  5826.  
  5827. /* extract wrap request from windowBits parameter */
  5828. if (windowBits < 0) {
  5829. wrap = 0;
  5830. windowBits = -windowBits;
  5831. }
  5832. else {
  5833. wrap = (windowBits >> 4) + 1;
  5834. if (windowBits < 48) {
  5835. windowBits &= 15;
  5836. }
  5837. }
  5838.  
  5839. /* set number of window bits, free window if different */
  5840. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  5841. return Z_STREAM_ERROR;
  5842. }
  5843. if (state.window !== null && state.wbits !== windowBits) {
  5844. state.window = null;
  5845. }
  5846.  
  5847. /* update state and reset the rest of it */
  5848. state.wrap = wrap;
  5849. state.wbits = windowBits;
  5850. return inflateReset(strm);
  5851. }
  5852.  
  5853. function inflateInit2(strm, windowBits) {
  5854. var ret;
  5855. var state;
  5856.  
  5857. if (!strm) { return Z_STREAM_ERROR; }
  5858. //strm.msg = Z_NULL; /* in case we return an error */
  5859.  
  5860. state = new InflateState();
  5861.  
  5862. //if (state === Z_NULL) return Z_MEM_ERROR;
  5863. //Tracev((stderr, "inflate: allocated\n"));
  5864. strm.state = state;
  5865. state.window = null/*Z_NULL*/;
  5866. ret = inflateReset2(strm, windowBits);
  5867. if (ret !== Z_OK) {
  5868. strm.state = null/*Z_NULL*/;
  5869. }
  5870. return ret;
  5871. }
  5872.  
  5873. function inflateInit(strm) {
  5874. return inflateInit2(strm, DEF_WBITS);
  5875. }
  5876.  
  5877.  
  5878. /*
  5879. Return state with length and distance decoding tables and index sizes set to
  5880. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  5881. If BUILDFIXED is defined, then instead this routine builds the tables the
  5882. first time it's called, and returns those tables the first time and
  5883. thereafter. This reduces the size of the code by about 2K bytes, in
  5884. exchange for a little execution time. However, BUILDFIXED should not be
  5885. used for threaded applications, since the rewriting of the tables and virgin
  5886. may not be thread-safe.
  5887. */
  5888. var virgin = true;
  5889.  
  5890. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  5891.  
  5892. function fixedtables(state) {
  5893. /* build fixed huffman tables if first call (may not be thread safe) */
  5894. if (virgin) {
  5895. var sym;
  5896.  
  5897. lenfix = new utils.Buf32(512);
  5898. distfix = new utils.Buf32(32);
  5899.  
  5900. /* literal/length table */
  5901. sym = 0;
  5902. while (sym < 144) { state.lens[sym++] = 8; }
  5903. while (sym < 256) { state.lens[sym++] = 9; }
  5904. while (sym < 280) { state.lens[sym++] = 7; }
  5905. while (sym < 288) { state.lens[sym++] = 8; }
  5906.  
  5907. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
  5908.  
  5909. /* distance table */
  5910. sym = 0;
  5911. while (sym < 32) { state.lens[sym++] = 5; }
  5912.  
  5913. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
  5914.  
  5915. /* do this just once */
  5916. virgin = false;
  5917. }
  5918.  
  5919. state.lencode = lenfix;
  5920. state.lenbits = 9;
  5921. state.distcode = distfix;
  5922. state.distbits = 5;
  5923. }
  5924.  
  5925.  
  5926. /*
  5927. Update the window with the last wsize (normally 32K) bytes written before
  5928. returning. If window does not exist yet, create it. This is only called
  5929. when a window is already in use, or when output has been written during this
  5930. inflate call, but the end of the deflate stream has not been reached yet.
  5931. It is also called to create a window for dictionary data when a dictionary
  5932. is loaded.
  5933.  
  5934. Providing output buffers larger than 32K to inflate() should provide a speed
  5935. advantage, since only the last 32K of output is copied to the sliding window
  5936. upon return from inflate(), and since all distances after the first 32K of
  5937. output will fall in the output data, making match copies simpler and faster.
  5938. The advantage may be dependent on the size of the processor's data caches.
  5939. */
  5940. function updatewindow(strm, src, end, copy) {
  5941. var dist;
  5942. var state = strm.state;
  5943.  
  5944. /* if it hasn't been done already, allocate space for the window */
  5945. if (state.window === null) {
  5946. state.wsize = 1 << state.wbits;
  5947. state.wnext = 0;
  5948. state.whave = 0;
  5949.  
  5950. state.window = new utils.Buf8(state.wsize);
  5951. }
  5952.  
  5953. /* copy state->wsize or less output bytes into the circular window */
  5954. if (copy >= state.wsize) {
  5955. utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
  5956. state.wnext = 0;
  5957. state.whave = state.wsize;
  5958. }
  5959. else {
  5960. dist = state.wsize - state.wnext;
  5961. if (dist > copy) {
  5962. dist = copy;
  5963. }
  5964. //zmemcpy(state->window + state->wnext, end - copy, dist);
  5965. utils.arraySet(state.window, src, end - copy, dist, state.wnext);
  5966. copy -= dist;
  5967. if (copy) {
  5968. //zmemcpy(state->window, end - copy, copy);
  5969. utils.arraySet(state.window, src, end - copy, copy, 0);
  5970. state.wnext = copy;
  5971. state.whave = state.wsize;
  5972. }
  5973. else {
  5974. state.wnext += dist;
  5975. if (state.wnext === state.wsize) { state.wnext = 0; }
  5976. if (state.whave < state.wsize) { state.whave += dist; }
  5977. }
  5978. }
  5979. return 0;
  5980. }
  5981.  
  5982. function inflate(strm, flush) {
  5983. var state;
  5984. var input, output; // input/output buffers
  5985. var next; /* next input INDEX */
  5986. var put; /* next output INDEX */
  5987. var have, left; /* available input and output */
  5988. var hold; /* bit buffer */
  5989. var bits; /* bits in bit buffer */
  5990. var _in, _out; /* save starting available input and output */
  5991. var copy; /* number of stored or match bytes to copy */
  5992. var from; /* where to copy match bytes from */
  5993. var from_source;
  5994. var here = 0; /* current decoding table entry */
  5995. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  5996. //var last; /* parent table entry */
  5997. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  5998. var len; /* length to copy for repeats, bits to drop */
  5999. var ret; /* return code */
  6000. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  6001. var opts;
  6002.  
  6003. var n; // temporary var for NEED_BITS
  6004.  
  6005. var order = /* permutation of code lengths */
  6006. [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
  6007.  
  6008.  
  6009. if (!strm || !strm.state || !strm.output ||
  6010. (!strm.input && strm.avail_in !== 0)) {
  6011. return Z_STREAM_ERROR;
  6012. }
  6013.  
  6014. state = strm.state;
  6015. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  6016.  
  6017.  
  6018. //--- LOAD() ---
  6019. put = strm.next_out;
  6020. output = strm.output;
  6021. left = strm.avail_out;
  6022. next = strm.next_in;
  6023. input = strm.input;
  6024. have = strm.avail_in;
  6025. hold = state.hold;
  6026. bits = state.bits;
  6027. //---
  6028.  
  6029. _in = have;
  6030. _out = left;
  6031. ret = Z_OK;
  6032.  
  6033. inf_leave: // goto emulation
  6034. for (;;) {
  6035. switch (state.mode) {
  6036. case HEAD:
  6037. if (state.wrap === 0) {
  6038. state.mode = TYPEDO;
  6039. break;
  6040. }
  6041. //=== NEEDBITS(16);
  6042. while (bits < 16) {
  6043. if (have === 0) { break inf_leave; }
  6044. have--;
  6045. hold += input[next++] << bits;
  6046. bits += 8;
  6047. }
  6048. //===//
  6049. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  6050. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  6051. //=== CRC2(state.check, hold);
  6052. hbuf[0] = hold & 0xff;
  6053. hbuf[1] = (hold >>> 8) & 0xff;
  6054. state.check = crc32(state.check, hbuf, 2, 0);
  6055. //===//
  6056.  
  6057. //=== INITBITS();
  6058. hold = 0;
  6059. bits = 0;
  6060. //===//
  6061. state.mode = FLAGS;
  6062. break;
  6063. }
  6064. state.flags = 0; /* expect zlib header */
  6065. if (state.head) {
  6066. state.head.done = false;
  6067. }
  6068. if (!(state.wrap & 1) || /* check if zlib header allowed */
  6069. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  6070. strm.msg = 'incorrect header check';
  6071. state.mode = BAD;
  6072. break;
  6073. }
  6074. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  6075. strm.msg = 'unknown compression method';
  6076. state.mode = BAD;
  6077. break;
  6078. }
  6079. //--- DROPBITS(4) ---//
  6080. hold >>>= 4;
  6081. bits -= 4;
  6082. //---//
  6083. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  6084. if (state.wbits === 0) {
  6085. state.wbits = len;
  6086. }
  6087. else if (len > state.wbits) {
  6088. strm.msg = 'invalid window size';
  6089. state.mode = BAD;
  6090. break;
  6091. }
  6092. state.dmax = 1 << len;
  6093. //Tracev((stderr, "inflate: zlib header ok\n"));
  6094. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  6095. state.mode = hold & 0x200 ? DICTID : TYPE;
  6096. //=== INITBITS();
  6097. hold = 0;
  6098. bits = 0;
  6099. //===//
  6100. break;
  6101. case FLAGS:
  6102. //=== NEEDBITS(16); */
  6103. while (bits < 16) {
  6104. if (have === 0) { break inf_leave; }
  6105. have--;
  6106. hold += input[next++] << bits;
  6107. bits += 8;
  6108. }
  6109. //===//
  6110. state.flags = hold;
  6111. if ((state.flags & 0xff) !== Z_DEFLATED) {
  6112. strm.msg = 'unknown compression method';
  6113. state.mode = BAD;
  6114. break;
  6115. }
  6116. if (state.flags & 0xe000) {
  6117. strm.msg = 'unknown header flags set';
  6118. state.mode = BAD;
  6119. break;
  6120. }
  6121. if (state.head) {
  6122. state.head.text = ((hold >> 8) & 1);
  6123. }
  6124. if (state.flags & 0x0200) {
  6125. //=== CRC2(state.check, hold);
  6126. hbuf[0] = hold & 0xff;
  6127. hbuf[1] = (hold >>> 8) & 0xff;
  6128. state.check = crc32(state.check, hbuf, 2, 0);
  6129. //===//
  6130. }
  6131. //=== INITBITS();
  6132. hold = 0;
  6133. bits = 0;
  6134. //===//
  6135. state.mode = TIME;
  6136. /* falls through */
  6137. case TIME:
  6138. //=== NEEDBITS(32); */
  6139. while (bits < 32) {
  6140. if (have === 0) { break inf_leave; }
  6141. have--;
  6142. hold += input[next++] << bits;
  6143. bits += 8;
  6144. }
  6145. //===//
  6146. if (state.head) {
  6147. state.head.time = hold;
  6148. }
  6149. if (state.flags & 0x0200) {
  6150. //=== CRC4(state.check, hold)
  6151. hbuf[0] = hold & 0xff;
  6152. hbuf[1] = (hold >>> 8) & 0xff;
  6153. hbuf[2] = (hold >>> 16) & 0xff;
  6154. hbuf[3] = (hold >>> 24) & 0xff;
  6155. state.check = crc32(state.check, hbuf, 4, 0);
  6156. //===
  6157. }
  6158. //=== INITBITS();
  6159. hold = 0;
  6160. bits = 0;
  6161. //===//
  6162. state.mode = OS;
  6163. /* falls through */
  6164. case OS:
  6165. //=== NEEDBITS(16); */
  6166. while (bits < 16) {
  6167. if (have === 0) { break inf_leave; }
  6168. have--;
  6169. hold += input[next++] << bits;
  6170. bits += 8;
  6171. }
  6172. //===//
  6173. if (state.head) {
  6174. state.head.xflags = (hold & 0xff);
  6175. state.head.os = (hold >> 8);
  6176. }
  6177. if (state.flags & 0x0200) {
  6178. //=== CRC2(state.check, hold);
  6179. hbuf[0] = hold & 0xff;
  6180. hbuf[1] = (hold >>> 8) & 0xff;
  6181. state.check = crc32(state.check, hbuf, 2, 0);
  6182. //===//
  6183. }
  6184. //=== INITBITS();
  6185. hold = 0;
  6186. bits = 0;
  6187. //===//
  6188. state.mode = EXLEN;
  6189. /* falls through */
  6190. case EXLEN:
  6191. if (state.flags & 0x0400) {
  6192. //=== NEEDBITS(16); */
  6193. while (bits < 16) {
  6194. if (have === 0) { break inf_leave; }
  6195. have--;
  6196. hold += input[next++] << bits;
  6197. bits += 8;
  6198. }
  6199. //===//
  6200. state.length = hold;
  6201. if (state.head) {
  6202. state.head.extra_len = hold;
  6203. }
  6204. if (state.flags & 0x0200) {
  6205. //=== CRC2(state.check, hold);
  6206. hbuf[0] = hold & 0xff;
  6207. hbuf[1] = (hold >>> 8) & 0xff;
  6208. state.check = crc32(state.check, hbuf, 2, 0);
  6209. //===//
  6210. }
  6211. //=== INITBITS();
  6212. hold = 0;
  6213. bits = 0;
  6214. //===//
  6215. }
  6216. else if (state.head) {
  6217. state.head.extra = null/*Z_NULL*/;
  6218. }
  6219. state.mode = EXTRA;
  6220. /* falls through */
  6221. case EXTRA:
  6222. if (state.flags & 0x0400) {
  6223. copy = state.length;
  6224. if (copy > have) { copy = have; }
  6225. if (copy) {
  6226. if (state.head) {
  6227. len = state.head.extra_len - state.length;
  6228. if (!state.head.extra) {
  6229. // Use untyped array for more conveniend processing later
  6230. state.head.extra = new Array(state.head.extra_len);
  6231. }
  6232. utils.arraySet(
  6233. state.head.extra,
  6234. input,
  6235. next,
  6236. // extra field is limited to 65536 bytes
  6237. // - no need for additional size check
  6238. copy,
  6239. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  6240. len
  6241. );
  6242. //zmemcpy(state.head.extra + len, next,
  6243. // len + copy > state.head.extra_max ?
  6244. // state.head.extra_max - len : copy);
  6245. }
  6246. if (state.flags & 0x0200) {
  6247. state.check = crc32(state.check, input, copy, next);
  6248. }
  6249. have -= copy;
  6250. next += copy;
  6251. state.length -= copy;
  6252. }
  6253. if (state.length) { break inf_leave; }
  6254. }
  6255. state.length = 0;
  6256. state.mode = NAME;
  6257. /* falls through */
  6258. case NAME:
  6259. if (state.flags & 0x0800) {
  6260. if (have === 0) { break inf_leave; }
  6261. copy = 0;
  6262. do {
  6263. // TODO: 2 or 1 bytes?
  6264. len = input[next + copy++];
  6265. /* use constant limit because in js we should not preallocate memory */
  6266. if (state.head && len &&
  6267. (state.length < 65536 /*state.head.name_max*/)) {
  6268. state.head.name += String.fromCharCode(len);
  6269. }
  6270. } while (len && copy < have);
  6271.  
  6272. if (state.flags & 0x0200) {
  6273. state.check = crc32(state.check, input, copy, next);
  6274. }
  6275. have -= copy;
  6276. next += copy;
  6277. if (len) { break inf_leave; }
  6278. }
  6279. else if (state.head) {
  6280. state.head.name = null;
  6281. }
  6282. state.length = 0;
  6283. state.mode = COMMENT;
  6284. /* falls through */
  6285. case COMMENT:
  6286. if (state.flags & 0x1000) {
  6287. if (have === 0) { break inf_leave; }
  6288. copy = 0;
  6289. do {
  6290. len = input[next + copy++];
  6291. /* use constant limit because in js we should not preallocate memory */
  6292. if (state.head && len &&
  6293. (state.length < 65536 /*state.head.comm_max*/)) {
  6294. state.head.comment += String.fromCharCode(len);
  6295. }
  6296. } while (len && copy < have);
  6297. if (state.flags & 0x0200) {
  6298. state.check = crc32(state.check, input, copy, next);
  6299. }
  6300. have -= copy;
  6301. next += copy;
  6302. if (len) { break inf_leave; }
  6303. }
  6304. else if (state.head) {
  6305. state.head.comment = null;
  6306. }
  6307. state.mode = HCRC;
  6308. /* falls through */
  6309. case HCRC:
  6310. if (state.flags & 0x0200) {
  6311. //=== NEEDBITS(16); */
  6312. while (bits < 16) {
  6313. if (have === 0) { break inf_leave; }
  6314. have--;
  6315. hold += input[next++] << bits;
  6316. bits += 8;
  6317. }
  6318. //===//
  6319. if (hold !== (state.check & 0xffff)) {
  6320. strm.msg = 'header crc mismatch';
  6321. state.mode = BAD;
  6322. break;
  6323. }
  6324. //=== INITBITS();
  6325. hold = 0;
  6326. bits = 0;
  6327. //===//
  6328. }
  6329. if (state.head) {
  6330. state.head.hcrc = ((state.flags >> 9) & 1);
  6331. state.head.done = true;
  6332. }
  6333. strm.adler = state.check = 0;
  6334. state.mode = TYPE;
  6335. break;
  6336. case DICTID:
  6337. //=== NEEDBITS(32); */
  6338. while (bits < 32) {
  6339. if (have === 0) { break inf_leave; }
  6340. have--;
  6341. hold += input[next++] << bits;
  6342. bits += 8;
  6343. }
  6344. //===//
  6345. strm.adler = state.check = zswap32(hold);
  6346. //=== INITBITS();
  6347. hold = 0;
  6348. bits = 0;
  6349. //===//
  6350. state.mode = DICT;
  6351. /* falls through */
  6352. case DICT:
  6353. if (state.havedict === 0) {
  6354. //--- RESTORE() ---
  6355. strm.next_out = put;
  6356. strm.avail_out = left;
  6357. strm.next_in = next;
  6358. strm.avail_in = have;
  6359. state.hold = hold;
  6360. state.bits = bits;
  6361. //---
  6362. return Z_NEED_DICT;
  6363. }
  6364. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  6365. state.mode = TYPE;
  6366. /* falls through */
  6367. case TYPE:
  6368. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  6369. /* falls through */
  6370. case TYPEDO:
  6371. if (state.last) {
  6372. //--- BYTEBITS() ---//
  6373. hold >>>= bits & 7;
  6374. bits -= bits & 7;
  6375. //---//
  6376. state.mode = CHECK;
  6377. break;
  6378. }
  6379. //=== NEEDBITS(3); */
  6380. while (bits < 3) {
  6381. if (have === 0) { break inf_leave; }
  6382. have--;
  6383. hold += input[next++] << bits;
  6384. bits += 8;
  6385. }
  6386. //===//
  6387. state.last = (hold & 0x01)/*BITS(1)*/;
  6388. //--- DROPBITS(1) ---//
  6389. hold >>>= 1;
  6390. bits -= 1;
  6391. //---//
  6392.  
  6393. switch ((hold & 0x03)/*BITS(2)*/) {
  6394. case 0: /* stored block */
  6395. //Tracev((stderr, "inflate: stored block%s\n",
  6396. // state.last ? " (last)" : ""));
  6397. state.mode = STORED;
  6398. break;
  6399. case 1: /* fixed block */
  6400. fixedtables(state);
  6401. //Tracev((stderr, "inflate: fixed codes block%s\n",
  6402. // state.last ? " (last)" : ""));
  6403. state.mode = LEN_; /* decode codes */
  6404. if (flush === Z_TREES) {
  6405. //--- DROPBITS(2) ---//
  6406. hold >>>= 2;
  6407. bits -= 2;
  6408. //---//
  6409. break inf_leave;
  6410. }
  6411. break;
  6412. case 2: /* dynamic block */
  6413. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  6414. // state.last ? " (last)" : ""));
  6415. state.mode = TABLE;
  6416. break;
  6417. case 3:
  6418. strm.msg = 'invalid block type';
  6419. state.mode = BAD;
  6420. }
  6421. //--- DROPBITS(2) ---//
  6422. hold >>>= 2;
  6423. bits -= 2;
  6424. //---//
  6425. break;
  6426. case STORED:
  6427. //--- BYTEBITS() ---// /* go to byte boundary */
  6428. hold >>>= bits & 7;
  6429. bits -= bits & 7;
  6430. //---//
  6431. //=== NEEDBITS(32); */
  6432. while (bits < 32) {
  6433. if (have === 0) { break inf_leave; }
  6434. have--;
  6435. hold += input[next++] << bits;
  6436. bits += 8;
  6437. }
  6438. //===//
  6439. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  6440. strm.msg = 'invalid stored block lengths';
  6441. state.mode = BAD;
  6442. break;
  6443. }
  6444. state.length = hold & 0xffff;
  6445. //Tracev((stderr, "inflate: stored length %u\n",
  6446. // state.length));
  6447. //=== INITBITS();
  6448. hold = 0;
  6449. bits = 0;
  6450. //===//
  6451. state.mode = COPY_;
  6452. if (flush === Z_TREES) { break inf_leave; }
  6453. /* falls through */
  6454. case COPY_:
  6455. state.mode = COPY;
  6456. /* falls through */
  6457. case COPY:
  6458. copy = state.length;
  6459. if (copy) {
  6460. if (copy > have) { copy = have; }
  6461. if (copy > left) { copy = left; }
  6462. if (copy === 0) { break inf_leave; }
  6463. //--- zmemcpy(put, next, copy); ---
  6464. utils.arraySet(output, input, next, copy, put);
  6465. //---//
  6466. have -= copy;
  6467. next += copy;
  6468. left -= copy;
  6469. put += copy;
  6470. state.length -= copy;
  6471. break;
  6472. }
  6473. //Tracev((stderr, "inflate: stored end\n"));
  6474. state.mode = TYPE;
  6475. break;
  6476. case TABLE:
  6477. //=== NEEDBITS(14); */
  6478. while (bits < 14) {
  6479. if (have === 0) { break inf_leave; }
  6480. have--;
  6481. hold += input[next++] << bits;
  6482. bits += 8;
  6483. }
  6484. //===//
  6485. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  6486. //--- DROPBITS(5) ---//
  6487. hold >>>= 5;
  6488. bits -= 5;
  6489. //---//
  6490. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  6491. //--- DROPBITS(5) ---//
  6492. hold >>>= 5;
  6493. bits -= 5;
  6494. //---//
  6495. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  6496. //--- DROPBITS(4) ---//
  6497. hold >>>= 4;
  6498. bits -= 4;
  6499. //---//
  6500. //#ifndef PKZIP_BUG_WORKAROUND
  6501. if (state.nlen > 286 || state.ndist > 30) {
  6502. strm.msg = 'too many length or distance symbols';
  6503. state.mode = BAD;
  6504. break;
  6505. }
  6506. //#endif
  6507. //Tracev((stderr, "inflate: table sizes ok\n"));
  6508. state.have = 0;
  6509. state.mode = LENLENS;
  6510. /* falls through */
  6511. case LENLENS:
  6512. while (state.have < state.ncode) {
  6513. //=== NEEDBITS(3);
  6514. while (bits < 3) {
  6515. if (have === 0) { break inf_leave; }
  6516. have--;
  6517. hold += input[next++] << bits;
  6518. bits += 8;
  6519. }
  6520. //===//
  6521. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  6522. //--- DROPBITS(3) ---//
  6523. hold >>>= 3;
  6524. bits -= 3;
  6525. //---//
  6526. }
  6527. while (state.have < 19) {
  6528. state.lens[order[state.have++]] = 0;
  6529. }
  6530. // We have separate tables & no pointers. 2 commented lines below not needed.
  6531. //state.next = state.codes;
  6532. //state.lencode = state.next;
  6533. // Switch to use dynamic table
  6534. state.lencode = state.lendyn;
  6535. state.lenbits = 7;
  6536.  
  6537. opts = { bits: state.lenbits };
  6538. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  6539. state.lenbits = opts.bits;
  6540.  
  6541. if (ret) {
  6542. strm.msg = 'invalid code lengths set';
  6543. state.mode = BAD;
  6544. break;
  6545. }
  6546. //Tracev((stderr, "inflate: code lengths ok\n"));
  6547. state.have = 0;
  6548. state.mode = CODELENS;
  6549. /* falls through */
  6550. case CODELENS:
  6551. while (state.have < state.nlen + state.ndist) {
  6552. for (;;) {
  6553. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  6554. here_bits = here >>> 24;
  6555. here_op = (here >>> 16) & 0xff;
  6556. here_val = here & 0xffff;
  6557.  
  6558. if ((here_bits) <= bits) { break; }
  6559. //--- PULLBYTE() ---//
  6560. if (have === 0) { break inf_leave; }
  6561. have--;
  6562. hold += input[next++] << bits;
  6563. bits += 8;
  6564. //---//
  6565. }
  6566. if (here_val < 16) {
  6567. //--- DROPBITS(here.bits) ---//
  6568. hold >>>= here_bits;
  6569. bits -= here_bits;
  6570. //---//
  6571. state.lens[state.have++] = here_val;
  6572. }
  6573. else {
  6574. if (here_val === 16) {
  6575. //=== NEEDBITS(here.bits + 2);
  6576. n = here_bits + 2;
  6577. while (bits < n) {
  6578. if (have === 0) { break inf_leave; }
  6579. have--;
  6580. hold += input[next++] << bits;
  6581. bits += 8;
  6582. }
  6583. //===//
  6584. //--- DROPBITS(here.bits) ---//
  6585. hold >>>= here_bits;
  6586. bits -= here_bits;
  6587. //---//
  6588. if (state.have === 0) {
  6589. strm.msg = 'invalid bit length repeat';
  6590. state.mode = BAD;
  6591. break;
  6592. }
  6593. len = state.lens[state.have - 1];
  6594. copy = 3 + (hold & 0x03);//BITS(2);
  6595. //--- DROPBITS(2) ---//
  6596. hold >>>= 2;
  6597. bits -= 2;
  6598. //---//
  6599. }
  6600. else if (here_val === 17) {
  6601. //=== NEEDBITS(here.bits + 3);
  6602. n = here_bits + 3;
  6603. while (bits < n) {
  6604. if (have === 0) { break inf_leave; }
  6605. have--;
  6606. hold += input[next++] << bits;
  6607. bits += 8;
  6608. }
  6609. //===//
  6610. //--- DROPBITS(here.bits) ---//
  6611. hold >>>= here_bits;
  6612. bits -= here_bits;
  6613. //---//
  6614. len = 0;
  6615. copy = 3 + (hold & 0x07);//BITS(3);
  6616. //--- DROPBITS(3) ---//
  6617. hold >>>= 3;
  6618. bits -= 3;
  6619. //---//
  6620. }
  6621. else {
  6622. //=== NEEDBITS(here.bits + 7);
  6623. n = here_bits + 7;
  6624. while (bits < n) {
  6625. if (have === 0) { break inf_leave; }
  6626. have--;
  6627. hold += input[next++] << bits;
  6628. bits += 8;
  6629. }
  6630. //===//
  6631. //--- DROPBITS(here.bits) ---//
  6632. hold >>>= here_bits;
  6633. bits -= here_bits;
  6634. //---//
  6635. len = 0;
  6636. copy = 11 + (hold & 0x7f);//BITS(7);
  6637. //--- DROPBITS(7) ---//
  6638. hold >>>= 7;
  6639. bits -= 7;
  6640. //---//
  6641. }
  6642. if (state.have + copy > state.nlen + state.ndist) {
  6643. strm.msg = 'invalid bit length repeat';
  6644. state.mode = BAD;
  6645. break;
  6646. }
  6647. while (copy--) {
  6648. state.lens[state.have++] = len;
  6649. }
  6650. }
  6651. }
  6652.  
  6653. /* handle error breaks in while */
  6654. if (state.mode === BAD) { break; }
  6655.  
  6656. /* check for end-of-block code (better have one) */
  6657. if (state.lens[256] === 0) {
  6658. strm.msg = 'invalid code -- missing end-of-block';
  6659. state.mode = BAD;
  6660. break;
  6661. }
  6662.  
  6663. /* build code tables -- note: do not change the lenbits or distbits
  6664. values here (9 and 6) without reading the comments in inftrees.h
  6665. concerning the ENOUGH constants, which depend on those values */
  6666. state.lenbits = 9;
  6667.  
  6668. opts = { bits: state.lenbits };
  6669. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  6670. // We have separate tables & no pointers. 2 commented lines below not needed.
  6671. // state.next_index = opts.table_index;
  6672. state.lenbits = opts.bits;
  6673. // state.lencode = state.next;
  6674.  
  6675. if (ret) {
  6676. strm.msg = 'invalid literal/lengths set';
  6677. state.mode = BAD;
  6678. break;
  6679. }
  6680.  
  6681. state.distbits = 6;
  6682. //state.distcode.copy(state.codes);
  6683. // Switch to use dynamic table
  6684. state.distcode = state.distdyn;
  6685. opts = { bits: state.distbits };
  6686. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  6687. // We have separate tables & no pointers. 2 commented lines below not needed.
  6688. // state.next_index = opts.table_index;
  6689. state.distbits = opts.bits;
  6690. // state.distcode = state.next;
  6691.  
  6692. if (ret) {
  6693. strm.msg = 'invalid distances set';
  6694. state.mode = BAD;
  6695. break;
  6696. }
  6697. //Tracev((stderr, 'inflate: codes ok\n'));
  6698. state.mode = LEN_;
  6699. if (flush === Z_TREES) { break inf_leave; }
  6700. /* falls through */
  6701. case LEN_:
  6702. state.mode = LEN;
  6703. /* falls through */
  6704. case LEN:
  6705. if (have >= 6 && left >= 258) {
  6706. //--- RESTORE() ---
  6707. strm.next_out = put;
  6708. strm.avail_out = left;
  6709. strm.next_in = next;
  6710. strm.avail_in = have;
  6711. state.hold = hold;
  6712. state.bits = bits;
  6713. //---
  6714. inflate_fast(strm, _out);
  6715. //--- LOAD() ---
  6716. put = strm.next_out;
  6717. output = strm.output;
  6718. left = strm.avail_out;
  6719. next = strm.next_in;
  6720. input = strm.input;
  6721. have = strm.avail_in;
  6722. hold = state.hold;
  6723. bits = state.bits;
  6724. //---
  6725.  
  6726. if (state.mode === TYPE) {
  6727. state.back = -1;
  6728. }
  6729. break;
  6730. }
  6731. state.back = 0;
  6732. for (;;) {
  6733. here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/
  6734. here_bits = here >>> 24;
  6735. here_op = (here >>> 16) & 0xff;
  6736. here_val = here & 0xffff;
  6737.  
  6738. if (here_bits <= bits) { break; }
  6739. //--- PULLBYTE() ---//
  6740. if (have === 0) { break inf_leave; }
  6741. have--;
  6742. hold += input[next++] << bits;
  6743. bits += 8;
  6744. //---//
  6745. }
  6746. if (here_op && (here_op & 0xf0) === 0) {
  6747. last_bits = here_bits;
  6748. last_op = here_op;
  6749. last_val = here_val;
  6750. for (;;) {
  6751. here = state.lencode[last_val +
  6752. ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  6753. here_bits = here >>> 24;
  6754. here_op = (here >>> 16) & 0xff;
  6755. here_val = here & 0xffff;
  6756.  
  6757. if ((last_bits + here_bits) <= bits) { break; }
  6758. //--- PULLBYTE() ---//
  6759. if (have === 0) { break inf_leave; }
  6760. have--;
  6761. hold += input[next++] << bits;
  6762. bits += 8;
  6763. //---//
  6764. }
  6765. //--- DROPBITS(last.bits) ---//
  6766. hold >>>= last_bits;
  6767. bits -= last_bits;
  6768. //---//
  6769. state.back += last_bits;
  6770. }
  6771. //--- DROPBITS(here.bits) ---//
  6772. hold >>>= here_bits;
  6773. bits -= here_bits;
  6774. //---//
  6775. state.back += here_bits;
  6776. state.length = here_val;
  6777. if (here_op === 0) {
  6778. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  6779. // "inflate: literal '%c'\n" :
  6780. // "inflate: literal 0x%02x\n", here.val));
  6781. state.mode = LIT;
  6782. break;
  6783. }
  6784. if (here_op & 32) {
  6785. //Tracevv((stderr, "inflate: end of block\n"));
  6786. state.back = -1;
  6787. state.mode = TYPE;
  6788. break;
  6789. }
  6790. if (here_op & 64) {
  6791. strm.msg = 'invalid literal/length code';
  6792. state.mode = BAD;
  6793. break;
  6794. }
  6795. state.extra = here_op & 15;
  6796. state.mode = LENEXT;
  6797. /* falls through */
  6798. case LENEXT:
  6799. if (state.extra) {
  6800. //=== NEEDBITS(state.extra);
  6801. n = state.extra;
  6802. while (bits < n) {
  6803. if (have === 0) { break inf_leave; }
  6804. have--;
  6805. hold += input[next++] << bits;
  6806. bits += 8;
  6807. }
  6808. //===//
  6809. state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  6810. //--- DROPBITS(state.extra) ---//
  6811. hold >>>= state.extra;
  6812. bits -= state.extra;
  6813. //---//
  6814. state.back += state.extra;
  6815. }
  6816. //Tracevv((stderr, "inflate: length %u\n", state.length));
  6817. state.was = state.length;
  6818. state.mode = DIST;
  6819. /* falls through */
  6820. case DIST:
  6821. for (;;) {
  6822. here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
  6823. here_bits = here >>> 24;
  6824. here_op = (here >>> 16) & 0xff;
  6825. here_val = here & 0xffff;
  6826.  
  6827. if ((here_bits) <= bits) { break; }
  6828. //--- PULLBYTE() ---//
  6829. if (have === 0) { break inf_leave; }
  6830. have--;
  6831. hold += input[next++] << bits;
  6832. bits += 8;
  6833. //---//
  6834. }
  6835. if ((here_op & 0xf0) === 0) {
  6836. last_bits = here_bits;
  6837. last_op = here_op;
  6838. last_val = here_val;
  6839. for (;;) {
  6840. here = state.distcode[last_val +
  6841. ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  6842. here_bits = here >>> 24;
  6843. here_op = (here >>> 16) & 0xff;
  6844. here_val = here & 0xffff;
  6845.  
  6846. if ((last_bits + here_bits) <= bits) { break; }
  6847. //--- PULLBYTE() ---//
  6848. if (have === 0) { break inf_leave; }
  6849. have--;
  6850. hold += input[next++] << bits;
  6851. bits += 8;
  6852. //---//
  6853. }
  6854. //--- DROPBITS(last.bits) ---//
  6855. hold >>>= last_bits;
  6856. bits -= last_bits;
  6857. //---//
  6858. state.back += last_bits;
  6859. }
  6860. //--- DROPBITS(here.bits) ---//
  6861. hold >>>= here_bits;
  6862. bits -= here_bits;
  6863. //---//
  6864. state.back += here_bits;
  6865. if (here_op & 64) {
  6866. strm.msg = 'invalid distance code';
  6867. state.mode = BAD;
  6868. break;
  6869. }
  6870. state.offset = here_val;
  6871. state.extra = (here_op) & 15;
  6872. state.mode = DISTEXT;
  6873. /* falls through */
  6874. case DISTEXT:
  6875. if (state.extra) {
  6876. //=== NEEDBITS(state.extra);
  6877. n = state.extra;
  6878. while (bits < n) {
  6879. if (have === 0) { break inf_leave; }
  6880. have--;
  6881. hold += input[next++] << bits;
  6882. bits += 8;
  6883. }
  6884. //===//
  6885. state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  6886. //--- DROPBITS(state.extra) ---//
  6887. hold >>>= state.extra;
  6888. bits -= state.extra;
  6889. //---//
  6890. state.back += state.extra;
  6891. }
  6892. //#ifdef INFLATE_STRICT
  6893. if (state.offset > state.dmax) {
  6894. strm.msg = 'invalid distance too far back';
  6895. state.mode = BAD;
  6896. break;
  6897. }
  6898. //#endif
  6899. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  6900. state.mode = MATCH;
  6901. /* falls through */
  6902. case MATCH:
  6903. if (left === 0) { break inf_leave; }
  6904. copy = _out - left;
  6905. if (state.offset > copy) { /* copy from window */
  6906. copy = state.offset - copy;
  6907. if (copy > state.whave) {
  6908. if (state.sane) {
  6909. strm.msg = 'invalid distance too far back';
  6910. state.mode = BAD;
  6911. break;
  6912. }
  6913. // (!) This block is disabled in zlib defailts,
  6914. // don't enable it for binary compatibility
  6915. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  6916. // Trace((stderr, "inflate.c too far\n"));
  6917. // copy -= state.whave;
  6918. // if (copy > state.length) { copy = state.length; }
  6919. // if (copy > left) { copy = left; }
  6920. // left -= copy;
  6921. // state.length -= copy;
  6922. // do {
  6923. // output[put++] = 0;
  6924. // } while (--copy);
  6925. // if (state.length === 0) { state.mode = LEN; }
  6926. // break;
  6927. //#endif
  6928. }
  6929. if (copy > state.wnext) {
  6930. copy -= state.wnext;
  6931. from = state.wsize - copy;
  6932. }
  6933. else {
  6934. from = state.wnext - copy;
  6935. }
  6936. if (copy > state.length) { copy = state.length; }
  6937. from_source = state.window;
  6938. }
  6939. else { /* copy from output */
  6940. from_source = output;
  6941. from = put - state.offset;
  6942. copy = state.length;
  6943. }
  6944. if (copy > left) { copy = left; }
  6945. left -= copy;
  6946. state.length -= copy;
  6947. do {
  6948. output[put++] = from_source[from++];
  6949. } while (--copy);
  6950. if (state.length === 0) { state.mode = LEN; }
  6951. break;
  6952. case LIT:
  6953. if (left === 0) { break inf_leave; }
  6954. output[put++] = state.length;
  6955. left--;
  6956. state.mode = LEN;
  6957. break;
  6958. case CHECK:
  6959. if (state.wrap) {
  6960. //=== NEEDBITS(32);
  6961. while (bits < 32) {
  6962. if (have === 0) { break inf_leave; }
  6963. have--;
  6964. // Use '|' insdead of '+' to make sure that result is signed
  6965. hold |= input[next++] << bits;
  6966. bits += 8;
  6967. }
  6968. //===//
  6969. _out -= left;
  6970. strm.total_out += _out;
  6971. state.total += _out;
  6972. if (_out) {
  6973. strm.adler = state.check =
  6974. /*UPDATE(state.check, put - _out, _out);*/
  6975. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  6976.  
  6977. }
  6978. _out = left;
  6979. // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
  6980. if ((state.flags ? hold : zswap32(hold)) !== state.check) {
  6981. strm.msg = 'incorrect data check';
  6982. state.mode = BAD;
  6983. break;
  6984. }
  6985. //=== INITBITS();
  6986. hold = 0;
  6987. bits = 0;
  6988. //===//
  6989. //Tracev((stderr, "inflate: check matches trailer\n"));
  6990. }
  6991. state.mode = LENGTH;
  6992. /* falls through */
  6993. case LENGTH:
  6994. if (state.wrap && state.flags) {
  6995. //=== NEEDBITS(32);
  6996. while (bits < 32) {
  6997. if (have === 0) { break inf_leave; }
  6998. have--;
  6999. hold += input[next++] << bits;
  7000. bits += 8;
  7001. }
  7002. //===//
  7003. if (hold !== (state.total & 0xffffffff)) {
  7004. strm.msg = 'incorrect length check';
  7005. state.mode = BAD;
  7006. break;
  7007. }
  7008. //=== INITBITS();
  7009. hold = 0;
  7010. bits = 0;
  7011. //===//
  7012. //Tracev((stderr, "inflate: length matches trailer\n"));
  7013. }
  7014. state.mode = DONE;
  7015. /* falls through */
  7016. case DONE:
  7017. ret = Z_STREAM_END;
  7018. break inf_leave;
  7019. case BAD:
  7020. ret = Z_DATA_ERROR;
  7021. break inf_leave;
  7022. case MEM:
  7023. return Z_MEM_ERROR;
  7024. case SYNC:
  7025. /* falls through */
  7026. default:
  7027. return Z_STREAM_ERROR;
  7028. }
  7029. }
  7030.  
  7031. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  7032.  
  7033. /*
  7034. Return from inflate(), updating the total counts and the check value.
  7035. If there was no progress during the inflate() call, return a buffer
  7036. error. Call updatewindow() to create and/or update the window state.
  7037. Note: a memory error from inflate() is non-recoverable.
  7038. */
  7039.  
  7040. //--- RESTORE() ---
  7041. strm.next_out = put;
  7042. strm.avail_out = left;
  7043. strm.next_in = next;
  7044. strm.avail_in = have;
  7045. state.hold = hold;
  7046. state.bits = bits;
  7047. //---
  7048.  
  7049. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  7050. (state.mode < CHECK || flush !== Z_FINISH))) {
  7051. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  7052. state.mode = MEM;
  7053. return Z_MEM_ERROR;
  7054. }
  7055. }
  7056. _in -= strm.avail_in;
  7057. _out -= strm.avail_out;
  7058. strm.total_in += _in;
  7059. strm.total_out += _out;
  7060. state.total += _out;
  7061. if (state.wrap && _out) {
  7062. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  7063. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  7064. }
  7065. strm.data_type = state.bits + (state.last ? 64 : 0) +
  7066. (state.mode === TYPE ? 128 : 0) +
  7067. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  7068. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  7069. ret = Z_BUF_ERROR;
  7070. }
  7071. return ret;
  7072. }
  7073.  
  7074. function inflateEnd(strm) {
  7075.  
  7076. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  7077. return Z_STREAM_ERROR;
  7078. }
  7079.  
  7080. var state = strm.state;
  7081. if (state.window) {
  7082. state.window = null;
  7083. }
  7084. strm.state = null;
  7085. return Z_OK;
  7086. }
  7087.  
  7088. function inflateGetHeader(strm, head) {
  7089. var state;
  7090.  
  7091. /* check state */
  7092. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  7093. state = strm.state;
  7094. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  7095.  
  7096. /* save header structure */
  7097. state.head = head;
  7098. head.done = false;
  7099. return Z_OK;
  7100. }
  7101.  
  7102. function inflateSetDictionary(strm, dictionary) {
  7103. var dictLength = dictionary.length;
  7104.  
  7105. var state;
  7106. var dictid;
  7107. var ret;
  7108.  
  7109. /* check state */
  7110. if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
  7111. state = strm.state;
  7112.  
  7113. if (state.wrap !== 0 && state.mode !== DICT) {
  7114. return Z_STREAM_ERROR;
  7115. }
  7116.  
  7117. /* check for correct dictionary identifier */
  7118. if (state.mode === DICT) {
  7119. dictid = 1; /* adler32(0, null, 0)*/
  7120. /* dictid = adler32(dictid, dictionary, dictLength); */
  7121. dictid = adler32(dictid, dictionary, dictLength, 0);
  7122. if (dictid !== state.check) {
  7123. return Z_DATA_ERROR;
  7124. }
  7125. }
  7126. /* copy dictionary to window using updatewindow(), which will amend the
  7127. existing dictionary if appropriate */
  7128. ret = updatewindow(strm, dictionary, dictLength, dictLength);
  7129. if (ret) {
  7130. state.mode = MEM;
  7131. return Z_MEM_ERROR;
  7132. }
  7133. state.havedict = 1;
  7134. // Tracev((stderr, "inflate: dictionary set\n"));
  7135. return Z_OK;
  7136. }
  7137.  
  7138. exports.inflateReset = inflateReset;
  7139. exports.inflateReset2 = inflateReset2;
  7140. exports.inflateResetKeep = inflateResetKeep;
  7141. exports.inflateInit = inflateInit;
  7142. exports.inflateInit2 = inflateInit2;
  7143. exports.inflate = inflate;
  7144. exports.inflateEnd = inflateEnd;
  7145. exports.inflateGetHeader = inflateGetHeader;
  7146. exports.inflateSetDictionary = inflateSetDictionary;
  7147. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  7148.  
  7149. /* Not implemented
  7150. exports.inflateCopy = inflateCopy;
  7151. exports.inflateGetDictionary = inflateGetDictionary;
  7152. exports.inflateMark = inflateMark;
  7153. exports.inflatePrime = inflatePrime;
  7154. exports.inflateSync = inflateSync;
  7155. exports.inflateSyncPoint = inflateSyncPoint;
  7156. exports.inflateUndermine = inflateUndermine;
  7157. */
  7158.  
  7159. },{"../utils/common":21,"./adler32":23,"./crc32":25,"./inffast":27,"./inftrees":29}],29:[function(require,module,exports){
  7160. 'use strict';
  7161.  
  7162.  
  7163. var utils = require('../utils/common');
  7164.  
  7165. var MAXBITS = 15;
  7166. var ENOUGH_LENS = 852;
  7167. var ENOUGH_DISTS = 592;
  7168. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  7169.  
  7170. var CODES = 0;
  7171. var LENS = 1;
  7172. var DISTS = 2;
  7173.  
  7174. var lbase = [ /* Length codes 257..285 base */
  7175. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  7176. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  7177. ];
  7178.  
  7179. var lext = [ /* Length codes 257..285 extra */
  7180. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  7181. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  7182. ];
  7183.  
  7184. var dbase = [ /* Distance codes 0..29 base */
  7185. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  7186. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  7187. 8193, 12289, 16385, 24577, 0, 0
  7188. ];
  7189.  
  7190. var dext = [ /* Distance codes 0..29 extra */
  7191. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  7192. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  7193. 28, 28, 29, 29, 64, 64
  7194. ];
  7195.  
  7196. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  7197. {
  7198. var bits = opts.bits;
  7199. //here = opts.here; /* table entry for duplication */
  7200.  
  7201. var len = 0; /* a code's length in bits */
  7202. var sym = 0; /* index of code symbols */
  7203. var min = 0, max = 0; /* minimum and maximum code lengths */
  7204. var root = 0; /* number of index bits for root table */
  7205. var curr = 0; /* number of index bits for current table */
  7206. var drop = 0; /* code bits to drop for sub-table */
  7207. var left = 0; /* number of prefix codes available */
  7208. var used = 0; /* code entries in table used */
  7209. var huff = 0; /* Huffman code */
  7210. var incr; /* for incrementing code, index */
  7211. var fill; /* index for replicating entries */
  7212. var low; /* low bits for current root entry */
  7213. var mask; /* mask for low root bits */
  7214. var next; /* next available space in table */
  7215. var base = null; /* base value table to use */
  7216. var base_index = 0;
  7217. // var shoextra; /* extra bits table to use */
  7218. var end; /* use base and extra for symbol > end */
  7219. var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
  7220. var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
  7221. var extra = null;
  7222. var extra_index = 0;
  7223.  
  7224. var here_bits, here_op, here_val;
  7225.  
  7226. /*
  7227. Process a set of code lengths to create a canonical Huffman code. The
  7228. code lengths are lens[0..codes-1]. Each length corresponds to the
  7229. symbols 0..codes-1. The Huffman code is generated by first sorting the
  7230. symbols by length from short to long, and retaining the symbol order
  7231. for codes with equal lengths. Then the code starts with all zero bits
  7232. for the first code of the shortest length, and the codes are integer
  7233. increments for the same length, and zeros are appended as the length
  7234. increases. For the deflate format, these bits are stored backwards
  7235. from their more natural integer increment ordering, and so when the
  7236. decoding tables are built in the large loop below, the integer codes
  7237. are incremented backwards.
  7238.  
  7239. This routine assumes, but does not check, that all of the entries in
  7240. lens[] are in the range 0..MAXBITS. The caller must assure this.
  7241. 1..MAXBITS is interpreted as that code length. zero means that that
  7242. symbol does not occur in this code.
  7243.  
  7244. The codes are sorted by computing a count of codes for each length,
  7245. creating from that a table of starting indices for each length in the
  7246. sorted table, and then entering the symbols in order in the sorted
  7247. table. The sorted table is work[], with that space being provided by
  7248. the caller.
  7249.  
  7250. The length counts are used for other purposes as well, i.e. finding
  7251. the minimum and maximum length codes, determining if there are any
  7252. codes at all, checking for a valid set of lengths, and looking ahead
  7253. at length counts to determine sub-table sizes when building the
  7254. decoding tables.
  7255. */
  7256.  
  7257. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  7258. for (len = 0; len <= MAXBITS; len++) {
  7259. count[len] = 0;
  7260. }
  7261. for (sym = 0; sym < codes; sym++) {
  7262. count[lens[lens_index + sym]]++;
  7263. }
  7264.  
  7265. /* bound code lengths, force root to be within code lengths */
  7266. root = bits;
  7267. for (max = MAXBITS; max >= 1; max--) {
  7268. if (count[max] !== 0) { break; }
  7269. }
  7270. if (root > max) {
  7271. root = max;
  7272. }
  7273. if (max === 0) { /* no symbols to code at all */
  7274. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  7275. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  7276. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  7277. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  7278.  
  7279.  
  7280. //table.op[opts.table_index] = 64;
  7281. //table.bits[opts.table_index] = 1;
  7282. //table.val[opts.table_index++] = 0;
  7283. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  7284.  
  7285. opts.bits = 1;
  7286. return 0; /* no symbols, but wait for decoding to report error */
  7287. }
  7288. for (min = 1; min < max; min++) {
  7289. if (count[min] !== 0) { break; }
  7290. }
  7291. if (root < min) {
  7292. root = min;
  7293. }
  7294.  
  7295. /* check for an over-subscribed or incomplete set of lengths */
  7296. left = 1;
  7297. for (len = 1; len <= MAXBITS; len++) {
  7298. left <<= 1;
  7299. left -= count[len];
  7300. if (left < 0) {
  7301. return -1;
  7302. } /* over-subscribed */
  7303. }
  7304. if (left > 0 && (type === CODES || max !== 1)) {
  7305. return -1; /* incomplete set */
  7306. }
  7307.  
  7308. /* generate offsets into symbol table for each length for sorting */
  7309. offs[1] = 0;
  7310. for (len = 1; len < MAXBITS; len++) {
  7311. offs[len + 1] = offs[len] + count[len];
  7312. }
  7313.  
  7314. /* sort symbols by length, by symbol order within each length */
  7315. for (sym = 0; sym < codes; sym++) {
  7316. if (lens[lens_index + sym] !== 0) {
  7317. work[offs[lens[lens_index + sym]]++] = sym;
  7318. }
  7319. }
  7320.  
  7321. /*
  7322. Create and fill in decoding tables. In this loop, the table being
  7323. filled is at next and has curr index bits. The code being used is huff
  7324. with length len. That code is converted to an index by dropping drop
  7325. bits off of the bottom. For codes where len is less than drop + curr,
  7326. those top drop + curr - len bits are incremented through all values to
  7327. fill the table with replicated entries.
  7328.  
  7329. root is the number of index bits for the root table. When len exceeds
  7330. root, sub-tables are created pointed to by the root entry with an index
  7331. of the low root bits of huff. This is saved in low to check for when a
  7332. new sub-table should be started. drop is zero when the root table is
  7333. being filled, and drop is root when sub-tables are being filled.
  7334.  
  7335. When a new sub-table is needed, it is necessary to look ahead in the
  7336. code lengths to determine what size sub-table is needed. The length
  7337. counts are used for this, and so count[] is decremented as codes are
  7338. entered in the tables.
  7339.  
  7340. used keeps track of how many table entries have been allocated from the
  7341. provided *table space. It is checked for LENS and DIST tables against
  7342. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  7343. the initial root table size constants. See the comments in inftrees.h
  7344. for more information.
  7345.  
  7346. sym increments through all symbols, and the loop terminates when
  7347. all codes of length max, i.e. all codes, have been processed. This
  7348. routine permits incomplete codes, so another loop after this one fills
  7349. in the rest of the decoding tables with invalid code markers.
  7350. */
  7351.  
  7352. /* set up for code type */
  7353. // poor man optimization - use if-else instead of switch,
  7354. // to avoid deopts in old v8
  7355. if (type === CODES) {
  7356. base = extra = work; /* dummy value--not used */
  7357. end = 19;
  7358.  
  7359. } else if (type === LENS) {
  7360. base = lbase;
  7361. base_index -= 257;
  7362. extra = lext;
  7363. extra_index -= 257;
  7364. end = 256;
  7365.  
  7366. } else { /* DISTS */
  7367. base = dbase;
  7368. extra = dext;
  7369. end = -1;
  7370. }
  7371.  
  7372. /* initialize opts for loop */
  7373. huff = 0; /* starting code */
  7374. sym = 0; /* starting code symbol */
  7375. len = min; /* starting code length */
  7376. next = table_index; /* current table to fill in */
  7377. curr = root; /* current table index bits */
  7378. drop = 0; /* current bits to drop from code for index */
  7379. low = -1; /* trigger new sub-table when len > root */
  7380. used = 1 << root; /* use root table entries */
  7381. mask = used - 1; /* mask for comparing low */
  7382.  
  7383. /* check available table space */
  7384. if ((type === LENS && used > ENOUGH_LENS) ||
  7385. (type === DISTS && used > ENOUGH_DISTS)) {
  7386. return 1;
  7387. }
  7388.  
  7389. var i = 0;
  7390. /* process all codes and make table entries */
  7391. for (;;) {
  7392. i++;
  7393. /* create table entry */
  7394. here_bits = len - drop;
  7395. if (work[sym] < end) {
  7396. here_op = 0;
  7397. here_val = work[sym];
  7398. }
  7399. else if (work[sym] > end) {
  7400. here_op = extra[extra_index + work[sym]];
  7401. here_val = base[base_index + work[sym]];
  7402. }
  7403. else {
  7404. here_op = 32 + 64; /* end of block */
  7405. here_val = 0;
  7406. }
  7407.  
  7408. /* replicate for those indices with low len bits equal to huff */
  7409. incr = 1 << (len - drop);
  7410. fill = 1 << curr;
  7411. min = fill; /* save offset to next table */
  7412. do {
  7413. fill -= incr;
  7414. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  7415. } while (fill !== 0);
  7416.  
  7417. /* backwards increment the len-bit code huff */
  7418. incr = 1 << (len - 1);
  7419. while (huff & incr) {
  7420. incr >>= 1;
  7421. }
  7422. if (incr !== 0) {
  7423. huff &= incr - 1;
  7424. huff += incr;
  7425. } else {
  7426. huff = 0;
  7427. }
  7428.  
  7429. /* go to next symbol, update count, len */
  7430. sym++;
  7431. if (--count[len] === 0) {
  7432. if (len === max) { break; }
  7433. len = lens[lens_index + work[sym]];
  7434. }
  7435.  
  7436. /* create new sub-table if needed */
  7437. if (len > root && (huff & mask) !== low) {
  7438. /* if first time, transition to sub-tables */
  7439. if (drop === 0) {
  7440. drop = root;
  7441. }
  7442.  
  7443. /* increment past last table */
  7444. next += min; /* here min is 1 << curr */
  7445.  
  7446. /* determine length of next table */
  7447. curr = len - drop;
  7448. left = 1 << curr;
  7449. while (curr + drop < max) {
  7450. left -= count[curr + drop];
  7451. if (left <= 0) { break; }
  7452. curr++;
  7453. left <<= 1;
  7454. }
  7455.  
  7456. /* check for enough space */
  7457. used += 1 << curr;
  7458. if ((type === LENS && used > ENOUGH_LENS) ||
  7459. (type === DISTS && used > ENOUGH_DISTS)) {
  7460. return 1;
  7461. }
  7462.  
  7463. /* point entry in root table to sub-table */
  7464. low = huff & mask;
  7465. /*table.op[low] = curr;
  7466. table.bits[low] = root;
  7467. table.val[low] = next - opts.table_index;*/
  7468. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  7469. }
  7470. }
  7471.  
  7472. /* fill in remaining table entry if code is incomplete (guaranteed to have
  7473. at most one remaining entry, since if the code is incomplete, the
  7474. maximum code length that was allowed to get this far is one bit) */
  7475. if (huff !== 0) {
  7476. //table.op[next + huff] = 64; /* invalid code marker */
  7477. //table.bits[next + huff] = len - drop;
  7478. //table.val[next + huff] = 0;
  7479. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  7480. }
  7481.  
  7482. /* set return parameters */
  7483. //opts.table_index += used;
  7484. opts.bits = root;
  7485. return 0;
  7486. };
  7487.  
  7488. },{"../utils/common":21}],30:[function(require,module,exports){
  7489. 'use strict';
  7490.  
  7491. module.exports = {
  7492. 2: 'need dictionary', /* Z_NEED_DICT 2 */
  7493. 1: 'stream end', /* Z_STREAM_END 1 */
  7494. 0: '', /* Z_OK 0 */
  7495. '-1': 'file error', /* Z_ERRNO (-1) */
  7496. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  7497. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  7498. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  7499. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  7500. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  7501. };
  7502.  
  7503. },{}],31:[function(require,module,exports){
  7504. 'use strict';
  7505.  
  7506.  
  7507. function ZStream() {
  7508. /* next input byte */
  7509. this.input = null; // JS specific, because we have no pointers
  7510. this.next_in = 0;
  7511. /* number of bytes available at input */
  7512. this.avail_in = 0;
  7513. /* total number of input bytes read so far */
  7514. this.total_in = 0;
  7515. /* next output byte should be put there */
  7516. this.output = null; // JS specific, because we have no pointers
  7517. this.next_out = 0;
  7518. /* remaining free space at output */
  7519. this.avail_out = 0;
  7520. /* total number of bytes output so far */
  7521. this.total_out = 0;
  7522. /* last error message, NULL if no error */
  7523. this.msg = ''/*Z_NULL*/;
  7524. /* not visible by applications */
  7525. this.state = null;
  7526. /* best guess about the data type: binary or text */
  7527. this.data_type = 2/*Z_UNKNOWN*/;
  7528. /* adler32 value of the uncompressed data */
  7529. this.adler = 0;
  7530. }
  7531.  
  7532. module.exports = ZStream;
  7533.  
  7534. },{}],32:[function(require,module,exports){
  7535. // shim for using process in browser
  7536. var process = module.exports = {};
  7537.  
  7538. // cached from whatever global is present so that test runners that stub it
  7539. // don't break things. But we need to wrap it in a try catch in case it is
  7540. // wrapped in strict mode code which doesn't define any globals. It's inside a
  7541. // function because try/catches deoptimize in certain engines.
  7542.  
  7543. var cachedSetTimeout;
  7544. var cachedClearTimeout;
  7545.  
  7546. function defaultSetTimout() {
  7547. throw new Error('setTimeout has not been defined');
  7548. }
  7549. function defaultClearTimeout () {
  7550. throw new Error('clearTimeout has not been defined');
  7551. }
  7552. (function () {
  7553. try {
  7554. if (typeof setTimeout === 'function') {
  7555. cachedSetTimeout = setTimeout;
  7556. } else {
  7557. cachedSetTimeout = defaultSetTimout;
  7558. }
  7559. } catch (e) {
  7560. cachedSetTimeout = defaultSetTimout;
  7561. }
  7562. try {
  7563. if (typeof clearTimeout === 'function') {
  7564. cachedClearTimeout = clearTimeout;
  7565. } else {
  7566. cachedClearTimeout = defaultClearTimeout;
  7567. }
  7568. } catch (e) {
  7569. cachedClearTimeout = defaultClearTimeout;
  7570. }
  7571. } ())
  7572. function runTimeout(fun) {
  7573. if (cachedSetTimeout === setTimeout) {
  7574. //normal enviroments in sane situations
  7575. return setTimeout(fun, 0);
  7576. }
  7577. // if setTimeout wasn't available but was latter defined
  7578. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  7579. cachedSetTimeout = setTimeout;
  7580. return setTimeout(fun, 0);
  7581. }
  7582. try {
  7583. // when when somebody has screwed with setTimeout but no I.E. maddness
  7584. return cachedSetTimeout(fun, 0);
  7585. } catch(e){
  7586. try {
  7587. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  7588. return cachedSetTimeout.call(null, fun, 0);
  7589. } catch(e){
  7590. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  7591. return cachedSetTimeout.call(this, fun, 0);
  7592. }
  7593. }
  7594.  
  7595.  
  7596. }
  7597. function runClearTimeout(marker) {
  7598. if (cachedClearTimeout === clearTimeout) {
  7599. //normal enviroments in sane situations
  7600. return clearTimeout(marker);
  7601. }
  7602. // if clearTimeout wasn't available but was latter defined
  7603. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  7604. cachedClearTimeout = clearTimeout;
  7605. return clearTimeout(marker);
  7606. }
  7607. try {
  7608. // when when somebody has screwed with setTimeout but no I.E. maddness
  7609. return cachedClearTimeout(marker);
  7610. } catch (e){
  7611. try {
  7612. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  7613. return cachedClearTimeout.call(null, marker);
  7614. } catch (e){
  7615. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  7616. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  7617. return cachedClearTimeout.call(this, marker);
  7618. }
  7619. }
  7620.  
  7621.  
  7622.  
  7623. }
  7624. var queue = [];
  7625. var draining = false;
  7626. var currentQueue;
  7627. var queueIndex = -1;
  7628.  
  7629. function cleanUpNextTick() {
  7630. if (!draining || !currentQueue) {
  7631. return;
  7632. }
  7633. draining = false;
  7634. if (currentQueue.length) {
  7635. queue = currentQueue.concat(queue);
  7636. } else {
  7637. queueIndex = -1;
  7638. }
  7639. if (queue.length) {
  7640. drainQueue();
  7641. }
  7642. }
  7643.  
  7644. function drainQueue() {
  7645. if (draining) {
  7646. return;
  7647. }
  7648. var timeout = runTimeout(cleanUpNextTick);
  7649. draining = true;
  7650.  
  7651. var len = queue.length;
  7652. while(len) {
  7653. currentQueue = queue;
  7654. queue = [];
  7655. while (++queueIndex < len) {
  7656. if (currentQueue) {
  7657. currentQueue[queueIndex].run();
  7658. }
  7659. }
  7660. queueIndex = -1;
  7661. len = queue.length;
  7662. }
  7663. currentQueue = null;
  7664. draining = false;
  7665. runClearTimeout(timeout);
  7666. }
  7667.  
  7668. process.nextTick = function (fun) {
  7669. var args = new Array(arguments.length - 1);
  7670. if (arguments.length > 1) {
  7671. for (var i = 1; i < arguments.length; i++) {
  7672. args[i - 1] = arguments[i];
  7673. }
  7674. }
  7675. queue.push(new Item(fun, args));
  7676. if (queue.length === 1 && !draining) {
  7677. runTimeout(drainQueue);
  7678. }
  7679. };
  7680.  
  7681. // v8 likes predictible objects
  7682. function Item(fun, array) {
  7683. this.fun = fun;
  7684. this.array = array;
  7685. }
  7686. Item.prototype.run = function () {
  7687. this.fun.apply(null, this.array);
  7688. };
  7689. process.title = 'browser';
  7690. process.browser = true;
  7691. process.env = {};
  7692. process.argv = [];
  7693. process.version = ''; // empty string to avoid regexp issues
  7694. process.versions = {};
  7695.  
  7696. function noop() {}
  7697.  
  7698. process.on = noop;
  7699. process.addListener = noop;
  7700. process.once = noop;
  7701. process.off = noop;
  7702. process.removeListener = noop;
  7703. process.removeAllListeners = noop;
  7704. process.emit = noop;
  7705.  
  7706. process.binding = function (name) {
  7707. throw new Error('process.binding is not supported');
  7708. };
  7709.  
  7710. process.cwd = function () { return '/' };
  7711. process.chdir = function (dir) {
  7712. throw new Error('process.chdir is not supported');
  7713. };
  7714. process.umask = function() { return 0; };
  7715.  
  7716. },{}],33:[function(require,module,exports){
  7717. (function (Buffer){
  7718. /**
  7719. * Convert a typed array to a Buffer without a copy
  7720. *
  7721. * Author: Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  7722. * License: MIT
  7723. *
  7724. * `npm install typedarray-to-buffer`
  7725. */
  7726.  
  7727. module.exports = function (arr) {
  7728. if (typeof Buffer._augment === 'function' && Buffer.TYPED_ARRAY_SUPPORT) {
  7729. // If `Buffer` is from the `buffer` module and this browser supports typed arrays,
  7730. // then augment it with all the `Buffer` methods.
  7731. return Buffer._augment(arr)
  7732. } else {
  7733. // Otherwise, fallback to creating a `Buffer` with a copy.
  7734. return new Buffer(arr)
  7735. }
  7736. }
  7737.  
  7738. }).call(this,require("buffer").Buffer)
  7739. },{"buffer":6}],34:[function(require,module,exports){
  7740. module.exports = function isBuffer(arg) {
  7741. return arg && typeof arg === 'object'
  7742. && typeof arg.copy === 'function'
  7743. && typeof arg.fill === 'function'
  7744. && typeof arg.readUInt8 === 'function';
  7745. }
  7746. },{}],35:[function(require,module,exports){
  7747. (function (process,global){
  7748. // Copyright Joyent, Inc. and other Node contributors.
  7749. //
  7750. // Permission is hereby granted, free of charge, to any person obtaining a
  7751. // copy of this software and associated documentation files (the
  7752. // "Software"), to deal in the Software without restriction, including
  7753. // without limitation the rights to use, copy, modify, merge, publish,
  7754. // distribute, sublicense, and/or sell copies of the Software, and to permit
  7755. // persons to whom the Software is furnished to do so, subject to the
  7756. // following conditions:
  7757. //
  7758. // The above copyright notice and this permission notice shall be included
  7759. // in all copies or substantial portions of the Software.
  7760. //
  7761. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  7762. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  7763. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  7764. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  7765. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  7766. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  7767. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  7768.  
  7769. var formatRegExp = /%[sdj%]/g;
  7770. exports.format = function(f) {
  7771. if (!isString(f)) {
  7772. var objects = [];
  7773. for (var i = 0; i < arguments.length; i++) {
  7774. objects.push(inspect(arguments[i]));
  7775. }
  7776. return objects.join(' ');
  7777. }
  7778.  
  7779. var i = 1;
  7780. var args = arguments;
  7781. var len = args.length;
  7782. var str = String(f).replace(formatRegExp, function(x) {
  7783. if (x === '%%') return '%';
  7784. if (i >= len) return x;
  7785. switch (x) {
  7786. case '%s': return String(args[i++]);
  7787. case '%d': return Number(args[i++]);
  7788. case '%j':
  7789. try {
  7790. return JSON.stringify(args[i++]);
  7791. } catch (_) {
  7792. return '[Circular]';
  7793. }
  7794. default:
  7795. return x;
  7796. }
  7797. });
  7798. for (var x = args[i]; i < len; x = args[++i]) {
  7799. if (isNull(x) || !isObject(x)) {
  7800. str += ' ' + x;
  7801. } else {
  7802. str += ' ' + inspect(x);
  7803. }
  7804. }
  7805. return str;
  7806. };
  7807.  
  7808.  
  7809. // Mark that a method should not be used.
  7810. // Returns a modified function which warns once by default.
  7811. // If --no-deprecation is set, then it is a no-op.
  7812. exports.deprecate = function(fn, msg) {
  7813. // Allow for deprecating things in the process of starting up.
  7814. if (isUndefined(global.process)) {
  7815. return function() {
  7816. return exports.deprecate(fn, msg).apply(this, arguments);
  7817. };
  7818. }
  7819.  
  7820. if (process.noDeprecation === true) {
  7821. return fn;
  7822. }
  7823.  
  7824. var warned = false;
  7825. function deprecated() {
  7826. if (!warned) {
  7827. if (process.throwDeprecation) {
  7828. throw new Error(msg);
  7829. } else if (process.traceDeprecation) {
  7830. console.trace(msg);
  7831. } else {
  7832. console.error(msg);
  7833. }
  7834. warned = true;
  7835. }
  7836. return fn.apply(this, arguments);
  7837. }
  7838.  
  7839. return deprecated;
  7840. };
  7841.  
  7842.  
  7843. var debugs = {};
  7844. var debugEnviron;
  7845. exports.debuglog = function(set) {
  7846. if (isUndefined(debugEnviron))
  7847. debugEnviron = process.env.NODE_DEBUG || '';
  7848. set = set.toUpperCase();
  7849. if (!debugs[set]) {
  7850. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  7851. var pid = process.pid;
  7852. debugs[set] = function() {
  7853. var msg = exports.format.apply(exports, arguments);
  7854. console.error('%s %d: %s', set, pid, msg);
  7855. };
  7856. } else {
  7857. debugs[set] = function() {};
  7858. }
  7859. }
  7860. return debugs[set];
  7861. };
  7862.  
  7863.  
  7864. /**
  7865. * Echos the value of a value. Trys to print the value out
  7866. * in the best way possible given the different types.
  7867. *
  7868. * @param {Object} obj The object to print out.
  7869. * @param {Object} opts Optional options object that alters the output.
  7870. */
  7871. /* legacy: obj, showHidden, depth, colors*/
  7872. function inspect(obj, opts) {
  7873. // default options
  7874. var ctx = {
  7875. seen: [],
  7876. stylize: stylizeNoColor
  7877. };
  7878. // legacy...
  7879. if (arguments.length >= 3) ctx.depth = arguments[2];
  7880. if (arguments.length >= 4) ctx.colors = arguments[3];
  7881. if (isBoolean(opts)) {
  7882. // legacy...
  7883. ctx.showHidden = opts;
  7884. } else if (opts) {
  7885. // got an "options" object
  7886. exports._extend(ctx, opts);
  7887. }
  7888. // set default options
  7889. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  7890. if (isUndefined(ctx.depth)) ctx.depth = 2;
  7891. if (isUndefined(ctx.colors)) ctx.colors = false;
  7892. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  7893. if (ctx.colors) ctx.stylize = stylizeWithColor;
  7894. return formatValue(ctx, obj, ctx.depth);
  7895. }
  7896. exports.inspect = inspect;
  7897.  
  7898.  
  7899. // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  7900. inspect.colors = {
  7901. 'bold' : [1, 22],
  7902. 'italic' : [3, 23],
  7903. 'underline' : [4, 24],
  7904. 'inverse' : [7, 27],
  7905. 'white' : [37, 39],
  7906. 'grey' : [90, 39],
  7907. 'black' : [30, 39],
  7908. 'blue' : [34, 39],
  7909. 'cyan' : [36, 39],
  7910. 'green' : [32, 39],
  7911. 'magenta' : [35, 39],
  7912. 'red' : [31, 39],
  7913. 'yellow' : [33, 39]
  7914. };
  7915.  
  7916. // Don't use 'blue' not visible on cmd.exe
  7917. inspect.styles = {
  7918. 'special': 'cyan',
  7919. 'number': 'yellow',
  7920. 'boolean': 'yellow',
  7921. 'undefined': 'grey',
  7922. 'null': 'bold',
  7923. 'string': 'green',
  7924. 'date': 'magenta',
  7925. // "name": intentionally not styling
  7926. 'regexp': 'red'
  7927. };
  7928.  
  7929.  
  7930. function stylizeWithColor(str, styleType) {
  7931. var style = inspect.styles[styleType];
  7932.  
  7933. if (style) {
  7934. return '\u001b[' + inspect.colors[style][0] + 'm' + str +
  7935. '\u001b[' + inspect.colors[style][1] + 'm';
  7936. } else {
  7937. return str;
  7938. }
  7939. }
  7940.  
  7941.  
  7942. function stylizeNoColor(str, styleType) {
  7943. return str;
  7944. }
  7945.  
  7946.  
  7947. function arrayToHash(array) {
  7948. var hash = {};
  7949.  
  7950. array.forEach(function(val, idx) {
  7951. hash[val] = true;
  7952. });
  7953.  
  7954. return hash;
  7955. }
  7956.  
  7957.  
  7958. function formatValue(ctx, value, recurseTimes) {
  7959. // Provide a hook for user-specified inspect functions.
  7960. // Check that value is an object with an inspect function on it
  7961. if (ctx.customInspect &&
  7962. value &&
  7963. isFunction(value.inspect) &&
  7964. // Filter out the util module, it's inspect function is special
  7965. value.inspect !== exports.inspect &&
  7966. // Also filter out any prototype objects using the circular check.
  7967. !(value.constructor && value.constructor.prototype === value)) {
  7968. var ret = value.inspect(recurseTimes, ctx);
  7969. if (!isString(ret)) {
  7970. ret = formatValue(ctx, ret, recurseTimes);
  7971. }
  7972. return ret;
  7973. }
  7974.  
  7975. // Primitive types cannot have properties
  7976. var primitive = formatPrimitive(ctx, value);
  7977. if (primitive) {
  7978. return primitive;
  7979. }
  7980.  
  7981. // Look up the keys of the object.
  7982. var keys = Object.keys(value);
  7983. var visibleKeys = arrayToHash(keys);
  7984.  
  7985. if (ctx.showHidden) {
  7986. keys = Object.getOwnPropertyNames(value);
  7987. }
  7988.  
  7989. // IE doesn't make error fields non-enumerable
  7990. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  7991. if (isError(value)
  7992. && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  7993. return formatError(value);
  7994. }
  7995.  
  7996. // Some type of object without properties can be shortcutted.
  7997. if (keys.length === 0) {
  7998. if (isFunction(value)) {
  7999. var name = value.name ? ': ' + value.name : '';
  8000. return ctx.stylize('[Function' + name + ']', 'special');
  8001. }
  8002. if (isRegExp(value)) {
  8003. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  8004. }
  8005. if (isDate(value)) {
  8006. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  8007. }
  8008. if (isError(value)) {
  8009. return formatError(value);
  8010. }
  8011. }
  8012.  
  8013. var base = '', array = false, braces = ['{', '}'];
  8014.  
  8015. // Make Array say that they are Array
  8016. if (isArray(value)) {
  8017. array = true;
  8018. braces = ['[', ']'];
  8019. }
  8020.  
  8021. // Make functions say that they are functions
  8022. if (isFunction(value)) {
  8023. var n = value.name ? ': ' + value.name : '';
  8024. base = ' [Function' + n + ']';
  8025. }
  8026.  
  8027. // Make RegExps say that they are RegExps
  8028. if (isRegExp(value)) {
  8029. base = ' ' + RegExp.prototype.toString.call(value);
  8030. }
  8031.  
  8032. // Make dates with properties first say the date
  8033. if (isDate(value)) {
  8034. base = ' ' + Date.prototype.toUTCString.call(value);
  8035. }
  8036.  
  8037. // Make error with message first say the error
  8038. if (isError(value)) {
  8039. base = ' ' + formatError(value);
  8040. }
  8041.  
  8042. if (keys.length === 0 && (!array || value.length == 0)) {
  8043. return braces[0] + base + braces[1];
  8044. }
  8045.  
  8046. if (recurseTimes < 0) {
  8047. if (isRegExp(value)) {
  8048. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  8049. } else {
  8050. return ctx.stylize('[Object]', 'special');
  8051. }
  8052. }
  8053.  
  8054. ctx.seen.push(value);
  8055.  
  8056. var output;
  8057. if (array) {
  8058. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  8059. } else {
  8060. output = keys.map(function(key) {
  8061. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  8062. });
  8063. }
  8064.  
  8065. ctx.seen.pop();
  8066.  
  8067. return reduceToSingleString(output, base, braces);
  8068. }
  8069.  
  8070.  
  8071. function formatPrimitive(ctx, value) {
  8072. if (isUndefined(value))
  8073. return ctx.stylize('undefined', 'undefined');
  8074. if (isString(value)) {
  8075. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
  8076. .replace(/'/g, "\\'")
  8077. .replace(/\\"/g, '"') + '\'';
  8078. return ctx.stylize(simple, 'string');
  8079. }
  8080. if (isNumber(value))
  8081. return ctx.stylize('' + value, 'number');
  8082. if (isBoolean(value))
  8083. return ctx.stylize('' + value, 'boolean');
  8084. // For some reason typeof null is "object", so special case here.
  8085. if (isNull(value))
  8086. return ctx.stylize('null', 'null');
  8087. }
  8088.  
  8089.  
  8090. function formatError(value) {
  8091. return '[' + Error.prototype.toString.call(value) + ']';
  8092. }
  8093.  
  8094.  
  8095. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  8096. var output = [];
  8097. for (var i = 0, l = value.length; i < l; ++i) {
  8098. if (hasOwnProperty(value, String(i))) {
  8099. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  8100. String(i), true));
  8101. } else {
  8102. output.push('');
  8103. }
  8104. }
  8105. keys.forEach(function(key) {
  8106. if (!key.match(/^\d+$/)) {
  8107. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  8108. key, true));
  8109. }
  8110. });
  8111. return output;
  8112. }
  8113.  
  8114.  
  8115. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  8116. var name, str, desc;
  8117. desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  8118. if (desc.get) {
  8119. if (desc.set) {
  8120. str = ctx.stylize('[Getter/Setter]', 'special');
  8121. } else {
  8122. str = ctx.stylize('[Getter]', 'special');
  8123. }
  8124. } else {
  8125. if (desc.set) {
  8126. str = ctx.stylize('[Setter]', 'special');
  8127. }
  8128. }
  8129. if (!hasOwnProperty(visibleKeys, key)) {
  8130. name = '[' + key + ']';
  8131. }
  8132. if (!str) {
  8133. if (ctx.seen.indexOf(desc.value) < 0) {
  8134. if (isNull(recurseTimes)) {
  8135. str = formatValue(ctx, desc.value, null);
  8136. } else {
  8137. str = formatValue(ctx, desc.value, recurseTimes - 1);
  8138. }
  8139. if (str.indexOf('\n') > -1) {
  8140. if (array) {
  8141. str = str.split('\n').map(function(line) {
  8142. return ' ' + line;
  8143. }).join('\n').substr(2);
  8144. } else {
  8145. str = '\n' + str.split('\n').map(function(line) {
  8146. return ' ' + line;
  8147. }).join('\n');
  8148. }
  8149. }
  8150. } else {
  8151. str = ctx.stylize('[Circular]', 'special');
  8152. }
  8153. }
  8154. if (isUndefined(name)) {
  8155. if (array && key.match(/^\d+$/)) {
  8156. return str;
  8157. }
  8158. name = JSON.stringify('' + key);
  8159. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  8160. name = name.substr(1, name.length - 2);
  8161. name = ctx.stylize(name, 'name');
  8162. } else {
  8163. name = name.replace(/'/g, "\\'")
  8164. .replace(/\\"/g, '"')
  8165. .replace(/(^"|"$)/g, "'");
  8166. name = ctx.stylize(name, 'string');
  8167. }
  8168. }
  8169.  
  8170. return name + ': ' + str;
  8171. }
  8172.  
  8173.  
  8174. function reduceToSingleString(output, base, braces) {
  8175. var numLinesEst = 0;
  8176. var length = output.reduce(function(prev, cur) {
  8177. numLinesEst++;
  8178. if (cur.indexOf('\n') >= 0) numLinesEst++;
  8179. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  8180. }, 0);
  8181.  
  8182. if (length > 60) {
  8183. return braces[0] +
  8184. (base === '' ? '' : base + '\n ') +
  8185. ' ' +
  8186. output.join(',\n ') +
  8187. ' ' +
  8188. braces[1];
  8189. }
  8190.  
  8191. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  8192. }
  8193.  
  8194.  
  8195. // NOTE: These type checking functions intentionally don't use `instanceof`
  8196. // because it is fragile and can be easily faked with `Object.create()`.
  8197. function isArray(ar) {
  8198. return Array.isArray(ar);
  8199. }
  8200. exports.isArray = isArray;
  8201.  
  8202. function isBoolean(arg) {
  8203. return typeof arg === 'boolean';
  8204. }
  8205. exports.isBoolean = isBoolean;
  8206.  
  8207. function isNull(arg) {
  8208. return arg === null;
  8209. }
  8210. exports.isNull = isNull;
  8211.  
  8212. function isNullOrUndefined(arg) {
  8213. return arg == null;
  8214. }
  8215. exports.isNullOrUndefined = isNullOrUndefined;
  8216.  
  8217. function isNumber(arg) {
  8218. return typeof arg === 'number';
  8219. }
  8220. exports.isNumber = isNumber;
  8221.  
  8222. function isString(arg) {
  8223. return typeof arg === 'string';
  8224. }
  8225. exports.isString = isString;
  8226.  
  8227. function isSymbol(arg) {
  8228. return typeof arg === 'symbol';
  8229. }
  8230. exports.isSymbol = isSymbol;
  8231.  
  8232. function isUndefined(arg) {
  8233. return arg === void 0;
  8234. }
  8235. exports.isUndefined = isUndefined;
  8236.  
  8237. function isRegExp(re) {
  8238. return isObject(re) && objectToString(re) === '[object RegExp]';
  8239. }
  8240. exports.isRegExp = isRegExp;
  8241.  
  8242. function isObject(arg) {
  8243. return typeof arg === 'object' && arg !== null;
  8244. }
  8245. exports.isObject = isObject;
  8246.  
  8247. function isDate(d) {
  8248. return isObject(d) && objectToString(d) === '[object Date]';
  8249. }
  8250. exports.isDate = isDate;
  8251.  
  8252. function isError(e) {
  8253. return isObject(e) &&
  8254. (objectToString(e) === '[object Error]' || e instanceof Error);
  8255. }
  8256. exports.isError = isError;
  8257.  
  8258. function isFunction(arg) {
  8259. return typeof arg === 'function';
  8260. }
  8261. exports.isFunction = isFunction;
  8262.  
  8263. function isPrimitive(arg) {
  8264. return arg === null ||
  8265. typeof arg === 'boolean' ||
  8266. typeof arg === 'number' ||
  8267. typeof arg === 'string' ||
  8268. typeof arg === 'symbol' || // ES6 symbol
  8269. typeof arg === 'undefined';
  8270. }
  8271. exports.isPrimitive = isPrimitive;
  8272.  
  8273. exports.isBuffer = require('./support/isBuffer');
  8274.  
  8275. function objectToString(o) {
  8276. return Object.prototype.toString.call(o);
  8277. }
  8278.  
  8279.  
  8280. function pad(n) {
  8281. return n < 10 ? '0' + n.toString(10) : n.toString(10);
  8282. }
  8283.  
  8284.  
  8285. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
  8286. 'Oct', 'Nov', 'Dec'];
  8287.  
  8288. // 26 Feb 16:19:34
  8289. function timestamp() {
  8290. var d = new Date();
  8291. var time = [pad(d.getHours()),
  8292. pad(d.getMinutes()),
  8293. pad(d.getSeconds())].join(':');
  8294. return [d.getDate(), months[d.getMonth()], time].join(' ');
  8295. }
  8296.  
  8297.  
  8298. // log is just a thin wrapper to console.log that prepends a timestamp
  8299. exports.log = function() {
  8300. console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
  8301. };
  8302.  
  8303.  
  8304. /**
  8305. * Inherit the prototype methods from one constructor into another.
  8306. *
  8307. * The Function.prototype.inherits from lang.js rewritten as a standalone
  8308. * function (not on Function.prototype). NOTE: If this file is to be loaded
  8309. * during bootstrapping this function needs to be rewritten using some native
  8310. * functions as prototype setup using normal JavaScript does not work as
  8311. * expected during bootstrapping (see mirror.js in r114903).
  8312. *
  8313. * @param {function} ctor Constructor function which needs to inherit the
  8314. * prototype.
  8315. * @param {function} superCtor Constructor function to inherit prototype from.
  8316. */
  8317. exports.inherits = require('inherits');
  8318.  
  8319. exports._extend = function(origin, add) {
  8320. // Don't do anything if add isn't an object
  8321. if (!add || !isObject(add)) return origin;
  8322.  
  8323. var keys = Object.keys(add);
  8324. var i = keys.length;
  8325. while (i--) {
  8326. origin[keys[i]] = add[keys[i]];
  8327. }
  8328. return origin;
  8329. };
  8330.  
  8331. function hasOwnProperty(obj, prop) {
  8332. return Object.prototype.hasOwnProperty.call(obj, prop);
  8333. }
  8334.  
  8335. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  8336. },{"./support/isBuffer":34,"_process":32,"inherits":9}],36:[function(require,module,exports){
  8337. module.exports = hasKeys
  8338.  
  8339. function hasKeys(source) {
  8340. return source !== null &&
  8341. (typeof source === "object" ||
  8342. typeof source === "function")
  8343. }
  8344.  
  8345. },{}],37:[function(require,module,exports){
  8346. var Keys = require("object-keys")
  8347. var hasKeys = require("./has-keys")
  8348.  
  8349. module.exports = extend
  8350.  
  8351. function extend() {
  8352. var target = {}
  8353.  
  8354. for (var i = 0; i < arguments.length; i++) {
  8355. var source = arguments[i]
  8356.  
  8357. if (!hasKeys(source)) {
  8358. continue
  8359. }
  8360.  
  8361. var keys = Keys(source)
  8362.  
  8363. for (var j = 0; j < keys.length; j++) {
  8364. var name = keys[j]
  8365. target[name] = source[name]
  8366. }
  8367. }
  8368.  
  8369. return target
  8370. }
  8371.  
  8372. },{"./has-keys":36,"object-keys":17}],38:[function(require,module,exports){
  8373. 'use strict';
  8374.  
  8375. var leveljs = require('level-js');
  8376.  
  8377. // something about trying to store these language files in indexedDB
  8378. // causes iOS Safari to crash
  8379.  
  8380. var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent);
  8381. var noIDB = typeof indexedDB === 'undefined' || iOS;
  8382.  
  8383. var db = noIDB ? { open: function open(_, cb) {
  8384. return cb(true);
  8385. } } : leveljs('./tessdata2');
  8386.  
  8387. var langdata = require('../common/langdata.json');
  8388.  
  8389. module.exports = function getLanguageData(req, res, cb) {
  8390. var lang = req.options.lang;
  8391.  
  8392. function saveDataFile(data) {
  8393. try {
  8394. db.put(lang, data, function (err) {
  8395. return console.log('cached', lang, err);
  8396. });
  8397. } finally {
  8398. cb(data);
  8399. }
  8400. }
  8401.  
  8402. db.open({ compression: false }, function (err) {
  8403. if (err) return fetchLanguageData(req, res, cb);
  8404. db.get(lang, function (err, data) {
  8405. if (err) return fetchLanguageData(req, res, saveDataFile);
  8406. res.progress({ status: 'found in cache ' + lang + '.traineddata' });
  8407. cb(data);
  8408. });
  8409. });
  8410. };
  8411.  
  8412. var ungzip = require('pako/lib/inflate.js').ungzip;
  8413.  
  8414. function fetchLanguageData(req, res, cb) {
  8415. var lang = req.options.lang;
  8416. var langfile = lang + '.traineddata.gz';
  8417. var url = req.workerOptions.langPath + langfile;
  8418.  
  8419. var xhr = new XMLHttpRequest();
  8420. xhr.open('GET', url, true);
  8421. xhr.responseType = 'arraybuffer';
  8422. xhr.onerror = function (e) {
  8423. xhr.onprogress = xhr.onload = null;
  8424. cb(xhr, null);
  8425. };
  8426. xhr.onprogress = function (e) {
  8427. return res.progress({
  8428. status: 'downloading ' + langfile,
  8429. loaded: e.loaded,
  8430. progress: Math.min(1, e.loaded / langdata[lang])
  8431. });
  8432. };
  8433.  
  8434. xhr.onload = function (e) {
  8435. if (!(xhr.status == 200 || xhr.status == 0 && xhr.response)) return res.reject('Error downloading language ' + url);
  8436. res.progress({ status: 'unzipping ' + langfile, progress: 0 });
  8437.  
  8438. // in case the gzips are already ungzipped or extra gzipped
  8439. var response = new Uint8Array(xhr.response);
  8440. try {
  8441. var n = 2;
  8442. while (response[0] == 0x1f && response[1] == 0x8b) {
  8443. response = ungzip(response);
  8444. res.progress({ status: 'unzipping ' + langfile, progress: 1 - 1 / n++ });
  8445. }
  8446. } catch (err) {
  8447. return res.reject('Error unzipping language file ' + langfile + '\n' + err.message);
  8448. }
  8449. res.progress({ status: 'unzipping ' + langfile, progress: 1 });
  8450.  
  8451. cb(response);
  8452. };
  8453. xhr.send();
  8454. }
  8455.  
  8456. },{"../common/langdata.json":42,"level-js":13,"pako/lib/inflate.js":20}],39:[function(require,module,exports){
  8457. (function (process,global){
  8458. 'use strict';
  8459.  
  8460. var workerUtils = require('../common/worker.js');
  8461.  
  8462. if (process.env.NODE_ENV === "development") {
  8463. console.debug('Using Development Worker');
  8464. }
  8465.  
  8466. global.addEventListener('message', function (e) {
  8467. var packet = e.data;
  8468. workerUtils.dispatchHandlers(packet, function (obj) {
  8469. return postMessage(obj);
  8470. });
  8471. });
  8472.  
  8473. exports.getCore = function (req, res) {
  8474. if (!global.TesseractCore) {
  8475. res.progress({ status: 'loading tesseract core', progress: 0 });
  8476. importScripts(req.workerOptions.corePath);
  8477. res.progress({ status: 'loading tesseract core', progress: 1 });
  8478. }
  8479. return TesseractCore;
  8480. };
  8481.  
  8482. exports.getLanguageData = require('./lang.js');
  8483.  
  8484. workerUtils.setAdapter(module.exports);
  8485.  
  8486. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  8487. },{"../common/worker.js":43,"./lang.js":38,"_process":32}],40:[function(require,module,exports){
  8488. 'use strict';
  8489.  
  8490. // This converts an image to grayscale
  8491.  
  8492. module.exports = function desaturate(image) {
  8493. var width, height;
  8494. if (image.data) {
  8495. var src = image.data;
  8496. width = image.width, height = image.height;
  8497. var dst = new Uint8Array(width * height);
  8498. var srcLength = src.length | 0,
  8499. srcLength_16 = srcLength - 16 | 0;
  8500.  
  8501. for (var i = 0, j = 0; i <= srcLength_16; i += 16, j += 4) {
  8502. // convert to grayscale 4 pixels at a time; eveything with alpha gets put in front of 50% gray
  8503. dst[j] = (src[i] * 77 + src[i + 1] * 151 + src[i + 2] * 28) * src[i + 3] + (255 - src[i + 3] << 15) + 32768 >> 16;
  8504. dst[j + 1] = (src[i + 4] * 77 + src[i + 5] * 151 + src[i + 6] * 28) * src[i + 7] + (255 - src[i + 7] << 15) + 32768 >> 16;
  8505. dst[j + 2] = (src[i + 8] * 77 + src[i + 9] * 151 + src[i + 10] * 28) * src[i + 11] + (255 - src[i + 11] << 15) + 32768 >> 16;
  8506. dst[j + 3] = (src[i + 12] * 77 + src[i + 13] * 151 + src[i + 14] * 28) * src[i + 15] + (255 - src[i + 15] << 15) + 32768 >> 16;
  8507. }
  8508. for (; i < srcLength; i += 4, ++j) {
  8509. //finish up
  8510. dst[j] = (src[i] * 77 + src[i + 1] * 151 + src[i + 2] * 28) * src[i + 3] + (255 - src[i + 3] << 15) + 32768 >> 16;
  8511. }image = dst;
  8512. } else {
  8513. throw 'Invalid ImageData';
  8514. }
  8515. return image;
  8516. };
  8517.  
  8518. },{}],41:[function(require,module,exports){
  8519. 'use strict';
  8520.  
  8521. module.exports = function DumpLiterallyEverything(Module, base) {
  8522. var ri = base.GetIterator();
  8523. var blocks = [];
  8524. var block, para, textline, word, symbol;
  8525.  
  8526. function enumToString(value, prefix) {
  8527. return Object.keys(Module).filter(function (e) {
  8528. return e.substr(0, prefix.length + 1) == prefix + '_';
  8529. }).filter(function (e) {
  8530. return Module[e] === value;
  8531. }).map(function (e) {
  8532. return e.slice(prefix.length + 1);
  8533. })[0];
  8534. }
  8535.  
  8536. ri.Begin();
  8537. do {
  8538. if (ri.IsAtBeginningOf(Module.RIL_BLOCK)) {
  8539. var poly = ri.BlockPolygon();
  8540. var polygon = null;
  8541. // BlockPolygon() returns null when automatic page segmentation is off
  8542. if (Module.getPointer(poly) > 0) {
  8543. var n = poly.get_n(),
  8544. px = poly.get_x(),
  8545. py = poly.get_y(),
  8546. polygon = [];
  8547. for (var i = 0; i < n; i++) {
  8548. polygon.push([px.getValue(i), py.getValue(i)]);
  8549. }
  8550. Module._ptaDestroy(Module.getPointer(poly));
  8551. }
  8552.  
  8553. block = {
  8554. paragraphs: [],
  8555.  
  8556. text: ri.GetUTF8Text(Module.RIL_BLOCK),
  8557. confidence: ri.Confidence(Module.RIL_BLOCK),
  8558. baseline: ri.getBaseline(Module.RIL_BLOCK),
  8559. bbox: ri.getBoundingBox(Module.RIL_BLOCK),
  8560.  
  8561. blocktype: enumToString(ri.BlockType(), 'PT'),
  8562. polygon: polygon
  8563. };
  8564. blocks.push(block);
  8565. }
  8566. if (ri.IsAtBeginningOf(Module.RIL_PARA)) {
  8567. para = {
  8568. lines: [],
  8569.  
  8570. text: ri.GetUTF8Text(Module.RIL_PARA),
  8571. confidence: ri.Confidence(Module.RIL_PARA),
  8572. baseline: ri.getBaseline(Module.RIL_PARA),
  8573. bbox: ri.getBoundingBox(Module.RIL_PARA),
  8574.  
  8575. is_ltr: !!ri.ParagraphIsLtr()
  8576. };
  8577. block.paragraphs.push(para);
  8578. }
  8579. if (ri.IsAtBeginningOf(Module.RIL_TEXTLINE)) {
  8580. textline = {
  8581. words: [],
  8582.  
  8583. text: ri.GetUTF8Text(Module.RIL_TEXTLINE),
  8584. confidence: ri.Confidence(Module.RIL_TEXTLINE),
  8585. baseline: ri.getBaseline(Module.RIL_TEXTLINE),
  8586. bbox: ri.getBoundingBox(Module.RIL_TEXTLINE)
  8587. };
  8588. para.lines.push(textline);
  8589. }
  8590. if (ri.IsAtBeginningOf(Module.RIL_WORD)) {
  8591. var fontInfo = ri.getWordFontAttributes(),
  8592. wordDir = ri.WordDirection();
  8593. word = {
  8594. symbols: [],
  8595. choices: [],
  8596.  
  8597. text: ri.GetUTF8Text(Module.RIL_WORD),
  8598. confidence: ri.Confidence(Module.RIL_WORD),
  8599. baseline: ri.getBaseline(Module.RIL_WORD),
  8600. bbox: ri.getBoundingBox(Module.RIL_WORD),
  8601.  
  8602. is_numeric: !!ri.WordIsNumeric(),
  8603. in_dictionary: !!ri.WordIsFromDictionary(),
  8604. direction: enumToString(wordDir, 'DIR'),
  8605. language: ri.WordRecognitionLanguage(),
  8606.  
  8607. is_bold: fontInfo.is_bold,
  8608. is_italic: fontInfo.is_italic,
  8609. is_underlined: fontInfo.is_underlined,
  8610. is_monospace: fontInfo.is_monospace,
  8611. is_serif: fontInfo.is_serif,
  8612. is_smallcaps: fontInfo.is_smallcaps,
  8613. font_size: fontInfo.pointsize,
  8614. font_id: fontInfo.font_id,
  8615. font_name: fontInfo.font_name
  8616. };
  8617. var wc = new Module.WordChoiceIterator(ri);
  8618. do {
  8619. word.choices.push({
  8620. text: wc.GetUTF8Text(),
  8621. confidence: wc.Confidence()
  8622. });
  8623. } while (wc.Next());
  8624. Module.destroy(wc);
  8625. textline.words.push(word);
  8626. }
  8627.  
  8628. var image = null;
  8629. // var pix = ri.GetBinaryImage(Module.RIL_SYMBOL)
  8630. // var image = pix2array(pix);
  8631. // // for some reason it seems that things stop working if you destroy pics
  8632. // Module._pixDestroy(Module.getPointer(pix));
  8633. if (ri.IsAtBeginningOf(Module.RIL_SYMBOL)) {
  8634. symbol = {
  8635. choices: [],
  8636. image: image,
  8637.  
  8638. text: ri.GetUTF8Text(Module.RIL_SYMBOL),
  8639. confidence: ri.Confidence(Module.RIL_SYMBOL),
  8640. baseline: ri.getBaseline(Module.RIL_SYMBOL),
  8641. bbox: ri.getBoundingBox(Module.RIL_SYMBOL),
  8642.  
  8643. is_superscript: !!ri.SymbolIsSuperscript(),
  8644. is_subscript: !!ri.SymbolIsSubscript(),
  8645. is_dropcap: !!ri.SymbolIsDropcap()
  8646. };
  8647. word.symbols.push(symbol);
  8648. var ci = new Module.ChoiceIterator(ri);
  8649. do {
  8650. symbol.choices.push({
  8651. text: ci.GetUTF8Text(),
  8652. confidence: ci.Confidence()
  8653. });
  8654. } while (ci.Next());
  8655. Module.destroy(ci);
  8656. }
  8657. } while (ri.Next(Module.RIL_SYMBOL));
  8658. Module.destroy(ri);
  8659.  
  8660. return {
  8661. text: base.GetUTF8Text(),
  8662. html: deindent(base.GetHOCRText()),
  8663.  
  8664. confidence: base.MeanTextConf(),
  8665.  
  8666. blocks: blocks,
  8667.  
  8668. psm: enumToString(base.GetPageSegMode(), 'PSM'),
  8669. oem: enumToString(base.oem(), 'OEM'),
  8670. version: base.Version()
  8671. };
  8672. };
  8673.  
  8674. // the generated HOCR is excessively indented, so
  8675. // we get rid of that indentation
  8676.  
  8677. function deindent(html) {
  8678. var lines = html.split('\n');
  8679. if (lines[0].substring(0, 2) === " ") {
  8680. for (var i = 0; i < lines.length; i++) {
  8681. if (lines[i].substring(0, 2) === " ") {
  8682. lines[i] = lines[i].slice(2);
  8683. }
  8684. };
  8685. }
  8686. return lines.join('\n');
  8687. }
  8688.  
  8689. },{}],42:[function(require,module,exports){
  8690. module.exports={"afr": 1079573, "ara": 1701536, "aze": 1420865, "bel": 1276820, "ben": 6772012, "bul": 1605615, "cat": 1652368, "ces": 1035441, "chi_sim": 17710414, "chi_tra": 24717749, "chr": 320649, "dan-frak": 677656, "dan": 1972936, "deu-frak": 822644, "deu": 991656, "ell": 859719, "eng": 9453554, "enm": 619254, "epo": 1241212, "equ": 821130, "est": 1905040, "eus": 1641190, "fin": 979418, "fra": 1376221, "frk": 5912963, "frm": 5147082, "glg": 1674938, "grc": 3012615, "heb": 1051501, "hin": 6590065, "hrv": 1926995, "hun": 3074473, "ind": 1874776, "isl": 1634041, "ita": 948593, "ita_old": 3436571, "jpn": 13507168, "kan": 4390317, "kor": 5353098, "lav": 1843944, "lit": 1779240, "mal": 5966263, "meme": 88453, "mkd": 1163087, "mlt": 1463001, "msa": 1665427, "nld": 1134708, "nor": 2191610, "osd": 4274649, "pol": 7024662, "por": 909359, "ron": 915680, "rus": 5969957, "slk-frak": 289885, "slk": 2217342, "slv": 1611338, "spa": 883170, "spa_old": 5647453, "sqi": 1667041, "srp": 1770244, "swa": 757916, "swe": 2451917, "tam": 3498763, "tel": 5795246, "tgl": 1496256, "tha": 3811136, "tur": 3563264, "ukr": 937566, "vie": 2195922}
  8691. },{}],43:[function(require,module,exports){
  8692. 'use strict';
  8693.  
  8694. var latestJob,
  8695. Module,
  8696. base,
  8697. adapter = {},
  8698. dump = require('./dump.js'),
  8699. desaturate = require('./desaturate.js');
  8700.  
  8701. function dispatchHandlers(packet, send) {
  8702. function respond(status, data) {
  8703. send({
  8704. jobId: packet.jobId,
  8705. status: status,
  8706. action: packet.action,
  8707. data: data
  8708. });
  8709. }
  8710. respond.resolve = respond.bind(this, 'resolve');
  8711. respond.reject = respond.bind(this, 'reject');
  8712. respond.progress = respond.bind(this, 'progress');
  8713.  
  8714. latestJob = respond;
  8715.  
  8716. try {
  8717. if (packet.action === 'recognize') {
  8718. handleRecognize(packet.payload, respond);
  8719. } else if (packet.action === 'detect') {
  8720. handleDetect(packet.payload, respond);
  8721. }
  8722. } catch (err) {
  8723. respond.reject(err);
  8724. }
  8725. }
  8726. exports.dispatchHandlers = dispatchHandlers;
  8727.  
  8728. exports.setAdapter = function setAdapter(impl) {
  8729. adapter = impl;
  8730. };
  8731.  
  8732. function handleInit(req, res) {
  8733. var MIN_MEMORY = 100663296;
  8734.  
  8735. if (['chi_sim', 'chi_tra', 'jpn'].includes(req.options.lang)) {
  8736. MIN_MEMORY = 167772160;
  8737. }
  8738.  
  8739. if (!Module || Module.TOTAL_MEMORY < MIN_MEMORY) {
  8740. var Core = adapter.getCore(req, res);
  8741.  
  8742. res.progress({ status: 'initializing tesseract', progress: 0 });
  8743.  
  8744. Module = Core({
  8745. TOTAL_MEMORY: MIN_MEMORY,
  8746. TesseractProgress: function TesseractProgress(percent) {
  8747. latestJob.progress({ status: 'recognizing text', progress: Math.max(0, (percent - 30) / 70) });
  8748. },
  8749. onRuntimeInitialized: function onRuntimeInitialized() {}
  8750. });
  8751.  
  8752. Module.FS_createPath("/", "tessdata", true, true);
  8753. base = new Module.TessBaseAPI();
  8754. res.progress({ status: 'initializing tesseract', progress: 1 });
  8755. }
  8756. }
  8757.  
  8758. function setImage(Module, base, image) {
  8759. var imgbin = desaturate(image),
  8760. width = image.width,
  8761. height = image.height;
  8762.  
  8763. var ptr = Module.allocate(imgbin, 'i8', Module.ALLOC_NORMAL);
  8764. base.SetImage(Module.wrapPointer(ptr), width, height, 1, width);
  8765. base.SetRectangle(0, 0, width, height);
  8766. return ptr;
  8767. }
  8768.  
  8769. function loadLanguage(req, res, cb) {
  8770. var lang = req.options.lang,
  8771. langFile = lang + '.traineddata';
  8772.  
  8773. if (!Module._loadedLanguages) Module._loadedLanguages = {};
  8774. if (lang in Module._loadedLanguages) return cb();
  8775.  
  8776. adapter.getLanguageData(req, res, function (data) {
  8777. res.progress({ status: 'loading ' + langFile, progress: 0 });
  8778. Module.FS_createDataFile('tessdata', langFile, data, true, false);
  8779. Module._loadedLanguages[lang] = true;
  8780. res.progress({ status: 'loading ' + langFile, progress: 1 });
  8781. cb();
  8782. });
  8783. }
  8784.  
  8785. function handleRecognize(req, res) {
  8786. handleInit(req, res);
  8787.  
  8788. loadLanguage(req, res, function () {
  8789. var options = req.options;
  8790.  
  8791. function progressUpdate(progress) {
  8792. res.progress({ status: 'initializing api', progress: progress });
  8793. }
  8794.  
  8795. progressUpdate(0);
  8796. base.Init(null, req.options.lang);
  8797. progressUpdate(.3);
  8798.  
  8799. for (var option in options) {
  8800. if (options.hasOwnProperty(option)) {
  8801. base.SetVariable(option, options[option]);
  8802. }
  8803. }
  8804.  
  8805. progressUpdate(.6);
  8806. var ptr = setImage(Module, base, req.image);
  8807. progressUpdate(1);
  8808.  
  8809. base.Recognize(null);
  8810.  
  8811. var result = dump(Module, base);
  8812.  
  8813. base.End();
  8814. Module._free(ptr);
  8815.  
  8816. res.resolve(result);
  8817. });
  8818. }
  8819.  
  8820. function handleDetect(req, res) {
  8821. handleInit(req, res);
  8822. req.options.lang = 'osd';
  8823. loadLanguage(req, res, function () {
  8824. base.Init(null, 'osd');
  8825. base.SetPageSegMode(Module.PSM_OSD_ONLY);
  8826.  
  8827. var ptr = setImage(Module, base, req.image),
  8828. results = new Module.OSResults();
  8829.  
  8830. if (!base.DetectOS(results)) {
  8831. base.End();
  8832. Module._free(ptr);
  8833. res.reject("Failed to detect OS");
  8834. } else {
  8835. var best = results.get_best_result(),
  8836. oid = best.get_orientation_id(),
  8837. sid = best.get_script_id();
  8838.  
  8839. base.End();
  8840. Module._free(ptr);
  8841.  
  8842. res.resolve({
  8843. tesseract_script_id: sid,
  8844. script: results.get_unicharset().get_script_from_script_id(sid),
  8845. script_confidence: best.get_sconfidence(),
  8846. orientation_degrees: [0, 270, 180, 90][oid],
  8847. orientation_confidence: best.get_oconfidence()
  8848. });
  8849. }
  8850. });
  8851. }
  8852.  
  8853. },{"./desaturate.js":40,"./dump.js":41}]},{},[39]);