UNPKG

17 kBJavaScriptView Raw
1// Copyright Joyent, Inc. and other Node contributors.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a
4// copy of this software and associated documentation files (the
5// "Software"), to deal in the Software without restriction, including
6// without limitation the rights to use, copy, modify, merge, publish,
7// distribute, sublicense, and/or sell copies of the Software, and to permit
8// persons to whom the Software is furnished to do so, subject to the
9// following conditions:
10//
11// The above copyright notice and this permission notice shall be included
12// in all copies or substantial portions of the Software.
13//
14// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22import {Transform} from 'stream';
23import * as _binding from './zlib-lib/binding';
24import {inherits} from 'util';
25function assert (a, msg) {
26 if (!a) {
27 throw new Error(msg);
28 }
29}
30var binding = {};
31Object.keys(_binding).forEach(function (key) {
32 binding[key] = _binding[key];
33});
34// zlib doesn't provide these, so kludge them in following the same
35// const naming scheme zlib uses.
36binding.Z_MIN_WINDOWBITS = 8;
37binding.Z_MAX_WINDOWBITS = 15;
38binding.Z_DEFAULT_WINDOWBITS = 15;
39
40// fewer than 64 bytes per chunk is stupid.
41// technically it could work with as few as 8, but even 64 bytes
42// is absurdly low. Usually a MB or more is best.
43binding.Z_MIN_CHUNK = 64;
44binding.Z_MAX_CHUNK = Infinity;
45binding.Z_DEFAULT_CHUNK = (16 * 1024);
46
47binding.Z_MIN_MEMLEVEL = 1;
48binding.Z_MAX_MEMLEVEL = 9;
49binding.Z_DEFAULT_MEMLEVEL = 8;
50
51binding.Z_MIN_LEVEL = -1;
52binding.Z_MAX_LEVEL = 9;
53binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION;
54
55// translation table for return codes.
56export var codes = {
57 Z_OK: binding.Z_OK,
58 Z_STREAM_END: binding.Z_STREAM_END,
59 Z_NEED_DICT: binding.Z_NEED_DICT,
60 Z_ERRNO: binding.Z_ERRNO,
61 Z_STREAM_ERROR: binding.Z_STREAM_ERROR,
62 Z_DATA_ERROR: binding.Z_DATA_ERROR,
63 Z_MEM_ERROR: binding.Z_MEM_ERROR,
64 Z_BUF_ERROR: binding.Z_BUF_ERROR,
65 Z_VERSION_ERROR: binding.Z_VERSION_ERROR
66};
67
68Object.keys(codes).forEach(function(k) {
69 codes[codes[k]] = k;
70});
71
72export function createDeflate(o) {
73 return new Deflate(o);
74}
75
76export function createInflate(o) {
77 return new Inflate(o);
78}
79
80export function createDeflateRaw(o) {
81 return new DeflateRaw(o);
82}
83
84export function createInflateRaw(o) {
85 return new InflateRaw(o);
86}
87
88export function createGzip(o) {
89 return new Gzip(o);
90}
91
92export function createGunzip(o) {
93 return new Gunzip(o);
94}
95
96export function createUnzip(o) {
97 return new Unzip(o);
98}
99
100// Convenience methods.
101// compress/decompress a string or buffer in one step.
102export function deflate(buffer, opts, callback) {
103 if (typeof opts === 'function') {
104 callback = opts;
105 opts = {};
106 }
107 return zlibBuffer(new Deflate(opts), buffer, callback);
108}
109
110export function deflateSync(buffer, opts) {
111 return zlibBufferSync(new Deflate(opts), buffer);
112}
113
114export function gzip(buffer, opts, callback) {
115 if (typeof opts === 'function') {
116 callback = opts;
117 opts = {};
118 }
119 return zlibBuffer(new Gzip(opts), buffer, callback);
120}
121
122export function gzipSync(buffer, opts) {
123 return zlibBufferSync(new Gzip(opts), buffer);
124}
125
126export function deflateRaw(buffer, opts, callback) {
127 if (typeof opts === 'function') {
128 callback = opts;
129 opts = {};
130 }
131 return zlibBuffer(new DeflateRaw(opts), buffer, callback);
132}
133
134export function deflateRawSync(buffer, opts) {
135 return zlibBufferSync(new DeflateRaw(opts), buffer);
136}
137
138export function unzip(buffer, opts, callback) {
139 if (typeof opts === 'function') {
140 callback = opts;
141 opts = {};
142 }
143 return zlibBuffer(new Unzip(opts), buffer, callback);
144}
145
146export function unzipSync(buffer, opts) {
147 return zlibBufferSync(new Unzip(opts), buffer);
148}
149
150export function inflate(buffer, opts, callback) {
151 if (typeof opts === 'function') {
152 callback = opts;
153 opts = {};
154 }
155 return zlibBuffer(new Inflate(opts), buffer, callback);
156}
157
158export function inflateSync(buffer, opts) {
159 return zlibBufferSync(new Inflate(opts), buffer);
160}
161
162export function gunzip(buffer, opts, callback) {
163 if (typeof opts === 'function') {
164 callback = opts;
165 opts = {};
166 }
167 return zlibBuffer(new Gunzip(opts), buffer, callback);
168}
169
170export function gunzipSync(buffer, opts) {
171 return zlibBufferSync(new Gunzip(opts), buffer);
172}
173
174export function inflateRaw(buffer, opts, callback) {
175 if (typeof opts === 'function') {
176 callback = opts;
177 opts = {};
178 }
179 return zlibBuffer(new InflateRaw(opts), buffer, callback);
180}
181
182export function inflateRawSync(buffer, opts) {
183 return zlibBufferSync(new InflateRaw(opts), buffer);
184}
185
186function zlibBuffer(engine, buffer, callback) {
187 var buffers = [];
188 var nread = 0;
189
190 engine.on('error', onError);
191 engine.on('end', onEnd);
192
193 engine.end(buffer);
194 flow();
195
196 function flow() {
197 var chunk;
198 while (null !== (chunk = engine.read())) {
199 buffers.push(chunk);
200 nread += chunk.length;
201 }
202 engine.once('readable', flow);
203 }
204
205 function onError(err) {
206 engine.removeListener('end', onEnd);
207 engine.removeListener('readable', flow);
208 callback(err);
209 }
210
211 function onEnd() {
212 var buf = Buffer.concat(buffers, nread);
213 buffers = [];
214 callback(null, buf);
215 engine.close();
216 }
217}
218
219function zlibBufferSync(engine, buffer) {
220 if (typeof buffer === 'string')
221 buffer = new Buffer(buffer);
222 if (!Buffer.isBuffer(buffer))
223 throw new TypeError('Not a string or buffer');
224
225 var flushFlag = binding.Z_FINISH;
226
227 return engine._processChunk(buffer, flushFlag);
228}
229
230// generic zlib
231// minimal 2-byte header
232export function Deflate(opts) {
233 if (!(this instanceof Deflate)) return new Deflate(opts);
234 Zlib.call(this, opts, binding.DEFLATE);
235}
236
237export function Inflate(opts) {
238 if (!(this instanceof Inflate)) return new Inflate(opts);
239 Zlib.call(this, opts, binding.INFLATE);
240}
241
242// gzip - bigger header, same deflate compression
243export function Gzip(opts) {
244 if (!(this instanceof Gzip)) return new Gzip(opts);
245 Zlib.call(this, opts, binding.GZIP);
246}
247
248export function Gunzip(opts) {
249 if (!(this instanceof Gunzip)) return new Gunzip(opts);
250 Zlib.call(this, opts, binding.GUNZIP);
251}
252
253// raw - no header
254export function DeflateRaw(opts) {
255 if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts);
256 Zlib.call(this, opts, binding.DEFLATERAW);
257}
258
259export function InflateRaw(opts) {
260 if (!(this instanceof InflateRaw)) return new InflateRaw(opts);
261 Zlib.call(this, opts, binding.INFLATERAW);
262}
263
264// auto-detect header.
265export function Unzip(opts) {
266 if (!(this instanceof Unzip)) return new Unzip(opts);
267 Zlib.call(this, opts, binding.UNZIP);
268}
269
270// the Zlib class they all inherit from
271// This thing manages the queue of requests, and returns
272// true or false if there is anything in the queue when
273// you call the .write() method.
274
275export function Zlib(opts, mode) {
276 this._opts = opts = opts || {};
277 this._chunkSize = opts.chunkSize || binding.Z_DEFAULT_CHUNK;
278
279 Transform.call(this, opts);
280
281 if (opts.flush) {
282 if (opts.flush !== binding.Z_NO_FLUSH &&
283 opts.flush !== binding.Z_PARTIAL_FLUSH &&
284 opts.flush !== binding.Z_SYNC_FLUSH &&
285 opts.flush !== binding.Z_FULL_FLUSH &&
286 opts.flush !== binding.Z_FINISH &&
287 opts.flush !== binding.Z_BLOCK) {
288 throw new Error('Invalid flush flag: ' + opts.flush);
289 }
290 }
291 this._flushFlag = opts.flush || binding.Z_NO_FLUSH;
292
293 if (opts.chunkSize) {
294 if (opts.chunkSize < binding.Z_MIN_CHUNK ||
295 opts.chunkSize > binding.Z_MAX_CHUNK) {
296 throw new Error('Invalid chunk size: ' + opts.chunkSize);
297 }
298 }
299
300 if (opts.windowBits) {
301 if (opts.windowBits < binding.Z_MIN_WINDOWBITS ||
302 opts.windowBits > binding.Z_MAX_WINDOWBITS) {
303 throw new Error('Invalid windowBits: ' + opts.windowBits);
304 }
305 }
306
307 if (opts.level) {
308 if (opts.level < binding.Z_MIN_LEVEL ||
309 opts.level > binding.Z_MAX_LEVEL) {
310 throw new Error('Invalid compression level: ' + opts.level);
311 }
312 }
313
314 if (opts.memLevel) {
315 if (opts.memLevel < binding.Z_MIN_MEMLEVEL ||
316 opts.memLevel > binding.Z_MAX_MEMLEVEL) {
317 throw new Error('Invalid memLevel: ' + opts.memLevel);
318 }
319 }
320
321 if (opts.strategy) {
322 if (opts.strategy != binding.Z_FILTERED &&
323 opts.strategy != binding.Z_HUFFMAN_ONLY &&
324 opts.strategy != binding.Z_RLE &&
325 opts.strategy != binding.Z_FIXED &&
326 opts.strategy != binding.Z_DEFAULT_STRATEGY) {
327 throw new Error('Invalid strategy: ' + opts.strategy);
328 }
329 }
330
331 if (opts.dictionary) {
332 if (!Buffer.isBuffer(opts.dictionary)) {
333 throw new Error('Invalid dictionary: it should be a Buffer instance');
334 }
335 }
336
337 this._binding = new binding.Zlib(mode);
338
339 var self = this;
340 this._hadError = false;
341 this._binding.onerror = function(message, errno) {
342 // there is no way to cleanly recover.
343 // continuing only obscures problems.
344 self._binding = null;
345 self._hadError = true;
346
347 var error = new Error(message);
348 error.errno = errno;
349 error.code = binding.codes[errno];
350 self.emit('error', error);
351 };
352
353 var level = binding.Z_DEFAULT_COMPRESSION;
354 if (typeof opts.level === 'number') level = opts.level;
355
356 var strategy = binding.Z_DEFAULT_STRATEGY;
357 if (typeof opts.strategy === 'number') strategy = opts.strategy;
358
359 this._binding.init(opts.windowBits || binding.Z_DEFAULT_WINDOWBITS,
360 level,
361 opts.memLevel || binding.Z_DEFAULT_MEMLEVEL,
362 strategy,
363 opts.dictionary);
364
365 this._buffer = new Buffer(this._chunkSize);
366 this._offset = 0;
367 this._closed = false;
368 this._level = level;
369 this._strategy = strategy;
370
371 this.once('end', this.close);
372}
373
374inherits(Zlib, Transform);
375
376Zlib.prototype.params = function(level, strategy, callback) {
377 if (level < binding.Z_MIN_LEVEL ||
378 level > binding.Z_MAX_LEVEL) {
379 throw new RangeError('Invalid compression level: ' + level);
380 }
381 if (strategy != binding.Z_FILTERED &&
382 strategy != binding.Z_HUFFMAN_ONLY &&
383 strategy != binding.Z_RLE &&
384 strategy != binding.Z_FIXED &&
385 strategy != binding.Z_DEFAULT_STRATEGY) {
386 throw new TypeError('Invalid strategy: ' + strategy);
387 }
388
389 if (this._level !== level || this._strategy !== strategy) {
390 var self = this;
391 this.flush(binding.Z_SYNC_FLUSH, function() {
392 self._binding.params(level, strategy);
393 if (!self._hadError) {
394 self._level = level;
395 self._strategy = strategy;
396 if (callback) callback();
397 }
398 });
399 } else {
400 process.nextTick(callback);
401 }
402};
403
404Zlib.prototype.reset = function() {
405 return this._binding.reset();
406};
407
408// This is the _flush function called by the transform class,
409// internally, when the last chunk has been written.
410Zlib.prototype._flush = function(callback) {
411 this._transform(new Buffer(0), '', callback);
412};
413
414Zlib.prototype.flush = function(kind, callback) {
415 var ws = this._writableState;
416
417 if (typeof kind === 'function' || (kind === void 0 && !callback)) {
418 callback = kind;
419 kind = binding.Z_FULL_FLUSH;
420 }
421
422 if (ws.ended) {
423 if (callback)
424 process.nextTick(callback);
425 } else if (ws.ending) {
426 if (callback)
427 this.once('end', callback);
428 } else if (ws.needDrain) {
429 var self = this;
430 this.once('drain', function() {
431 self.flush(callback);
432 });
433 } else {
434 this._flushFlag = kind;
435 this.write(new Buffer(0), '', callback);
436 }
437};
438
439Zlib.prototype.close = function(callback) {
440 if (callback)
441 process.nextTick(callback);
442
443 if (this._closed)
444 return;
445
446 this._closed = true;
447
448 this._binding.close();
449
450 var self = this;
451 process.nextTick(function() {
452 self.emit('close');
453 });
454};
455
456Zlib.prototype._transform = function(chunk, encoding, cb) {
457 var flushFlag;
458 var ws = this._writableState;
459 var ending = ws.ending || ws.ended;
460 var last = ending && (!chunk || ws.length === chunk.length);
461
462 if (!chunk === null && !Buffer.isBuffer(chunk))
463 return cb(new Error('invalid input'));
464
465 // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag.
466 // If it's explicitly flushing at some other time, then we use
467 // Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression
468 // goodness.
469 if (last)
470 flushFlag = binding.Z_FINISH;
471 else {
472 flushFlag = this._flushFlag;
473 // once we've flushed the last of the queue, stop flushing and
474 // go back to the normal behavior.
475 if (chunk.length >= ws.length) {
476 this._flushFlag = this._opts.flush || binding.Z_NO_FLUSH;
477 }
478 }
479
480 this._processChunk(chunk, flushFlag, cb);
481};
482
483Zlib.prototype._processChunk = function(chunk, flushFlag, cb) {
484 var availInBefore = chunk && chunk.length;
485 var availOutBefore = this._chunkSize - this._offset;
486 var inOff = 0;
487
488 var self = this;
489
490 var async = typeof cb === 'function';
491
492 if (!async) {
493 var buffers = [];
494 var nread = 0;
495
496 var error;
497 this.on('error', function(er) {
498 error = er;
499 });
500
501 do {
502 var res = this._binding.writeSync(flushFlag,
503 chunk, // in
504 inOff, // in_off
505 availInBefore, // in_len
506 this._buffer, // out
507 this._offset, //out_off
508 availOutBefore); // out_len
509 } while (!this._hadError && callback(res[0], res[1]));
510
511 if (this._hadError) {
512 throw error;
513 }
514
515 var buf = Buffer.concat(buffers, nread);
516 this.close();
517
518 return buf;
519 }
520
521 var req = this._binding.write(flushFlag,
522 chunk, // in
523 inOff, // in_off
524 availInBefore, // in_len
525 this._buffer, // out
526 this._offset, //out_off
527 availOutBefore); // out_len
528
529 req.buffer = chunk;
530 req.callback = callback;
531
532 function callback(availInAfter, availOutAfter) {
533 if (self._hadError)
534 return;
535
536 var have = availOutBefore - availOutAfter;
537 assert(have >= 0, 'have should not go down');
538
539 if (have > 0) {
540 var out = self._buffer.slice(self._offset, self._offset + have);
541 self._offset += have;
542 // serve some output to the consumer.
543 if (async) {
544 self.push(out);
545 } else {
546 buffers.push(out);
547 nread += out.length;
548 }
549 }
550
551 // exhausted the output buffer, or used all the input create a new one.
552 if (availOutAfter === 0 || self._offset >= self._chunkSize) {
553 availOutBefore = self._chunkSize;
554 self._offset = 0;
555 self._buffer = new Buffer(self._chunkSize);
556 }
557
558 if (availOutAfter === 0) {
559 // Not actually done. Need to reprocess.
560 // Also, update the availInBefore to the availInAfter value,
561 // so that if we have to hit it a third (fourth, etc.) time,
562 // it'll have the correct byte counts.
563 inOff += (availInBefore - availInAfter);
564 availInBefore = availInAfter;
565
566 if (!async)
567 return true;
568
569 var newReq = self._binding.write(flushFlag,
570 chunk,
571 inOff,
572 availInBefore,
573 self._buffer,
574 self._offset,
575 self._chunkSize);
576 newReq.callback = callback; // this same function
577 newReq.buffer = chunk;
578 return;
579 }
580
581 if (!async)
582 return false;
583
584 // finished with the chunk.
585 cb();
586 }
587};
588
589inherits(Deflate, Zlib);
590inherits(Inflate, Zlib);
591inherits(Gzip, Zlib);
592inherits(Gunzip, Zlib);
593inherits(DeflateRaw, Zlib);
594inherits(InflateRaw, Zlib);
595inherits(Unzip, Zlib);
596export default {
597 codes: codes,
598 createDeflate: createDeflate,
599 createInflate: createInflate,
600 createDeflateRaw: createDeflateRaw,
601 createInflateRaw: createInflateRaw,
602 createGzip: createGzip,
603 createGunzip: createGunzip,
604 createUnzip: createUnzip,
605 deflate: deflate,
606 deflateSync: deflateSync,
607 gzip: gzip,
608 gzipSync: gzipSync,
609 deflateRaw: deflateRaw,
610 deflateRawSync: deflateRawSync,
611 unzip: unzip,
612 unzipSync: unzipSync,
613 inflate: inflate,
614 inflateSync: inflateSync,
615 gunzip: gunzip,
616 gunzipSync: gunzipSync,
617 inflateRaw: inflateRaw,
618 inflateRawSync: inflateRawSync,
619 Deflate: Deflate,
620 Inflate: Inflate,
621 Gzip: Gzip,
622 Gunzip: Gunzip,
623 DeflateRaw: DeflateRaw,
624 InflateRaw: InflateRaw,
625 Unzip: Unzip,
626 Zlib: Zlib
627};