UNPKG

react-jquery-datatables

Version:

React, DataTables.net (aka jQuery DataTables), fork of https://github.com/carlosrocha/react-data-components

1,637 lines (1,393 loc) 1.4 MB
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {module.exports = global["pdfMake"] = __webpack_require__(1); /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(Buffer) {/* jslint node: true */ /* jslint browser: true */ /* global BlobBuilder */ 'use strict'; var PdfPrinter = __webpack_require__(2); var saveAs = __webpack_require__(3); var defaultClientFonts = { Roboto: { normal: 'Roboto-Regular.ttf', bold: 'Roboto-Medium.ttf', italics: 'Roboto-Italic.ttf', bolditalics: 'Roboto-Italic.ttf' } }; function Document(docDefinition, fonts, vfs) { this.docDefinition = docDefinition; this.fonts = fonts || defaultClientFonts; this.vfs = vfs; } Document.prototype._createDoc = function(options, callback) { var printer = new PdfPrinter(this.fonts); printer.fs.bindFS(this.vfs); var doc = printer.createPdfKitDocument(this.docDefinition, options); var chunks = []; var result; doc.on('data', function(chunk) { chunks.push(chunk); }); doc.on('end', function() { result = Buffer.concat(chunks); callback(result, doc._pdfMakePages); }); doc.end(); }; Document.prototype._getPages = function(options, cb){ if (!cb) throw 'getBuffer is an async method and needs a callback argument'; this._createDoc(options, function(ignoreBuffer, pages){ cb(pages); }); }; Document.prototype.open = function(message) { // we have to open the window immediately and store the reference // otherwise popup blockers will stop us var win = window.open('', '_blank'); try { this.getDataUrl(function(result) { win.location.href = result; }); } catch(e) { win.close(); throw e; } }; Document.prototype.print = function() { this.getDataUrl(function(dataUrl) { var iFrame = document.createElement('iframe'); iFrame.style.position = 'absolute'; iFrame.style.left = '-99999px'; iFrame.src = dataUrl; iFrame.onload = function() { function removeIFrame(){ document.body.removeChild(iFrame); document.removeEventListener('click', removeIFrame); } document.addEventListener('click', removeIFrame, false); }; document.body.appendChild(iFrame); }, { autoPrint: true }); }; Document.prototype.download = function(defaultFileName, cb) { if(typeof defaultFileName === "function") { cb = defaultFileName; defaultFileName = null; } defaultFileName = defaultFileName || 'file.pdf'; this.getBuffer(function(result) { saveAs(new Blob([result], {type: 'application/pdf'}), defaultFileName); if (typeof cb === "function") { cb(); } }); }; Document.prototype.getBase64 = function(cb, options) { if (!cb) throw 'getBase64 is an async method and needs a callback argument'; this._createDoc(options, function(buffer) { cb(buffer.toString('base64')); }); }; Document.prototype.getDataUrl = function(cb, options) { if (!cb) throw 'getDataUrl is an async method and needs a callback argument'; this._createDoc(options, function(buffer) { cb('data:application/pdf;base64,' + buffer.toString('base64')); }); }; Document.prototype.getBuffer = function(cb, options) { if (!cb) throw 'getBuffer is an async method and needs a callback argument'; this._createDoc(options, function(buffer){ cb(buffer); }); }; module.exports = { createPdf: function(docDefinition) { return new Document(docDefinition, window.pdfMake.fonts, window.pdfMake.vfs); } }; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4).Buffer)) /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { /* jslint node: true */ /* global window */ 'use strict'; var _ = __webpack_require__(11); var FontProvider = __webpack_require__(5); var LayoutBuilder = __webpack_require__(6); var PdfKit = __webpack_require__(28); var PDFReference = __webpack_require__(12); var sizes = __webpack_require__(7); var ImageMeasure = __webpack_require__(8); var textDecorator = __webpack_require__(9); var FontProvider = __webpack_require__(5); //////////////////////////////////////// // PdfPrinter /** * @class Creates an instance of a PdfPrinter which turns document definition into a pdf * * @param {Object} fontDescriptors font definition dictionary * * @example * var fontDescriptors = { * Roboto: { * normal: 'fonts/Roboto-Regular.ttf', * bold: 'fonts/Roboto-Medium.ttf', * italics: 'fonts/Roboto-Italic.ttf', * bolditalics: 'fonts/Roboto-Italic.ttf' * } * }; * * var printer = new PdfPrinter(fontDescriptors); */ function PdfPrinter(fontDescriptors) { this.fontDescriptors = fontDescriptors; } /** * Executes layout engine for the specified document and renders it into a pdfkit document * ready to be saved. * * @param {Object} docDefinition document definition * @param {Object} docDefinition.content an array describing the pdf structure (for more information take a look at the examples in the /examples folder) * @param {Object} [docDefinition.defaultStyle] default (implicit) style definition * @param {Object} [docDefinition.styles] dictionary defining all styles which can be used in the document * @param {Object} [docDefinition.pageSize] page size (pdfkit units, A4 dimensions by default) * @param {Number} docDefinition.pageSize.width width * @param {Number} docDefinition.pageSize.height height * @param {Object} [docDefinition.pageMargins] page margins (pdfkit units) * * @example * * var docDefinition = { * content: [ * 'First paragraph', * 'Second paragraph, this time a little bit longer', * { text: 'Third paragraph, slightly bigger font size', fontSize: 20 }, * { text: 'Another paragraph using a named style', style: 'header' }, * { text: ['playing with ', 'inlines' ] }, * { text: ['and ', { text: 'restyling ', bold: true }, 'them'] }, * ], * styles: { * header: { fontSize: 30, bold: true } * } * } * * var pdfDoc = printer.createPdfKitDocument(docDefinition); * * pdfDoc.pipe(fs.createWriteStream('sample.pdf')); * pdfDoc.end(); * * @return {Object} a pdfKit document object which can be saved or encode to data-url */ PdfPrinter.prototype.createPdfKitDocument = function(docDefinition, options) { options = options || {}; var pageSize = pageSize2widthAndHeight(docDefinition.pageSize || 'a4'); if(docDefinition.pageOrientation === 'landscape') { pageSize = { width: pageSize.height, height: pageSize.width}; } pageSize.orientation = docDefinition.pageOrientation === 'landscape' ? docDefinition.pageOrientation : 'portrait'; this.pdfKitDoc = new PdfKit({ size: [ pageSize.width, pageSize.height ], compress: false}); this.pdfKitDoc.info.Producer = 'pdfmake'; this.pdfKitDoc.info.Creator = 'pdfmake'; this.fontProvider = new FontProvider(this.fontDescriptors, this.pdfKitDoc); docDefinition.images = docDefinition.images || {}; var builder = new LayoutBuilder( pageSize, fixPageMargins(docDefinition.pageMargins || 40), new ImageMeasure(this.pdfKitDoc, docDefinition.images)); registerDefaultTableLayouts(builder); if (options.tableLayouts) { builder.registerTableLayouts(options.tableLayouts); } var pages = builder.layoutDocument(docDefinition.content, this.fontProvider, docDefinition.styles || {}, docDefinition.defaultStyle || { fontSize: 12, font: 'Roboto' }, docDefinition.background, docDefinition.header, docDefinition.footer, docDefinition.images, docDefinition.watermark, docDefinition.pageBreakBefore); renderPages(pages, this.fontProvider, this.pdfKitDoc); if(options.autoPrint){ var jsRef = this.pdfKitDoc.ref({ S: 'JavaScript', JS: new StringObject('this.print\\(true\\);') }); var namesRef = this.pdfKitDoc.ref({ Names: [new StringObject('EmbeddedJS'), new PDFReference(this.pdfKitDoc, jsRef.id)], }); jsRef.end(); namesRef.end(); this.pdfKitDoc._root.data.Names = { JavaScript: new PDFReference(this.pdfKitDoc, namesRef.id) }; } return this.pdfKitDoc; }; function fixPageMargins(margin) { if (!margin) return null; if (typeof margin === 'number' || margin instanceof Number) { margin = { left: margin, right: margin, top: margin, bottom: margin }; } else if (margin instanceof Array) { if (margin.length === 2) { margin = { left: margin[0], top: margin[1], right: margin[0], bottom: margin[1] }; } else if (margin.length === 4) { margin = { left: margin[0], top: margin[1], right: margin[2], bottom: margin[3] }; } else throw 'Invalid pageMargins definition'; } return margin; } function registerDefaultTableLayouts(layoutBuilder) { layoutBuilder.registerTableLayouts({ noBorders: { hLineWidth: function(i) { return 0; }, vLineWidth: function(i) { return 0; }, paddingLeft: function(i) { return i && 4 || 0; }, paddingRight: function(i, node) { return (i < node.table.widths.length - 1) ? 4 : 0; }, }, headerLineOnly: { hLineWidth: function(i, node) { if (i === 0 || i === node.table.body.length) return 0; return (i === node.table.headerRows) ? 2 : 0; }, vLineWidth: function(i) { return 0; }, paddingLeft: function(i) { return i === 0 ? 0 : 8; }, paddingRight: function(i, node) { return (i === node.table.widths.length - 1) ? 0 : 8; } }, lightHorizontalLines: { hLineWidth: function(i, node) { if (i === 0 || i === node.table.body.length) return 0; return (i === node.table.headerRows) ? 2 : 1; }, vLineWidth: function(i) { return 0; }, hLineColor: function(i) { return i === 1 ? 'black' : '#aaa'; }, paddingLeft: function(i) { return i === 0 ? 0 : 8; }, paddingRight: function(i, node) { return (i === node.table.widths.length - 1) ? 0 : 8; } } }); } var defaultLayout = { hLineWidth: function(i, node) { return 1; }, //return node.table.headerRows && i === node.table.headerRows && 3 || 0; }, vLineWidth: function(i, node) { return 1; }, hLineColor: function(i, node) { return 'black'; }, vLineColor: function(i, node) { return 'black'; }, paddingLeft: function(i, node) { return 4; }, //i && 4 || 0; }, paddingRight: function(i, node) { return 4; }, //(i < node.table.widths.length - 1) ? 4 : 0; }, paddingTop: function(i, node) { return 2; }, paddingBottom: function(i, node) { return 2; } }; function pageSize2widthAndHeight(pageSize) { if (typeof pageSize == 'string' || pageSize instanceof String) { var size = sizes[pageSize.toUpperCase()]; if (!size) throw ('Page size ' + pageSize + ' not recognized'); return { width: size[0], height: size[1] }; } return pageSize; } function StringObject(str){ this.isString = true; this.toString = function(){ return str; }; } function updatePageOrientationInOptions(currentPage, pdfKitDoc) { var previousPageOrientation = pdfKitDoc.options.size[0] > pdfKitDoc.options.size[1] ? 'landscape' : 'portrait'; if(currentPage.pageSize.orientation !== previousPageOrientation) { var width = pdfKitDoc.options.size[0]; var height = pdfKitDoc.options.size[1]; pdfKitDoc.options.size = [height, width]; } } function renderPages(pages, fontProvider, pdfKitDoc) { pdfKitDoc._pdfMakePages = pages; for (var i = 0; i < pages.length; i++) { if (i > 0) { updatePageOrientationInOptions(pages[i], pdfKitDoc); pdfKitDoc.addPage(pdfKitDoc.options); } var page = pages[i]; for(var ii = 0, il = page.items.length; ii < il; ii++) { var item = page.items[ii]; switch(item.type) { case 'vector': renderVector(item.item, pdfKitDoc); break; case 'line': renderLine(item.item, item.item.x, item.item.y, pdfKitDoc); break; case 'image': renderImage(item.item, item.item.x, item.item.y, pdfKitDoc); break; } } if(page.watermark){ renderWatermark(page, pdfKitDoc); } fontProvider.setFontRefsToPdfDoc(); } } function renderLine(line, x, y, pdfKitDoc) { x = x || 0; y = y || 0; var ascenderHeight = line.getAscenderHeight(); textDecorator.drawBackground(line, x, y, pdfKitDoc); //TODO: line.optimizeInlines(); for(var i = 0, l = line.inlines.length; i < l; i++) { var inline = line.inlines[i]; pdfKitDoc.fill(inline.color || 'black'); pdfKitDoc.save(); pdfKitDoc.transform(1, 0, 0, -1, 0, pdfKitDoc.page.height); var encoded = inline.font.encode(inline.text); pdfKitDoc.addContent('BT'); pdfKitDoc.addContent('' + (x + inline.x) + ' ' + (pdfKitDoc.page.height - y - ascenderHeight) + ' Td'); pdfKitDoc.addContent('/' + encoded.fontId + ' ' + inline.fontSize + ' Tf'); pdfKitDoc.addContent('<' + encoded.encodedText + '> Tj'); pdfKitDoc.addContent('ET'); pdfKitDoc.restore(); } textDecorator.drawDecorations(line, x, y, pdfKitDoc); } function renderWatermark(page, pdfKitDoc){ var watermark = page.watermark; pdfKitDoc.fill('black'); pdfKitDoc.opacity(0.6); pdfKitDoc.save(); pdfKitDoc.transform(1, 0, 0, -1, 0, pdfKitDoc.page.height); var angle = Math.atan2(pdfKitDoc.page.height, pdfKitDoc.page.width) * 180/Math.PI; pdfKitDoc.rotate(angle, {origin: [pdfKitDoc.page.width/2, pdfKitDoc.page.height/2]}); var encoded = watermark.font.encode(watermark.text); pdfKitDoc.addContent('BT'); pdfKitDoc.addContent('' + (pdfKitDoc.page.width/2 - watermark.size.size.width/2) + ' ' + (pdfKitDoc.page.height/2 - watermark.size.size.height/4) + ' Td'); pdfKitDoc.addContent('/' + encoded.fontId + ' ' + watermark.size.fontSize + ' Tf'); pdfKitDoc.addContent('<' + encoded.encodedText + '> Tj'); pdfKitDoc.addContent('ET'); pdfKitDoc.restore(); } function renderVector(vector, pdfDoc) { //TODO: pdf optimization (there's no need to write all properties everytime) pdfDoc.lineWidth(vector.lineWidth || 1); if (vector.dash) { pdfDoc.dash(vector.dash.length, { space: vector.dash.space || vector.dash.length }); } else { pdfDoc.undash(); } pdfDoc.fillOpacity(vector.fillOpacity || 1); pdfDoc.strokeOpacity(vector.strokeOpacity || 1); pdfDoc.lineJoin(vector.lineJoin || 'miter'); //TODO: clipping switch(vector.type) { case 'ellipse': pdfDoc.ellipse(vector.x, vector.y, vector.r1, vector.r2); break; case 'rect': if (vector.r) { pdfDoc.roundedRect(vector.x, vector.y, vector.w, vector.h, vector.r); } else { pdfDoc.rect(vector.x, vector.y, vector.w, vector.h); } break; case 'line': pdfDoc.moveTo(vector.x1, vector.y1); pdfDoc.lineTo(vector.x2, vector.y2); break; case 'polyline': if (vector.points.length === 0) break; pdfDoc.moveTo(vector.points[0].x, vector.points[0].y); for(var i = 1, l = vector.points.length; i < l; i++) { pdfDoc.lineTo(vector.points[i].x, vector.points[i].y); } if (vector.points.length > 1) { var p1 = vector.points[0]; var pn = vector.points[vector.points.length - 1]; if (vector.closePath || p1.x === pn.x && p1.y === pn.y) { pdfDoc.closePath(); } } break; } if (vector.color && vector.lineColor) { pdfDoc.fillAndStroke(vector.color, vector.lineColor); } else if (vector.color) { pdfDoc.fill(vector.color); } else { pdfDoc.stroke(vector.lineColor || 'black'); } } function renderImage(image, x, y, pdfKitDoc) { pdfKitDoc.image(image.image, image.x, image.y, { width: image._width, height: image._height }); } module.exports = PdfPrinter; /* temporary browser extension */ PdfPrinter.prototype.fs = __webpack_require__(10); /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(module) {/* FileSaver.js * A saveAs() FileSaver implementation. * 2014-08-29 * * By Eli Grey, http://eligrey.com * License: X11/MIT * See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md */ /*global self */ /*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */ /*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */ var saveAs = saveAs // IE 10+ (native saveAs) || (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob && navigator.msSaveOrOpenBlob.bind(navigator)) // Everyone else || (function(view) { "use strict"; // IE <10 is explicitly unsupported if (typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) { return; } var doc = view.document // only get URL when necessary in case Blob.js hasn't overridden it yet , get_URL = function() { return view.URL || view.webkitURL || view; } , save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a") , can_use_save_link = "download" in save_link , click = function(node) { var event = doc.createEvent("MouseEvents"); event.initMouseEvent( "click", true, false, view, 0, 0, 0, 0, 0 , false, false, false, false, 0, null ); node.dispatchEvent(event); } , webkit_req_fs = view.webkitRequestFileSystem , req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem , throw_outside = function(ex) { (view.setImmediate || view.setTimeout)(function() { throw ex; }, 0); } , force_saveable_type = "application/octet-stream" , fs_min_size = 0 // See https://code.google.com/p/chromium/issues/detail?id=375297#c7 for // the reasoning behind the timeout and revocation flow , arbitrary_revoke_timeout = 10 , revoke = function(file) { var revoker = function() { if (typeof file === "string") { // file is an object URL get_URL().revokeObjectURL(file); } else { // file is a File file.remove(); } }; if (view.chrome) { revoker(); } else { setTimeout(revoker, arbitrary_revoke_timeout); } } , dispatch = function(filesaver, event_types, event) { event_types = [].concat(event_types); var i = event_types.length; while (i--) { var listener = filesaver["on" + event_types[i]]; if (typeof listener === "function") { try { listener.call(filesaver, event || filesaver); } catch (ex) { throw_outside(ex); } } } } , FileSaver = function(blob, name) { // First try a.download, then web filesystem, then object URLs var filesaver = this , type = blob.type , blob_changed = false , object_url , target_view , dispatch_all = function() { dispatch(filesaver, "writestart progress write writeend".split(" ")); } // on any filesys errors revert to saving with object URLs , fs_error = function() { // don't create more object URLs than needed if (blob_changed || !object_url) { object_url = get_URL().createObjectURL(blob); } if (target_view) { target_view.location.href = object_url; } else { var new_tab = view.open(object_url, "_blank"); if (new_tab == undefined && typeof safari !== "undefined") { //Apple do not allow window.open, see http://bit.ly/1kZffRI view.location.href = object_url } } filesaver.readyState = filesaver.DONE; dispatch_all(); revoke(object_url); } , abortable = function(func) { return function() { if (filesaver.readyState !== filesaver.DONE) { return func.apply(this, arguments); } }; } , create_if_not_found = {create: true, exclusive: false} , slice ; filesaver.readyState = filesaver.INIT; if (!name) { name = "download"; } if (can_use_save_link) { object_url = get_URL().createObjectURL(blob); save_link.href = object_url; save_link.download = name; click(save_link); filesaver.readyState = filesaver.DONE; dispatch_all(); revoke(object_url); return; } // Object and web filesystem URLs have a problem saving in Google Chrome when // viewed in a tab, so I force save with application/octet-stream // http://code.google.com/p/chromium/issues/detail?id=91158 // Update: Google errantly closed 91158, I submitted it again: // https://code.google.com/p/chromium/issues/detail?id=389642 if (view.chrome && type && type !== force_saveable_type) { slice = blob.slice || blob.webkitSlice; blob = slice.call(blob, 0, blob.size, force_saveable_type); blob_changed = true; } // Since I can't be sure that the guessed media type will trigger a download // in WebKit, I append .download to the filename. // https://bugs.webkit.org/show_bug.cgi?id=65440 if (webkit_req_fs && name !== "download") { name += ".download"; } if (type === force_saveable_type || webkit_req_fs) { target_view = view; } if (!req_fs) { fs_error(); return; } fs_min_size += blob.size; req_fs(view.TEMPORARY, fs_min_size, abortable(function(fs) { fs.root.getDirectory("saved", create_if_not_found, abortable(function(dir) { var save = function() { dir.getFile(name, create_if_not_found, abortable(function(file) { file.createWriter(abortable(function(writer) { writer.onwriteend = function(event) { target_view.location.href = file.toURL(); filesaver.readyState = filesaver.DONE; dispatch(filesaver, "writeend", event); revoke(file); }; writer.onerror = function() { var error = writer.error; if (error.code !== error.ABORT_ERR) { fs_error(); } }; "writestart progress write abort".split(" ").forEach(function(event) { writer["on" + event] = filesaver["on" + event]; }); writer.write(blob); filesaver.abort = function() { writer.abort(); filesaver.readyState = filesaver.DONE; }; filesaver.readyState = filesaver.WRITING; }), fs_error); }), fs_error); }; dir.getFile(name, {create: false}, abortable(function(file) { // delete file if it already exists file.remove(); save(); }), abortable(function(ex) { if (ex.code === ex.NOT_FOUND_ERR) { save(); } else { fs_error(); } })); }), fs_error); }), fs_error); } , FS_proto = FileSaver.prototype , saveAs = function(blob, name) { return new FileSaver(blob, name); } ; FS_proto.abort = function() { var filesaver = this; filesaver.readyState = filesaver.DONE; dispatch(filesaver, "abort"); }; FS_proto.readyState = FS_proto.INIT = 0; FS_proto.WRITING = 1; FS_proto.DONE = 2; FS_proto.error = FS_proto.onwritestart = FS_proto.onprogress = FS_proto.onwrite = FS_proto.onabort = FS_proto.onerror = FS_proto.onwriteend = null; return saveAs; }( typeof self !== "undefined" && self || typeof window !== "undefined" && window || this.content )); // `self` is undefined in Firefox for Android content script context // while `this` is nsIContentFrameMessageManager // with an attribute `content` that corresponds to the window if (typeof module !== "undefined" && module !== null) { module.exports = saveAs; } else if (("function" !== "undefined" && __webpack_require__(13) !== null) && (__webpack_require__(14) != null)) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() { return saveAs; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(15)(module))) /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(Buffer) {/*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org> * @license MIT */ var base64 = __webpack_require__(31) var ieee754 = __webpack_require__(29) var isArray = __webpack_require__(30) exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer exports.INSPECT_MAX_BYTES = 50 Buffer.poolSize = 8192 // not used by this implementation var kMaxLength = 0x3fffffff var rootParent = {} /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Use Object implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * Note: * * - Implementation must support adding new properties to `Uint8Array` instances. * Firefox 4-29 lacked support, fixed in Firefox 30+. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. * * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. * * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of * incorrect length in some situations. * * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they will * get the Object implementation, which is slower but will work correctly. */ Buffer.TYPED_ARRAY_SUPPORT = (function () { try { var buf = new ArrayBuffer(0) var arr = new Uint8Array(buf) arr.foo = function () { return 42 } return arr.foo() === 42 && // typed array instances can be augmented typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` new Uint8Array(1).subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` } catch (e) { return false } })() /** * Class: Buffer * ============= * * The Buffer constructor returns instances of `Uint8Array` that are augmented * with function properties for all the node `Buffer` API functions. We use * `Uint8Array` so that square bracket notation works as expected -- it returns * a single octet. * * By augmenting the instances, we can avoid modifying the `Uint8Array` * prototype. */ function Buffer (arg) { if (!(this instanceof Buffer)) { // Avoid going through an ArgumentsAdaptorTrampoline in the common case. if (arguments.length > 1) return new Buffer(arg, arguments[1]) return new Buffer(arg) } this.length = 0 this.parent = undefined // Common case. if (typeof arg === 'number') { return fromNumber(this, arg) } // Slightly less common case. if (typeof arg === 'string') { return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8') } // Unusual. return fromObject(this, arg) } function fromNumber (that, length) { that = allocate(that, length < 0 ? 0 : checked(length) | 0) if (!Buffer.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < length; i++) { that[i] = 0 } } return that } function fromString (that, string, encoding) { if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8' // Assumption: byteLength() return value is always < kMaxLength. var length = byteLength(string, encoding) | 0 that = allocate(that, length) that.write(string, encoding) return that } function fromObject (that, object) { if (Buffer.isBuffer(object)) return fromBuffer(that, object) if (isArray(object)) return fromArray(that, object) if (object == null) { throw new TypeError('must start with number, buffer, array or string') } if (typeof ArrayBuffer !== 'undefined' && object.buffer instanceof ArrayBuffer) { return fromTypedArray(that, object) } if (object.length) return fromArrayLike(that, object) return fromJsonObject(that, object) } function fromBuffer (that, buffer) { var length = checked(buffer.length) | 0 that = allocate(that, length) buffer.copy(that, 0, 0, length) return that } function fromArray (that, array) { var length = checked(array.length) | 0 that = allocate(that, length) for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } // Duplicate of fromArray() to keep fromArray() monomorphic. function fromTypedArray (that, array) { var length = checked(array.length) | 0 that = allocate(that, length) // Truncating the elements is probably not what people expect from typed // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior // of the old Buffer constructor. for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } function fromArrayLike (that, array) { var length = checked(array.length) | 0 that = allocate(that, length) for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } // Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object. // Returns a zero-length buffer for inputs that don't conform to the spec. function fromJsonObject (that, object) { var array var length = 0 if (object.type === 'Buffer' && isArray(object.data)) { array = object.data length = checked(array.length) | 0 } that = allocate(that, length) for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } function allocate (that, length) { if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = Buffer._augment(new Uint8Array(length)) } else { // Fallback: Return an object instance of the Buffer class that.length = length that._isBuffer = true } var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1 if (fromPool) that.parent = rootParent return that } function checked (length) { // Note: cannot use `length < kMaxLength` here because that fails when // length is NaN (which is otherwise coerced to zero.) if (length >= kMaxLength) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + kMaxLength.toString(16) + ' bytes') } return length | 0 } function SlowBuffer (subject, encoding) { if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding) var buf = new Buffer(subject, encoding) delete buf.parent return buf } Buffer.isBuffer = function isBuffer (b) { return !!(b != null && b._isBuffer) } Buffer.compare = function compare (a, b) { if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { throw new TypeError('Arguments must be Buffers') } if (a === b) return 0 var x = a.length var y = b.length var i = 0 var len = Math.min(x, y) while (i < len) { if (a[i] !== b[i]) break ++i } if (i !== len) { x = a[i] y = b[i] } if (x < y) return -1 if (y < x) return 1 return 0 } Buffer.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'raw': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true default: return false } } Buffer.concat = function concat (list, length) { if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.') if (list.length === 0) { return new Buffer(0) } else if (list.length === 1) { return list[0] } var i if (length === undefined) { length = 0 for (i = 0; i < list.length; i++) { length += list[i].length } } var buf = new Buffer(length) var pos = 0 for (i = 0; i < list.length; i++) { var item = list[i] item.copy(buf, pos) pos += item.length } return buf } function byteLength (string, encoding) { if (typeof string !== 'string') string = String(string) if (string.length === 0) return 0 switch (encoding || 'utf8') { case 'ascii': case 'binary': case 'raw': return string.length case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return string.length * 2 case 'hex': return string.length >>> 1 case 'utf8': case 'utf-8': return utf8ToBytes(string).length case 'base64': return base64ToBytes(string).length default: return string.length } } Buffer.byteLength = byteLength // pre-set for values that may exist in the future Buffer.prototype.length = undefined Buffer.prototype.parent = undefined // toString(encoding, start=0, end=buffer.length) Buffer.prototype.toString = function toString (encoding, start, end) { var loweredCase = false start = start | 0 end = end === undefined || end === Infinity ? this.length : end | 0 if (!encoding) encoding = 'utf8' if (start < 0) start = 0 if (end > this.length) end = this.length if (end <= start) return '' while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end) case 'utf8': case 'utf-8': return utf8Slice(this, start, end) case 'ascii': return asciiSlice(this, start, end) case 'binary': return binarySlice(this, start, end) case 'base64': return base64Slice(this, start, end) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = (encoding + '').toLowerCase() loweredCase = true } } } Buffer.prototype.equals = function equals (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true return Buffer.compare(this, b) === 0 } Buffer.prototype.inspect = function inspect () { var str = '' var max = exports.INSPECT_MAX_BYTES if (this.length > 0) { str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') if (this.length > max) str += ' ... ' } return '<Buffer ' + str + '>' } Buffer.prototype.compare = function compare (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return 0 return Buffer.compare(this, b) } Buffer.prototype.indexOf = function indexOf (val, byteOffset) { if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff else if (byteOffset < -0x80000000) byteOffset = -0x80000000 byteOffset >>= 0 if (this.length === 0) return -1 if (byteOffset >= this.length) return -1 // Negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0) if (typeof val === 'string') { if (val.length === 0) return -1 // special case: looking for empty string always fails return String.prototype.indexOf.call(this, val, byteOffset) } if (Buffer.isBuffer(val)) { return arrayIndexOf(this, val, byteOffset) } if (typeof val === 'number') { if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') { return Uint8Array.prototype.indexOf.call(this, val, byteOffset) } return arrayIndexOf(this, [ val ], byteOffset) } function arrayIndexOf (arr, val, byteOffset) { var foundIndex = -1 for (var i = 0; byteOffset + i < arr.length; i++) { if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) { if (foundIndex === -1) foundIndex = i if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex } else { foundIndex = -1 } } return -1 } throw new TypeError('val must be string, number or Buffer') } // `get` will be removed in Node 0.13+ Buffer.prototype.get = function get (offset) { console.log('.get() is deprecated. Access using array indexes instead.') return this.readUInt8(offset) } // `set` will be removed in Node 0.13+ Buffer.prototype.set = function set (v, offset) { console.log('.set() is deprecated. Access using array indexes instead.') return this.writeUInt8(v, offset) } function hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 var remaining = buf.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } // must be an even number of digits var strLen = string.length if (strLen % 2 !== 0) throw new Error('Invalid hex string') if (length > strLen / 2) { length = strLen / 2 } for (var i = 0; i < length; i++) { var parsed = parseInt(string.substr(i * 2, 2), 16) if (isNaN(parsed)) throw new Error('Invalid hex string') buf[offset + i] = parsed } return i } function utf8Write (buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } function asciiWrite (buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length) } function binaryWrite (buf, string, offset, length) { return asciiWrite(buf, string, offset, length) } function base64Write (buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length) } function ucs2Write (buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } Buffer.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8' length = this.length offset = 0 // Buffer#write(string, encoding) } else if (length === undefined && typeof offset === 'string') { encoding = offset length = this.length offset = 0 // Buffer#write(string, offset[, length][, encoding]) } else if (isFinite(offset)) { offset = offset | 0 if (isFinite(length)) { length = length | 0 if (encoding === undefined) encoding = 'utf8' } else { encoding = length length = undefined } // legacy write(string, encoding, offset, length) - remove in v0.13 } else { var swap = encoding encoding = offset offset = length | 0 length = swap } var remaining = this.length - offset if (length === undefined || length > remaining) length = remaining if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { throw new RangeError('attempt to write outside buffer bounds') } if (!encoding) encoding = 'utf8' var loweredCase = false for (;;) { switch (encoding) { case 'hex': return hexWrite(this, string, offset, length) case 'utf8': case 'utf-8': return utf8Write(this, string, offset, length) case 'ascii': return asciiWrite(this, string, offset, length) case 'binary': return binaryWrite(this, string, offset, length) case 'base64': // Warning: maxLength not taken into account in base64Write return base64Write(this, string, offset, length) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return ucs2Write(this, string, offset, length) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) } } function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf) } else { return base64.fromByteArray(buf.slice(start, end)) } } function utf8Slice (buf, start, end) { var res = '' var tmp = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) { if (buf[i] <= 0x7F) { res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i]) tmp = '' } else { tmp += '%' + buf[i].toString(16) } } return res + decodeUtf8Char(tmp) } function asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) { ret += String.fromCharCode(buf[i] & 0x7F) } return ret } function binarySlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; i++) { ret += String.fromCharCode(buf[i]) } return ret } function hexSlice (buf, start, end) { var len = buf.length if (!start || start < 0) start = 0 if (!end || end < 0 || end > len) end = len var out = '' for (var i = start; i < end; i++) { out += toHex(buf[i]) } return out } function utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) } return res } Buffer.prototype.slice = function slice (start, end) { var len = this.length start = ~~start end = end === undefined ? len : ~~end if (start < 0) { start += len if (start < 0) start = 0 } else if (start > len) { start = len } if (end < 0) { end += len if (end < 0) end = 0 } else if (end > len) { end = len } if (end < start) end = start var newBuf if (Buffer.TYPED_ARRAY_SUPPORT) { newBuf = Buffer._augment(this.subarray(start, end)) } else { var sliceLen = end - start newBuf = new Buffer(sliceLen, undefined) for (var i = 0; i < sliceLen; i++) { newBuf[i] = this[i + start] } } if (newBuf.length) newBuf.parent = this.parent || this return newBuf } /* * Need to make sure that buffer isn't trying to write out of bounds. */ function checkOffset (offset, ext, length) { if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } return val } Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) { checkOffset(offset, byteLength, this.length) } var val = this[offset + --byteLength] var mul = 1 while (byteLength > 0 && (mul *= 0x100)) { val += this[offset + --byteLength] * mul } return val } Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) return this[offset] } Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return this[offset] | (this[offset + 1] << 8) } Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return (this[offset] << 8) | this[offset + 1] } Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ((this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + (this[offset + 3] * 0x1000000) } Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] * 0x1000000) + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]) } Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var i = byteLength var mul = 1 var val = this[offset + --i] while (i > 0 && (mul *= 0x100)) { val += this[offset + --i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) } Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset] | (this[offset + 1] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset + 1] | (this[offset] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24) } Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | (this[offset + 3]) } Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, true, 23, 4) } Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) r