react / react-0.13.3 / examples / basic-commonjs / node_modules / browserify / node_modules / browserify-zlib / src / index.js
80728 views// Copyright Joyent, Inc. and other Node contributors.1//2// Permission is hereby granted, free of charge, to any person obtaining a3// copy of this software and associated documentation files (the4// "Software"), to deal in the Software without restriction, including5// without limitation the rights to use, copy, modify, merge, publish,6// distribute, sublicense, and/or sell copies of the Software, and to permit7// persons to whom the Software is furnished to do so, subject to the8// following conditions:9//10// The above copyright notice and this permission notice shall be included11// in all copies or substantial portions of the Software.12//13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS14// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF15// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN16// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,17// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR18// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE19// USE OR OTHER DEALINGS IN THE SOFTWARE.2021var Transform = require('_stream_transform');2223var binding = require('./binding');24var util = require('util');25var assert = require('assert').ok;2627// zlib doesn't provide these, so kludge them in following the same28// const naming scheme zlib uses.29binding.Z_MIN_WINDOWBITS = 8;30binding.Z_MAX_WINDOWBITS = 15;31binding.Z_DEFAULT_WINDOWBITS = 15;3233// fewer than 64 bytes per chunk is stupid.34// technically it could work with as few as 8, but even 64 bytes35// is absurdly low. Usually a MB or more is best.36binding.Z_MIN_CHUNK = 64;37binding.Z_MAX_CHUNK = Infinity;38binding.Z_DEFAULT_CHUNK = (16 * 1024);3940binding.Z_MIN_MEMLEVEL = 1;41binding.Z_MAX_MEMLEVEL = 9;42binding.Z_DEFAULT_MEMLEVEL = 8;4344binding.Z_MIN_LEVEL = -1;45binding.Z_MAX_LEVEL = 9;46binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION;4748// expose all the zlib constants49Object.keys(binding).forEach(function(k) {50if (k.match(/^Z/)) exports[k] = binding[k];51});5253// translation table for return codes.54exports.codes = {55Z_OK: binding.Z_OK,56Z_STREAM_END: binding.Z_STREAM_END,57Z_NEED_DICT: binding.Z_NEED_DICT,58Z_ERRNO: binding.Z_ERRNO,59Z_STREAM_ERROR: binding.Z_STREAM_ERROR,60Z_DATA_ERROR: binding.Z_DATA_ERROR,61Z_MEM_ERROR: binding.Z_MEM_ERROR,62Z_BUF_ERROR: binding.Z_BUF_ERROR,63Z_VERSION_ERROR: binding.Z_VERSION_ERROR64};6566Object.keys(exports.codes).forEach(function(k) {67exports.codes[exports.codes[k]] = k;68});6970exports.Deflate = Deflate;71exports.Inflate = Inflate;72exports.Gzip = Gzip;73exports.Gunzip = Gunzip;74exports.DeflateRaw = DeflateRaw;75exports.InflateRaw = InflateRaw;76exports.Unzip = Unzip;7778exports.createDeflate = function(o) {79return new Deflate(o);80};8182exports.createInflate = function(o) {83return new Inflate(o);84};8586exports.createDeflateRaw = function(o) {87return new DeflateRaw(o);88};8990exports.createInflateRaw = function(o) {91return new InflateRaw(o);92};9394exports.createGzip = function(o) {95return new Gzip(o);96};9798exports.createGunzip = function(o) {99return new Gunzip(o);100};101102exports.createUnzip = function(o) {103return new Unzip(o);104};105106107// Convenience methods.108// compress/decompress a string or buffer in one step.109exports.deflate = function(buffer, opts, callback) {110if (typeof opts === 'function') {111callback = opts;112opts = {};113}114return zlibBuffer(new Deflate(opts), buffer, callback);115};116117exports.deflateSync = function(buffer, opts) {118return zlibBufferSync(new Deflate(opts), buffer);119};120121exports.gzip = function(buffer, opts, callback) {122if (typeof opts === 'function') {123callback = opts;124opts = {};125}126return zlibBuffer(new Gzip(opts), buffer, callback);127};128129exports.gzipSync = function(buffer, opts) {130return zlibBufferSync(new Gzip(opts), buffer);131};132133exports.deflateRaw = function(buffer, opts, callback) {134if (typeof opts === 'function') {135callback = opts;136opts = {};137}138return zlibBuffer(new DeflateRaw(opts), buffer, callback);139};140141exports.deflateRawSync = function(buffer, opts) {142return zlibBufferSync(new DeflateRaw(opts), buffer);143};144145exports.unzip = function(buffer, opts, callback) {146if (typeof opts === 'function') {147callback = opts;148opts = {};149}150return zlibBuffer(new Unzip(opts), buffer, callback);151};152153exports.unzipSync = function(buffer, opts) {154return zlibBufferSync(new Unzip(opts), buffer);155};156157exports.inflate = function(buffer, opts, callback) {158if (typeof opts === 'function') {159callback = opts;160opts = {};161}162return zlibBuffer(new Inflate(opts), buffer, callback);163};164165exports.inflateSync = function(buffer, opts) {166return zlibBufferSync(new Inflate(opts), buffer);167};168169exports.gunzip = function(buffer, opts, callback) {170if (typeof opts === 'function') {171callback = opts;172opts = {};173}174return zlibBuffer(new Gunzip(opts), buffer, callback);175};176177exports.gunzipSync = function(buffer, opts) {178return zlibBufferSync(new Gunzip(opts), buffer);179};180181exports.inflateRaw = function(buffer, opts, callback) {182if (typeof opts === 'function') {183callback = opts;184opts = {};185}186return zlibBuffer(new InflateRaw(opts), buffer, callback);187};188189exports.inflateRawSync = function(buffer, opts) {190return zlibBufferSync(new InflateRaw(opts), buffer);191};192193function zlibBuffer(engine, buffer, callback) {194var buffers = [];195var nread = 0;196197engine.on('error', onError);198engine.on('end', onEnd);199200engine.end(buffer);201flow();202203function flow() {204var chunk;205while (null !== (chunk = engine.read())) {206buffers.push(chunk);207nread += chunk.length;208}209engine.once('readable', flow);210}211212function onError(err) {213engine.removeListener('end', onEnd);214engine.removeListener('readable', flow);215callback(err);216}217218function onEnd() {219var buf = Buffer.concat(buffers, nread);220buffers = [];221callback(null, buf);222engine.close();223}224}225226function zlibBufferSync(engine, buffer) {227if (typeof buffer === 'string')228buffer = new Buffer(buffer);229if (!Buffer.isBuffer(buffer))230throw new TypeError('Not a string or buffer');231232var flushFlag = binding.Z_FINISH;233234return engine._processChunk(buffer, flushFlag);235}236237// generic zlib238// minimal 2-byte header239function Deflate(opts) {240if (!(this instanceof Deflate)) return new Deflate(opts);241Zlib.call(this, opts, binding.DEFLATE);242}243244function Inflate(opts) {245if (!(this instanceof Inflate)) return new Inflate(opts);246Zlib.call(this, opts, binding.INFLATE);247}248249250251// gzip - bigger header, same deflate compression252function Gzip(opts) {253if (!(this instanceof Gzip)) return new Gzip(opts);254Zlib.call(this, opts, binding.GZIP);255}256257function Gunzip(opts) {258if (!(this instanceof Gunzip)) return new Gunzip(opts);259Zlib.call(this, opts, binding.GUNZIP);260}261262263264// raw - no header265function DeflateRaw(opts) {266if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts);267Zlib.call(this, opts, binding.DEFLATERAW);268}269270function InflateRaw(opts) {271if (!(this instanceof InflateRaw)) return new InflateRaw(opts);272Zlib.call(this, opts, binding.INFLATERAW);273}274275276// auto-detect header.277function Unzip(opts) {278if (!(this instanceof Unzip)) return new Unzip(opts);279Zlib.call(this, opts, binding.UNZIP);280}281282283// the Zlib class they all inherit from284// This thing manages the queue of requests, and returns285// true or false if there is anything in the queue when286// you call the .write() method.287288function Zlib(opts, mode) {289this._opts = opts = opts || {};290this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK;291292Transform.call(this, opts);293294if (opts.flush) {295if (opts.flush !== binding.Z_NO_FLUSH &&296opts.flush !== binding.Z_PARTIAL_FLUSH &&297opts.flush !== binding.Z_SYNC_FLUSH &&298opts.flush !== binding.Z_FULL_FLUSH &&299opts.flush !== binding.Z_FINISH &&300opts.flush !== binding.Z_BLOCK) {301throw new Error('Invalid flush flag: ' + opts.flush);302}303}304this._flushFlag = opts.flush || binding.Z_NO_FLUSH;305306if (opts.chunkSize) {307if (opts.chunkSize < exports.Z_MIN_CHUNK ||308opts.chunkSize > exports.Z_MAX_CHUNK) {309throw new Error('Invalid chunk size: ' + opts.chunkSize);310}311}312313if (opts.windowBits) {314if (opts.windowBits < exports.Z_MIN_WINDOWBITS ||315opts.windowBits > exports.Z_MAX_WINDOWBITS) {316throw new Error('Invalid windowBits: ' + opts.windowBits);317}318}319320if (opts.level) {321if (opts.level < exports.Z_MIN_LEVEL ||322opts.level > exports.Z_MAX_LEVEL) {323throw new Error('Invalid compression level: ' + opts.level);324}325}326327if (opts.memLevel) {328if (opts.memLevel < exports.Z_MIN_MEMLEVEL ||329opts.memLevel > exports.Z_MAX_MEMLEVEL) {330throw new Error('Invalid memLevel: ' + opts.memLevel);331}332}333334if (opts.strategy) {335if (opts.strategy != exports.Z_FILTERED &&336opts.strategy != exports.Z_HUFFMAN_ONLY &&337opts.strategy != exports.Z_RLE &&338opts.strategy != exports.Z_FIXED &&339opts.strategy != exports.Z_DEFAULT_STRATEGY) {340throw new Error('Invalid strategy: ' + opts.strategy);341}342}343344if (opts.dictionary) {345if (!Buffer.isBuffer(opts.dictionary)) {346throw new Error('Invalid dictionary: it should be a Buffer instance');347}348}349350this._binding = new binding.Zlib(mode);351352var self = this;353this._hadError = false;354this._binding.onerror = function(message, errno) {355// there is no way to cleanly recover.356// continuing only obscures problems.357self._binding = null;358self._hadError = true;359360var error = new Error(message);361error.errno = errno;362error.code = exports.codes[errno];363self.emit('error', error);364};365366var level = exports.Z_DEFAULT_COMPRESSION;367if (typeof opts.level === 'number') level = opts.level;368369var strategy = exports.Z_DEFAULT_STRATEGY;370if (typeof opts.strategy === 'number') strategy = opts.strategy;371372this._binding.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS,373level,374opts.memLevel || exports.Z_DEFAULT_MEMLEVEL,375strategy,376opts.dictionary);377378this._buffer = new Buffer(this._chunkSize);379this._offset = 0;380this._closed = false;381this._level = level;382this._strategy = strategy;383384this.once('end', this.close);385}386387util.inherits(Zlib, Transform);388389Zlib.prototype.params = function(level, strategy, callback) {390if (level < exports.Z_MIN_LEVEL ||391level > exports.Z_MAX_LEVEL) {392throw new RangeError('Invalid compression level: ' + level);393}394if (strategy != exports.Z_FILTERED &&395strategy != exports.Z_HUFFMAN_ONLY &&396strategy != exports.Z_RLE &&397strategy != exports.Z_FIXED &&398strategy != exports.Z_DEFAULT_STRATEGY) {399throw new TypeError('Invalid strategy: ' + strategy);400}401402if (this._level !== level || this._strategy !== strategy) {403var self = this;404this.flush(binding.Z_SYNC_FLUSH, function() {405self._binding.params(level, strategy);406if (!self._hadError) {407self._level = level;408self._strategy = strategy;409if (callback) callback();410}411});412} else {413process.nextTick(callback);414}415};416417Zlib.prototype.reset = function() {418return this._binding.reset();419};420421// This is the _flush function called by the transform class,422// internally, when the last chunk has been written.423Zlib.prototype._flush = function(callback) {424this._transform(new Buffer(0), '', callback);425};426427Zlib.prototype.flush = function(kind, callback) {428var ws = this._writableState;429430if (typeof kind === 'function' || (kind === void 0 && !callback)) {431callback = kind;432kind = binding.Z_FULL_FLUSH;433}434435if (ws.ended) {436if (callback)437process.nextTick(callback);438} else if (ws.ending) {439if (callback)440this.once('end', callback);441} else if (ws.needDrain) {442var self = this;443this.once('drain', function() {444self.flush(callback);445});446} else {447this._flushFlag = kind;448this.write(new Buffer(0), '', callback);449}450};451452Zlib.prototype.close = function(callback) {453if (callback)454process.nextTick(callback);455456if (this._closed)457return;458459this._closed = true;460461this._binding.close();462463var self = this;464process.nextTick(function() {465self.emit('close');466});467};468469Zlib.prototype._transform = function(chunk, encoding, cb) {470var flushFlag;471var ws = this._writableState;472var ending = ws.ending || ws.ended;473var last = ending && (!chunk || ws.length === chunk.length);474475if (!chunk === null && !Buffer.isBuffer(chunk))476return cb(new Error('invalid input'));477478// If it's the last chunk, or a final flush, we use the Z_FINISH flush flag.479// If it's explicitly flushing at some other time, then we use480// Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression481// goodness.482if (last)483flushFlag = binding.Z_FINISH;484else {485flushFlag = this._flushFlag;486// once we've flushed the last of the queue, stop flushing and487// go back to the normal behavior.488if (chunk.length >= ws.length) {489this._flushFlag = this._opts.flush || binding.Z_NO_FLUSH;490}491}492493var self = this;494this._processChunk(chunk, flushFlag, cb);495};496497Zlib.prototype._processChunk = function(chunk, flushFlag, cb) {498var availInBefore = chunk && chunk.length;499var availOutBefore = this._chunkSize - this._offset;500var inOff = 0;501502var self = this;503504var async = typeof cb === 'function';505506if (!async) {507var buffers = [];508var nread = 0;509510var error;511this.on('error', function(er) {512error = er;513});514515do {516var res = this._binding.writeSync(flushFlag,517chunk, // in518inOff, // in_off519availInBefore, // in_len520this._buffer, // out521this._offset, //out_off522availOutBefore); // out_len523} while (!this._hadError && callback(res[0], res[1]));524525if (this._hadError) {526throw error;527}528529var buf = Buffer.concat(buffers, nread);530this.close();531532return buf;533}534535var req = this._binding.write(flushFlag,536chunk, // in537inOff, // in_off538availInBefore, // in_len539this._buffer, // out540this._offset, //out_off541availOutBefore); // out_len542543req.buffer = chunk;544req.callback = callback;545546function callback(availInAfter, availOutAfter) {547if (self._hadError)548return;549550var have = availOutBefore - availOutAfter;551assert(have >= 0, 'have should not go down');552553if (have > 0) {554var out = self._buffer.slice(self._offset, self._offset + have);555self._offset += have;556// serve some output to the consumer.557if (async) {558self.push(out);559} else {560buffers.push(out);561nread += out.length;562}563}564565// exhausted the output buffer, or used all the input create a new one.566if (availOutAfter === 0 || self._offset >= self._chunkSize) {567availOutBefore = self._chunkSize;568self._offset = 0;569self._buffer = new Buffer(self._chunkSize);570}571572if (availOutAfter === 0) {573// Not actually done. Need to reprocess.574// Also, update the availInBefore to the availInAfter value,575// so that if we have to hit it a third (fourth, etc.) time,576// it'll have the correct byte counts.577inOff += (availInBefore - availInAfter);578availInBefore = availInAfter;579580if (!async)581return true;582583var newReq = self._binding.write(flushFlag,584chunk,585inOff,586availInBefore,587self._buffer,588self._offset,589self._chunkSize);590newReq.callback = callback; // this same function591newReq.buffer = chunk;592return;593}594595if (!async)596return false;597598// finished with the chunk.599cb();600}601};602603util.inherits(Deflate, Zlib);604util.inherits(Inflate, Zlib);605util.inherits(Gzip, Zlib);606util.inherits(Gunzip, Zlib);607util.inherits(DeflateRaw, Zlib);608util.inherits(InflateRaw, Zlib);609util.inherits(Unzip, Zlib);610611612