Jitsi Meet - Secure, Simple and Scalable Video Conferences that you use as a standalone app or embed in your web application.
TypeScript debiandeep-videojitsijitsi-meetscalable-video-conferencessfuvideovideo-communicationvideo-conferencingwebrtc
Updates app.bundle.js and restores latest sdp-interop.
George Politisfb6ad8cffd13
diff --git a/index.html b/index.htmlindex 670a48dbc4..563cab48dc 100644--- a/index.html+++ b/index.html@@ -19,7 +19,7 @@<script src="libs/popover.js?v=1"></script><!-- bootstrap tooltip lib --><script src="libs/toastr.js?v=1"></script><!-- notifications lib --><script src="interface_config.js?v=5"></script>- <script src="libs/app.bundle.js?v=69"></script>+ <script src="libs/app.bundle.js?v=70"></script><script src="analytics.js?v=1"></script><!-- google analytics plugin --><link rel="stylesheet" href="css/font.css?v=7"/><link rel="stylesheet" href="css/toastr.css?v=1">diff --git a/libs/app.bundle.js b/libs/app.bundle.jsindex 514737391d..f04fb4a218 100644--- a/libs/app.bundle.js+++ b/libs/app.bundle.js@@ -1,63 +1,4 @@-!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.APP=e()}}(function(){var define,module,exports;return (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){-/* jshint -W117 */-/* application specific logic */--var APP =-{- init: function () {- this.UI = require("./modules/UI/UI");- this.API = require("./modules/API/API");- this.connectionquality = require("./modules/connectionquality/connectionquality");- this.statistics = require("./modules/statistics/statistics");- this.RTC = require("./modules/RTC/RTC");- this.simulcast = require("./modules/simulcast/simulcast");- this.desktopsharing = require("./modules/desktopsharing/desktopsharing");- this.xmpp = require("./modules/xmpp/xmpp");- this.keyboardshortcut = require("./modules/keyboardshortcut/keyboardshortcut");- this.translation = require("./modules/translation/translation");- this.settings = require("./modules/settings/Settings");- this.DTMF = require("./modules/DTMF/DTMF");- this.members = require("./modules/members/MemberList");- }-};--function init() {-- APP.RTC.start();- APP.xmpp.start();- APP.statistics.start();- APP.connectionquality.init();-- // Set default desktop sharing method- APP.desktopsharing.init();-- APP.keyboardshortcut.init();- APP.members.start();-}---$(document).ready(function () {-- APP.init();-- APP.translation.init();-- if(APP.API.isEnabled())- APP.API.init();-- APP.UI.start(init);--});--$(window).bind('beforeunload', function () {- if(APP.API.isEnabled())- APP.API.dispose();-});--module.exports = APP;---},{"./modules/API/API":2,"./modules/DTMF/DTMF":3,"./modules/RTC/RTC":7,"./modules/UI/UI":9,"./modules/connectionquality/connectionquality":36,"./modules/desktopsharing/desktopsharing":37,"./modules/keyboardshortcut/keyboardshortcut":38,"./modules/members/MemberList":39,"./modules/settings/Settings":40,"./modules/simulcast/simulcast":45,"./modules/statistics/statistics":48,"./modules/translation/translation":49,"./modules/xmpp/xmpp":63}],2:[function(require,module,exports){+(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.APP = f()}})(function(){var define,module,exports;return (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){/*** Implements API class that communicates with external api class* and provides interface to access Jitsi Meet features by external@@ -289,7 +230,7 @@ var API = {};module.exports = API;-},{"../../service/xmpp/XMPPEvents":104}],3:[function(require,module,exports){+},{"../../service/xmpp/XMPPEvents":105}],2:[function(require,module,exports){/* global APP *//**@@ -338,7 +279,7 @@ var DTMF = {module.exports = DTMF;-},{}],4:[function(require,module,exports){+},{}],3:[function(require,module,exports){/* global Strophe, focusedVideoSrc*/// cache datachannels to avoid garbage collection@@ -574,7 +515,7 @@ function onPinnedEndpointChanged(userResource)module.exports = DataChannels;-},{"../../service/RTC/RTCEvents":95}],5:[function(require,module,exports){+},{"../../service/RTC/RTCEvents":96}],4:[function(require,module,exports){var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");@@ -682,7 +623,7 @@ LocalStream.prototype.getId = function () {module.exports = LocalStream;-},{"../../service/RTC/StreamEventTypes.js":97}],6:[function(require,module,exports){+},{"../../service/RTC/StreamEventTypes.js":98}],5:[function(require,module,exports){////These lines should be uncommented when require works in app.jsvar MediaStreamType = require("../../service/RTC/MediaStreamTypes");var StreamEventType = require("../../service/RTC/StreamEventTypes");@@ -744,7 +685,7 @@ MediaStream.prototype.setVideoType = function (value) {module.exports = MediaStream;-},{"../../service/RTC/MediaStreamTypes":93,"../../service/RTC/StreamEventTypes":97}],7:[function(require,module,exports){+},{"../../service/RTC/MediaStreamTypes":94,"../../service/RTC/StreamEventTypes":98}],6:[function(require,module,exports){var EventEmitter = require("events");var RTCUtils = require("./RTCUtils.js");var LocalStream = require("./LocalStream.js");@@ -1030,7 +971,7 @@ var RTC = {module.exports = RTC;-},{"../../service/RTC/MediaStreamTypes":93,"../../service/RTC/RTCEvents.js":95,"../../service/RTC/StreamEventTypes.js":97,"../../service/UI/UIEvents":98,"../../service/desktopsharing/DesktopSharingEventTypes":101,"../../service/xmpp/XMPPEvents":104,"./DataChannels":4,"./LocalStream.js":5,"./MediaStream.js":6,"./RTCUtils.js":8,"events":105}],8:[function(require,module,exports){+},{"../../service/RTC/MediaStreamTypes":94,"../../service/RTC/RTCEvents.js":96,"../../service/RTC/StreamEventTypes.js":98,"../../service/UI/UIEvents":99,"../../service/desktopsharing/DesktopSharingEventTypes":102,"../../service/xmpp/XMPPEvents":105,"./DataChannels":3,"./LocalStream.js":4,"./MediaStream.js":5,"./RTCUtils.js":7,"events":65}],7:[function(require,module,exports){var RTCBrowserType = require("../../service/RTC/RTCBrowserType.js");var Resolutions = require("../../service/RTC/Resolutions");@@ -1528,7 +1469,7 @@ RTCUtils.prototype.createStream = function(stream, isVideo)module.exports = RTCUtils;-},{"../../service/RTC/RTCBrowserType.js":94,"../../service/RTC/Resolutions":96}],9:[function(require,module,exports){+},{"../../service/RTC/RTCBrowserType.js":95,"../../service/RTC/Resolutions":97}],8:[function(require,module,exports){var UI = {};var VideoLayout = require("./videolayout/VideoLayout.js");@@ -2347,7 +2288,7 @@ UI.setVideoMute = setVideoMute;module.exports = UI;-},{"../../service/RTC/RTCEvents":95,"../../service/RTC/StreamEventTypes":97,"../../service/connectionquality/CQEvents":100,"../../service/desktopsharing/DesktopSharingEventTypes":101,"../../service/members/Events":102,"../../service/xmpp/XMPPEvents":104,"./../settings/Settings":40,"./audio_levels/AudioLevels.js":10,"./authentication/Authentication":12,"./avatar/Avatar":14,"./etherpad/Etherpad.js":15,"./prezi/Prezi.js":16,"./side_pannels/SidePanelToggler":18,"./side_pannels/chat/Chat.js":19,"./side_pannels/contactlist/ContactList":23,"./side_pannels/settings/SettingsMenu":24,"./toolbars/BottomToolbar":25,"./toolbars/Toolbar":26,"./toolbars/ToolbarToggler":27,"./util/MessageHandler":29,"./util/NicknameHandler":30,"./util/UIUtil":31,"./videolayout/VideoLayout.js":33,"./welcome_page/RoomnameGenerator":34,"./welcome_page/WelcomePage":35,"events":105}],10:[function(require,module,exports){+},{"../../service/RTC/RTCEvents":96,"../../service/RTC/StreamEventTypes":98,"../../service/connectionquality/CQEvents":101,"../../service/desktopsharing/DesktopSharingEventTypes":102,"../../service/members/Events":103,"../../service/xmpp/XMPPEvents":105,"./../settings/Settings":39,"./audio_levels/AudioLevels.js":9,"./authentication/Authentication":11,"./avatar/Avatar":13,"./etherpad/Etherpad.js":14,"./prezi/Prezi.js":15,"./side_pannels/SidePanelToggler":17,"./side_pannels/chat/Chat.js":18,"./side_pannels/contactlist/ContactList":22,"./side_pannels/settings/SettingsMenu":23,"./toolbars/BottomToolbar":24,"./toolbars/Toolbar":25,"./toolbars/ToolbarToggler":26,"./util/MessageHandler":28,"./util/NicknameHandler":29,"./util/UIUtil":30,"./videolayout/VideoLayout.js":32,"./welcome_page/RoomnameGenerator":33,"./welcome_page/WelcomePage":34,"events":65}],9:[function(require,module,exports){var CanvasUtil = require("./CanvasUtils");var ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');@@ -2613,7 +2554,7 @@ var AudioLevels = (function(my) {})(AudioLevels || {});module.exports = AudioLevels;-},{"./CanvasUtils":11}],11:[function(require,module,exports){+},{"./CanvasUtils":10}],10:[function(require,module,exports){/*** Utility class for drawing canvas shapes.*/@@ -2725,7 +2666,7 @@ var CanvasUtil = (function(my) {})(CanvasUtil || {});module.exports = CanvasUtil;-},{}],12:[function(require,module,exports){+},{}],11:[function(require,module,exports){/* global $, APP*/var LoginDialog = require('./LoginDialog');@@ -2850,7 +2791,7 @@ var Authentication = {};module.exports = Authentication;-},{"../../xmpp/moderator":55,"./LoginDialog":13}],13:[function(require,module,exports){+},{"../../xmpp/moderator":54,"./LoginDialog":12}],12:[function(require,module,exports){/* global $, APP, config*/var XMPP = require('../../xmpp/xmpp');@@ -3079,7 +3020,7 @@ var LoginDialog = {};module.exports = LoginDialog;-},{"../../xmpp/moderator":55,"../../xmpp/xmpp":63}],14:[function(require,module,exports){+},{"../../xmpp/moderator":54,"../../xmpp/xmpp":62}],13:[function(require,module,exports){var Settings = require("../../settings/Settings");var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");@@ -3242,7 +3183,7 @@ var Avatar = {module.exports = Avatar;-},{"../../../service/RTC/MediaStreamTypes":93,"../../settings/Settings":40,"../videolayout/VideoLayout":33}],15:[function(require,module,exports){+},{"../../../service/RTC/MediaStreamTypes":94,"../../settings/Settings":39,"../videolayout/VideoLayout":32}],14:[function(require,module,exports){/* global $, config,setLargeVideoVisible, Util */@@ -3438,7 +3379,7 @@ var Etherpad = {module.exports = Etherpad;-},{"../prezi/Prezi":16,"../util/UIUtil":31,"../videolayout/VideoLayout":33}],16:[function(require,module,exports){+},{"../prezi/Prezi":15,"../util/UIUtil":30,"../videolayout/VideoLayout":32}],15:[function(require,module,exports){var ToolbarToggler = require("../toolbars/ToolbarToggler");var UIUtil = require("../util/UIUtil");var VideoLayout = require("../videolayout/VideoLayout");@@ -3814,7 +3755,7 @@ $(window).resize(function () {module.exports = Prezi;-},{"../toolbars/ToolbarToggler":27,"../util/MessageHandler":29,"../util/UIUtil":31,"../videolayout/VideoLayout":33,"./PreziPlayer":17}],17:[function(require,module,exports){+},{"../toolbars/ToolbarToggler":26,"../util/MessageHandler":28,"../util/UIUtil":30,"../videolayout/VideoLayout":32,"./PreziPlayer":16}],16:[function(require,module,exports){(function() {"use strict";var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };@@ -4110,7 +4051,7 @@ module.exports = Prezi;module.exports = PreziPlayer;-},{}],18:[function(require,module,exports){+},{}],17:[function(require,module,exports){var Chat = require("./chat/Chat");var ContactList = require("./contactlist/ContactList");var Settings = require("./../../settings/Settings");@@ -4367,7 +4308,7 @@ var PanelToggler = (function(my) {}(PanelToggler || {}));module.exports = PanelToggler;-},{"../toolbars/ToolbarToggler":27,"../util/UIUtil":31,"../videolayout/VideoLayout":33,"./../../settings/Settings":40,"./chat/Chat":19,"./contactlist/ContactList":23,"./settings/SettingsMenu":24}],19:[function(require,module,exports){+},{"../toolbars/ToolbarToggler":26,"../util/UIUtil":30,"../videolayout/VideoLayout":32,"./../../settings/Settings":39,"./chat/Chat":18,"./contactlist/ContactList":22,"./settings/SettingsMenu":23}],18:[function(require,module,exports){/* global $, Util, nickname:true */var Replacement = require("./Replacement");var CommandsProcessor = require("./Commands");@@ -4725,7 +4666,7 @@ var Chat = (function (my) {return my;}(Chat || {}));module.exports = Chat;-},{"../../../../service/UI/UIEvents":98,"../../toolbars/ToolbarToggler":27,"../../util/NicknameHandler":30,"../../util/UIUtil":31,"../SidePanelToggler":18,"./Commands":20,"./Replacement":21,"./smileys.json":22}],20:[function(require,module,exports){+},{"../../../../service/UI/UIEvents":99,"../../toolbars/ToolbarToggler":26,"../../util/NicknameHandler":29,"../../util/UIUtil":30,"../SidePanelToggler":17,"./Commands":19,"./Replacement":20,"./smileys.json":21}],19:[function(require,module,exports){var UIUtil = require("../../util/UIUtil");/**@@ -4823,7 +4764,7 @@ CommandsProcessor.prototype.processCommand = function()};module.exports = CommandsProcessor;-},{"../../util/UIUtil":31}],21:[function(require,module,exports){+},{"../../util/UIUtil":30}],20:[function(require,module,exports){var Smileys = require("./smileys.json");/*** Processes links and smileys in "body"@@ -4887,7 +4828,7 @@ module.exports = {linkify: linkify};-},{"./smileys.json":22}],22:[function(require,module,exports){+},{"./smileys.json":21}],21:[function(require,module,exports){module.exports={"smileys": {"smiley1": ":)",@@ -4937,7 +4878,7 @@ module.exports={}}-},{}],23:[function(require,module,exports){+},{}],22:[function(require,module,exports){var numberOfContacts = 0;var notificationInterval;@@ -5127,7 +5068,7 @@ var ContactList = {};module.exports = ContactList;-},{}],24:[function(require,module,exports){+},{}],23:[function(require,module,exports){var Avatar = require("../../avatar/Avatar");var Settings = require("./../../../settings/Settings");var UIUtil = require("../../util/UIUtil");@@ -5237,7 +5178,7 @@ var SettingsMenu = {module.exports = SettingsMenu;-},{"../../../../service/translation/languages":103,"../../avatar/Avatar":14,"../../util/UIUtil":31,"./../../../settings/Settings":40}],25:[function(require,module,exports){+},{"../../../../service/translation/languages":104,"../../avatar/Avatar":13,"../../util/UIUtil":30,"./../../../settings/Settings":39}],24:[function(require,module,exports){var PanelToggler = require("../side_pannels/SidePanelToggler");var buttonHandlers = {@@ -5282,7 +5223,7 @@ var BottomToolbar = (function (my) {module.exports = BottomToolbar;-},{"../side_pannels/SidePanelToggler":18}],26:[function(require,module,exports){+},{"../side_pannels/SidePanelToggler":17}],25:[function(require,module,exports){/* global APP,$, buttonClick, config, lockRoom,setSharedKey, Util */var messageHandler = require("../util/MessageHandler");@@ -5931,7 +5872,7 @@ var Toolbar = (function (my) {}(Toolbar || {}));module.exports = Toolbar;-},{"../../../service/authentication/AuthenticationEvents":99,"../authentication/Authentication":12,"../etherpad/Etherpad":15,"../prezi/Prezi":16,"../side_pannels/SidePanelToggler":18,"../util/MessageHandler":29,"../util/UIUtil":31,"./BottomToolbar":25}],27:[function(require,module,exports){+},{"../../../service/authentication/AuthenticationEvents":100,"../authentication/Authentication":11,"../etherpad/Etherpad":14,"../prezi/Prezi":15,"../side_pannels/SidePanelToggler":17,"../util/MessageHandler":28,"../util/UIUtil":30,"./BottomToolbar":24}],26:[function(require,module,exports){/* global $, interfaceConfig, Moderator, DesktopStreaming.showDesktopSharingButton */var toolbarTimeoutObject,@@ -6049,7 +5990,7 @@ var ToolbarToggler = {};module.exports = ToolbarToggler;-},{}],28:[function(require,module,exports){+},{}],27:[function(require,module,exports){var JitsiPopover = (function () {/*** Constructs new JitsiPopover and attaches it to the element@@ -6173,7 +6114,7 @@ var JitsiPopover = (function () {})();module.exports = JitsiPopover;-},{}],29:[function(require,module,exports){+},{}],28:[function(require,module,exports){/* global $, APP, jQuery, toastr */var messageHandler = (function(my) {@@ -6381,7 +6322,7 @@ module.exports = messageHandler;-},{}],30:[function(require,module,exports){+},{}],29:[function(require,module,exports){var UIEvents = require("../../../service/UI/UIEvents");var nickname = null;@@ -6412,7 +6353,7 @@ var NickanameHandler = {};module.exports = NickanameHandler;-},{"../../../service/UI/UIEvents":98}],31:[function(require,module,exports){+},{"../../../service/UI/UIEvents":99}],30:[function(require,module,exports){/*** Created by hristo on 12/22/14.*/@@ -6494,7 +6435,7 @@ module.exports = {};-},{"../side_pannels/SidePanelToggler":18}],32:[function(require,module,exports){+},{"../side_pannels/SidePanelToggler":17}],31:[function(require,module,exports){var JitsiPopover = require("../util/JitsiPopover");/**@@ -6922,7 +6863,7 @@ ConnectionIndicator.prototype.hideIndicator = function () {};module.exports = ConnectionIndicator;-},{"../util/JitsiPopover":28}],33:[function(require,module,exports){+},{"../util/JitsiPopover":27}],32:[function(require,module,exports){var AudioLevels = require("../audio_levels/AudioLevels");var Avatar = require("../avatar/Avatar");var Chat = require("../side_pannels/chat/Chat");@@ -9241,7 +9182,7 @@ var VideoLayout = (function (my) {}(VideoLayout || {}));module.exports = VideoLayout;-},{"../../../service/RTC/MediaStreamTypes":93,"../../../service/UI/UIEvents":98,"../audio_levels/AudioLevels":10,"../avatar/Avatar":14,"../etherpad/Etherpad":15,"../prezi/Prezi":16,"../side_pannels/chat/Chat":19,"../side_pannels/contactlist/ContactList":23,"../util/NicknameHandler":30,"../util/UIUtil":31,"./ConnectionIndicator":32}],34:[function(require,module,exports){+},{"../../../service/RTC/MediaStreamTypes":94,"../../../service/UI/UIEvents":99,"../audio_levels/AudioLevels":9,"../avatar/Avatar":13,"../etherpad/Etherpad":14,"../prezi/Prezi":15,"../side_pannels/chat/Chat":18,"../side_pannels/contactlist/ContactList":22,"../util/NicknameHandler":29,"../util/UIUtil":30,"./ConnectionIndicator":31}],33:[function(require,module,exports){//var nouns = [//];var pluralNouns = [@@ -9422,7 +9363,7 @@ var RoomNameGenerator = {module.exports = RoomNameGenerator;-},{}],35:[function(require,module,exports){+},{}],34:[function(require,module,exports){var animateTimeout, updateTimeout;var RoomNameGenerator = require("./RoomnameGenerator");@@ -9524,7 +9465,7 @@ function setupWelcomePage()}module.exports = setupWelcomePage;-},{"./RoomnameGenerator":34}],36:[function(require,module,exports){+},{"./RoomnameGenerator":33}],35:[function(require,module,exports){var EventEmitter = require("events");var eventEmitter = new EventEmitter();var CQEvents = require("../../service/connectionquality/CQEvents");@@ -9659,7 +9600,7 @@ var ConnectionQuality = {};module.exports = ConnectionQuality;-},{"../../service/connectionquality/CQEvents":100,"../../service/xmpp/XMPPEvents":104,"events":105}],37:[function(require,module,exports){+},{"../../service/connectionquality/CQEvents":101,"../../service/xmpp/XMPPEvents":105,"events":65}],36:[function(require,module,exports){/* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,getUserMediaWithConstraints *//**@@ -10027,7 +9968,7 @@ module.exports = {};-},{"../../service/desktopsharing/DesktopSharingEventTypes":101,"events":105}],38:[function(require,module,exports){+},{"../../service/desktopsharing/DesktopSharingEventTypes":102,"events":65}],37:[function(require,module,exports){//maps keycode to character, id of popover for given function and functionvar shortcuts = {67: {@@ -10120,7 +10061,7 @@ var KeyboardShortcut = {module.exports = KeyboardShortcut;-},{}],39:[function(require,module,exports){+},{}],38:[function(require,module,exports){/* global APP *//**@@ -10245,7 +10186,7 @@ var Members = {module.exports = Members;-},{"../../service/members/Events":102,"../../service/xmpp/XMPPEvents":104,"events":105}],40:[function(require,module,exports){+},{"../../service/members/Events":103,"../../service/xmpp/XMPPEvents":105,"events":65}],39:[function(require,module,exports){var email = '';var displayName = '';var userId;@@ -10312,7 +10253,7 @@ var Settings =module.exports = Settings;-},{}],41:[function(require,module,exports){+},{}],40:[function(require,module,exports){/**** @constructor@@ -10345,7 +10286,7 @@ SimulcastLogger.prototype.error = function (text) {};module.exports = SimulcastLogger;-},{}],42:[function(require,module,exports){+},{}],41:[function(require,module,exports){var SimulcastLogger = require("./SimulcastLogger");var SimulcastUtils = require("./SimulcastUtils");var MediaStreamType = require("../../service/RTC/MediaStreamTypes");@@ -10614,7 +10555,7 @@ SimulcastReceiver.prototype.transformRemoteDescription = function (desc) {};module.exports = SimulcastReceiver;-},{"../../service/RTC/MediaStreamTypes":93,"./SimulcastLogger":41,"./SimulcastUtils":44}],43:[function(require,module,exports){+},{"../../service/RTC/MediaStreamTypes":94,"./SimulcastLogger":40,"./SimulcastUtils":43}],42:[function(require,module,exports){var SimulcastLogger = require("./SimulcastLogger");var SimulcastUtils = require("./SimulcastUtils");@@ -11137,7 +11078,7 @@ module.exports = {"no": NoSimulcastSender}-},{"./SimulcastLogger":41,"./SimulcastUtils":44}],44:[function(require,module,exports){+},{"./SimulcastLogger":40,"./SimulcastUtils":43}],43:[function(require,module,exports){var SimulcastLogger = require("./SimulcastLogger");/**@@ -11371,7 +11312,7 @@ SimulcastUtils.prototype._compileVideoSources = function (videoSources) {};module.exports = SimulcastUtils;-},{"./SimulcastLogger":41}],45:[function(require,module,exports){+},{"./SimulcastLogger":40}],44:[function(require,module,exports){/*jslint plusplus: true *//*jslint nomen: true*/@@ -11574,7 +11515,7 @@ SimulcastManager.prototype.resetSender = function() {var simulcast = new SimulcastManager();module.exports = simulcast;-},{"../../service/RTC/RTCEvents":95,"./SimulcastReceiver":42,"./SimulcastSender":43,"./SimulcastUtils":44}],46:[function(require,module,exports){+},{"../../service/RTC/RTCEvents":96,"./SimulcastReceiver":41,"./SimulcastSender":42,"./SimulcastUtils":43}],45:[function(require,module,exports){/*** Provides statistics for the local stream.*/@@ -11705,7 +11646,7 @@ LocalStatsCollector.prototype.stop = function () {};module.exports = LocalStatsCollector;-},{}],47:[function(require,module,exports){+},{}],46:[function(require,module,exports){/* global ssrc2jid *//* jshint -W117 */var RTCBrowserType = require("../../service/RTC/RTCBrowserType");@@ -12446,7 +12387,7 @@ StatsCollector.prototype.processAudioLevelReport = function ()};-},{"../../service/RTC/RTCBrowserType":94}],48:[function(require,module,exports){+},{"../../service/RTC/RTCBrowserType":95}],47:[function(require,module,exports){/*** Created by hristo on 8/4/14.*/@@ -12579,7 +12520,7 @@ var statistics =module.exports = statistics;-},{"../../service/RTC/StreamEventTypes.js":97,"../../service/xmpp/XMPPEvents":104,"./LocalStatsCollector.js":46,"./RTPStatsCollector.js":47,"events":105}],49:[function(require,module,exports){+},{"../../service/RTC/StreamEventTypes.js":98,"../../service/xmpp/XMPPEvents":105,"./LocalStatsCollector.js":45,"./RTPStatsCollector.js":46,"events":65}],48:[function(require,module,exports){var i18n = require("i18next-client");var languages = require("../../service/translation/languages");var Settings = require("../settings/Settings");@@ -12713,7 +12654,7 @@ module.exports = {}};-},{"../../service/translation/languages":103,"../settings/Settings":40,"i18next-client":65}],50:[function(require,module,exports){+},{"../../service/translation/languages":104,"../settings/Settings":39,"i18next-client":66}],49:[function(require,module,exports){/* jshint -W117 */var TraceablePeerConnection = require("./TraceablePeerConnection");var SDPDiffer = require("./SDPDiffer");@@ -14098,7 +14039,7 @@ JingleSession.prototype.remoteStreamAdded = function (data, times) {module.exports = JingleSession;-},{"../../service/RTC/RTCBrowserType":94,"./SDP":51,"./SDPDiffer":52,"./SDPUtil":53,"./TraceablePeerConnection":54,"async":64}],51:[function(require,module,exports){+},{"../../service/RTC/RTCBrowserType":95,"./SDP":50,"./SDPDiffer":51,"./SDPUtil":52,"./TraceablePeerConnection":53,"async":63}],50:[function(require,module,exports){/* jshint -W117 */var SDPUtil = require("./SDPUtil");@@ -14720,7 +14661,7 @@ SDP.prototype.jingle2media = function (content) {module.exports = SDP;-},{"./SDPUtil":53}],52:[function(require,module,exports){+},{"./SDPUtil":52}],51:[function(require,module,exports){function SDPDiffer(mySDP, otherSDP) {this.mySDP = mySDP;this.otherSDP = otherSDP;@@ -14886,7 +14827,7 @@ SDPDiffer.prototype.toJingle = function(modify) {};module.exports = SDPDiffer;-},{}],53:[function(require,module,exports){+},{}],52:[function(require,module,exports){SDPUtil = {iceparams: function (mediadesc, sessiondesc) {var data = null;@@ -15236,7 +15177,7 @@ SDPUtil = {}};module.exports = SDPUtil;-},{}],54:[function(require,module,exports){+},{}],53:[function(require,module,exports){function TraceablePeerConnection(ice_config, constraints) {var self = this;var RTCPeerconnection = navigator.mozGetUserMedia ? mozRTCPeerConnection : webkitRTCPeerConnection;@@ -15556,7 +15497,7 @@ TraceablePeerConnection.prototype.getStats = function(callback, errback) {module.exports = TraceablePeerConnection;-},{"sdp-interop":86}],55:[function(require,module,exports){+},{"sdp-interop":87}],54:[function(require,module,exports){/* global $, $iq, APP, config, connection, UI, messageHandler,roomName, sessionTerminated, Strophe, Util */var XMPPEvents = require("../../service/xmpp/XMPPEvents");@@ -15988,7 +15929,7 @@ module.exports = Moderator;-},{"../../service/authentication/AuthenticationEvents":99,"../../service/xmpp/XMPPEvents":104,"../settings/Settings":40}],56:[function(require,module,exports){+},{"../../service/authentication/AuthenticationEvents":100,"../../service/xmpp/XMPPEvents":105,"../settings/Settings":39}],55:[function(require,module,exports){/* global $, $iq, config, connection, focusMucJid, messageHandler, Moderator,Toolbar, Util */var Moderator = require("./moderator");@@ -16144,7 +16085,7 @@ var Recording = {}module.exports = Recording;-},{"./moderator":55}],57:[function(require,module,exports){+},{"./moderator":54}],56:[function(require,module,exports){/* jshint -W117 *//* a simple MUC connection plugin* can only handle a single MUC room@@ -16828,7 +16769,7 @@ module.exports = function(XMPP, eventEmitter) {};-},{"../../service/xmpp/XMPPEvents":104,"./JingleSession":50,"./moderator":55}],58:[function(require,module,exports){+},{"../../service/xmpp/XMPPEvents":105,"./JingleSession":49,"./moderator":54}],57:[function(require,module,exports){/* jshint -W117 */var JingleSession = require("./JingleSession");@@ -17175,7 +17116,7 @@ module.exports = function(XMPP, eventEmitter)};-},{"../../service/xmpp/XMPPEvents":104,"./JingleSession":50}],59:[function(require,module,exports){+},{"../../service/xmpp/XMPPEvents":105,"./JingleSession":49}],58:[function(require,module,exports){/* global Strophe */module.exports = function () {@@ -17196,7 +17137,7 @@ module.exports = function () {}});};-},{}],60:[function(require,module,exports){+},{}],59:[function(require,module,exports){/* global $, $iq, config, connection, focusMucJid, forceMuted,setAudioMuted, Strophe *//**@@ -17255,7 +17196,7 @@ module.exports = function (XMPP) {}});}-},{}],61:[function(require,module,exports){+},{}],60:[function(require,module,exports){/* jshint -W117 */module.exports = function() {Strophe.addConnectionPlugin('rayo',@@ -17352,7 +17293,7 @@ module.exports = function() {);};-},{}],62:[function(require,module,exports){+},{}],61:[function(require,module,exports){/*** Strophe logger implementation. Logs from level WARN and above.*/@@ -17396,7 +17337,7 @@ module.exports = function () {};};-},{}],63:[function(require,module,exports){+},{}],62:[function(require,module,exports){/* global $, APP, config, Strophe*/var Moderator = require("./moderator");var EventEmitter = require("events");@@ -18012,7 +17953,7 @@ var XMPP = {module.exports = XMPP;-},{"../../service/RTC/RTCEvents":95,"../../service/RTC/StreamEventTypes":97,"../../service/UI/UIEvents":98,"../../service/xmpp/XMPPEvents":104,"../settings/Settings":40,"./SDP":51,"./moderator":55,"./recording":56,"./strophe.emuc":57,"./strophe.jingle":58,"./strophe.logger":59,"./strophe.moderate":60,"./strophe.rayo":61,"./strophe.util":62,"events":105,"pako":66,"retry":82}],64:[function(require,module,exports){+},{"../../service/RTC/RTCEvents":96,"../../service/RTC/StreamEventTypes":98,"../../service/UI/UIEvents":99,"../../service/xmpp/XMPPEvents":105,"../settings/Settings":39,"./SDP":50,"./moderator":54,"./recording":55,"./strophe.emuc":56,"./strophe.jingle":57,"./strophe.logger":58,"./strophe.moderate":59,"./strophe.rayo":60,"./strophe.util":61,"events":65,"pako":67,"retry":83}],63:[function(require,module,exports){(function (process){/*!* async@@ -19139,10337 +19080,10492 @@ module.exports = XMPP;}());}).call(this,require('_process'))-},{"_process":106}],65:[function(require,module,exports){-// i18next, v1.7.7-// Copyright (c)2014 Jan Mühlemann (jamuhl).-// Distributed under MIT license-// http://i18next.com-(function() {+},{"_process":64}],64:[function(require,module,exports){+// shim for using process in browser- // add indexOf to non ECMA-262 standard compliant browsers- if (!Array.prototype.indexOf) {- Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {- "use strict";- if (this == null) {- throw new TypeError();- }- var t = Object(this);- var len = t.length >>> 0;- if (len === 0) {- return -1;- }- var n = 0;- if (arguments.length > 0) {- n = Number(arguments[1]);- if (n != n) { // shortcut for verifying if it's NaN- n = 0;- } else if (n != 0 && n != Infinity && n != -Infinity) {- n = (n > 0 || -1) * Math.floor(Math.abs(n));- }- }- if (n >= len) {- return -1;- }- var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);- for (; k < len; k++) {- if (k in t && t[k] === searchElement) {- return k;- }- }- return -1;- }+var process = module.exports = {};+var queue = [];+var draining = false;+var currentQueue;+var queueIndex = -1;++function cleanUpNextTick() {+ draining = false;+ if (currentQueue.length) {+ queue = currentQueue.concat(queue);+ } else {+ queueIndex = -1;}-- // add lastIndexOf to non ECMA-262 standard compliant browsers- if (!Array.prototype.lastIndexOf) {- Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {- "use strict";- if (this == null) {- throw new TypeError();- }- var t = Object(this);- var len = t.length >>> 0;- if (len === 0) {- return -1;- }- var n = len;- if (arguments.length > 1) {- n = Number(arguments[1]);- if (n != n) {- n = 0;- } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {- n = (n > 0 || -1) * Math.floor(Math.abs(n));- }- }- var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);- for (; k >= 0; k--) {- if (k in t && t[k] === searchElement) {- return k;- }- }- return -1;- };+ if (queue.length) {+ drainQueue();}-- // Add string trim for IE8.- if (typeof String.prototype.trim !== 'function') {- String.prototype.trim = function() {- return this.replace(/^\s+|\s+$/g, '');+}++function drainQueue() {+ if (draining) {+ return;+ }+ var timeout = setTimeout(cleanUpNextTick);+ draining = true;++ var len = queue.length;+ while(len) {+ currentQueue = queue;+ queue = [];+ while (++queueIndex < len) {+ currentQueue[queueIndex].run();}+ queueIndex = -1;+ len = queue.length;}+ currentQueue = null;+ draining = false;+ clearTimeout(timeout);+}- var root = this- , $ = root.jQuery || root.Zepto- , i18n = {}- , resStore = {}- , currentLng- , replacementCounter = 0- , languages = []- , initialized = false- , sync = {};+process.nextTick = function (fun) {+ var args = new Array(arguments.length - 1);+ if (arguments.length > 1) {+ for (var i = 1; i < arguments.length; i++) {+ args[i - 1] = arguments[i];+ }+ }+ queue.push(new Item(fun, args));+ if (!draining) {+ setTimeout(drainQueue, 0);+ }+};+// v8 likes predictible objects+function Item(fun, array) {+ this.fun = fun;+ this.array = array;+}+Item.prototype.run = function () {+ this.fun.apply(null, this.array);+};+process.title = 'browser';+process.browser = true;+process.env = {};+process.argv = [];+process.version = ''; // empty string to avoid regexp issues+process.versions = {};+function noop() {}- // Export the i18next object for **CommonJS**.- // If we're not in CommonJS, add `i18n` to the- // global object or to jquery.- if (typeof module !== 'undefined' && module.exports) {- if (!$) {- try {- $ = require('jquery');- } catch(e) {- // just ignore- }- }- if ($) {- $.i18n = $.i18n || i18n;- }- module.exports = i18n;- } else {- if ($) {- $.i18n = $.i18n || i18n;- }-- root.i18n = root.i18n || i18n;- }- sync = {-- load: function(lngs, options, cb) {- if (options.useLocalStorage) {- sync._loadLocal(lngs, options, function(err, store) {- var missingLngs = [];- for (var i = 0, len = lngs.length; i < len; i++) {- if (!store[lngs[i]]) missingLngs.push(lngs[i]);- }-- if (missingLngs.length > 0) {- sync._fetch(missingLngs, options, function(err, fetched) {- f.extend(store, fetched);- sync._storeLocal(fetched);-- cb(null, store);- });- } else {- cb(null, store);- }- });- } else {- sync._fetch(lngs, options, function(err, store){- cb(null, store);- });- }- },-- _loadLocal: function(lngs, options, cb) {- var store = {}- , nowMS = new Date().getTime();-- if(window.localStorage) {-- var todo = lngs.length;-- f.each(lngs, function(key, lng) {- var local = window.localStorage.getItem('res_' + lng);-- if (local) {- local = JSON.parse(local);-- if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {- store[lng] = local;- }- }-- todo--; // wait for all done befor callback- if (todo === 0) cb(null, store);- });- }- },-- _storeLocal: function(store) {- if(window.localStorage) {- for (var m in store) {- store[m].i18nStamp = new Date().getTime();- f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));- }- }- return;- },-- _fetch: function(lngs, options, cb) {- var ns = options.ns- , store = {};-- if (!options.dynamicLoad) {- var todo = ns.namespaces.length * lngs.length- , errors;-- // load each file individual- f.each(ns.namespaces, function(nsIndex, nsValue) {- f.each(lngs, function(lngIndex, lngValue) {-- // Call this once our translation has returned.- var loadComplete = function(err, data) {- if (err) {- errors = errors || [];- errors.push(err);- }- store[lngValue] = store[lngValue] || {};- store[lngValue][nsValue] = data;-- todo--; // wait for all done befor callback- if (todo === 0) cb(errors, store);- };-- if(typeof options.customLoad == 'function'){- // Use the specified custom callback.- options.customLoad(lngValue, nsValue, options, loadComplete);- } else {- //~ // Use our inbuilt sync.- sync._fetchOne(lngValue, nsValue, options, loadComplete);- }- });- });- } else {- // Call this once our translation has returned.- var loadComplete = function(err, data) {- cb(null, data);- };-- if(typeof options.customLoad == 'function'){- // Use the specified custom callback.- options.customLoad(lngs, ns.namespaces, options, loadComplete);- } else {- var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });- // load all needed stuff once- f.ajax({- url: url,- success: function(data, status, xhr) {- f.log('loaded: ' + url);- loadComplete(null, data);- },- error : function(xhr, status, error) {- f.log('failed loading: ' + url);- loadComplete('failed loading resource.json error: ' + error);- },- dataType: "json",- async : options.getAsync- });- }- }- },-- _fetchOne: function(lng, ns, options, done) {- var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });- f.ajax({- url: url,- success: function(data, status, xhr) {- f.log('loaded: ' + url);- done(null, data);- },- error : function(xhr, status, error) {- if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {- // file loaded but invalid json, stop waste time !- f.error('There is a typo in: ' + url);- } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {- f.log('Does not exist: ' + url);- } else {- var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);- f.log(theStatus + ' when loading ' + url);- }-- done(error, {});- },- dataType: "json",- async : options.getAsync- });- },-- postMissing: function(lng, ns, key, defaultValue, lngs) {- var payload = {};- payload[key] = defaultValue;-- var urls = [];-- if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {- for (var i = 0; i < o.fallbackLng.length; i++) {- urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});- }- } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {- urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});- } else if (o.sendMissingTo === 'all') {- for (var i = 0, l = lngs.length; i < l; i++) {- urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});- }- }-- for (var y = 0, len = urls.length; y < len; y++) {- var item = urls[y];- f.ajax({- url: item.url,- type: o.sendType,- data: payload,- success: function(data, status, xhr) {- f.log('posted missing key \'' + key + '\' to: ' + item.url);-- // add key to resStore- var keys = key.split('.');- var x = 0;- var value = resStore[item.lng][ns];- while (keys[x]) {- if (x === keys.length - 1) {- value = value[keys[x]] = defaultValue;- } else {- value = value[keys[x]] = value[keys[x]] || {};- }- x++;- }- },- error : function(xhr, status, error) {- f.log('failed posting missing key \'' + key + '\' to: ' + item.url);- },- dataType: "json",- async : o.postAsync- });- }- },-- reload: reload- };- // defaults- var o = {- lng: undefined,- load: 'all',- preload: [],- lowerCaseLng: false,- returnObjectTrees: false,- fallbackLng: ['dev'],- fallbackNS: [],- detectLngQS: 'setLng',- detectLngFromLocalStorage: false,- ns: 'translation',- fallbackOnNull: true,- fallbackOnEmpty: false,- fallbackToDefaultNS: false,- nsseparator: ':',- keyseparator: '.',- selectorAttr: 'data-i18n',- debug: false,-- resGetPath: 'locales/__lng__/__ns__.json',- resPostPath: 'locales/add/__lng__/__ns__',-- getAsync: true,- postAsync: true,-- resStore: undefined,- useLocalStorage: false,- localStorageExpirationTime: 7*24*60*60*1000,-- dynamicLoad: false,- sendMissing: false,- sendMissingTo: 'fallback', // current | all- sendType: 'POST',-- interpolationPrefix: '__',- interpolationSuffix: '__',- defaultVariables: false,- reusePrefix: '$t(',- reuseSuffix: ')',- pluralSuffix: '_plural',- pluralNotFound: ['plural_not_found', Math.random()].join(''),- contextNotFound: ['context_not_found', Math.random()].join(''),- escapeInterpolation: false,- indefiniteSuffix: '_indefinite',- indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),-- setJqueryExt: true,- defaultValueFromContent: true,- useDataAttrOptions: false,- cookieExpirationTime: undefined,- useCookie: true,- cookieName: 'i18next',- cookieDomain: undefined,-- objectTreeKeyHandler: undefined,- postProcess: undefined,- parseMissingKey: undefined,- missingKeyHandler: sync.postMissing,-- shortcutFunction: 'sprintf' // or: defaultValue- };- function _extend(target, source) {- if (!source || typeof source === 'function') {- return target;- }-- for (var attr in source) { target[attr] = source[attr]; }- return target;- }-- function _deepExtend(target, source) {- for (var prop in source)- if (prop in target)- _deepExtend(target[prop], source[prop]);- else- target[prop] = source[prop];- return target;- }-- function _each(object, callback, args) {- var name, i = 0,- length = object.length,- isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";-- if (args) {- if (isObj) {- for (name in object) {- if (callback.apply(object[name], args) === false) {- break;- }- }- } else {- for ( ; i < length; ) {- if (callback.apply(object[i++], args) === false) {- break;- }- }- }-- // A special, fast, case for the most common use of each- } else {- if (isObj) {- for (name in object) {- if (callback.call(object[name], name, object[name]) === false) {- break;- }- }- } else {- for ( ; i < length; ) {- if (callback.call(object[i], i, object[i++]) === false) {- break;- }- }- }- }-- return object;- }-- var _entityMap = {- "&": "&",- "<": "<",- ">": ">",- '"': '"',- "'": ''',- "/": '/'- };-- function _escape(data) {- if (typeof data === 'string') {- return data.replace(/[&<>"'\/]/g, function (s) {- return _entityMap[s];- });- }else{- return data;- }- }-- function _ajax(options) {-- // v0.5.0 of https://github.com/goloroden/http.js- var getXhr = function (callback) {- // Use the native XHR object if the browser supports it.- if (window.XMLHttpRequest) {- return callback(null, new XMLHttpRequest());- } else if (window.ActiveXObject) {- // In Internet Explorer check for ActiveX versions of the XHR object.- try {- return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));- } catch (e) {- return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));- }- }-- // If no XHR support was found, throw an error.- return callback(new Error());- };-- var encodeUsingUrlEncoding = function (data) {- if(typeof data === 'string') {- return data;- }-- var result = [];- for(var dataItem in data) {- if(data.hasOwnProperty(dataItem)) {- result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));- }- }-- return result.join('&');- };-- var utf8 = function (text) {- text = text.replace(/\r\n/g, '\n');- var result = '';-- for(var i = 0; i < text.length; i++) {- var c = text.charCodeAt(i);-- if(c < 128) {- result += String.fromCharCode(c);- } else if((c > 127) && (c < 2048)) {- result += String.fromCharCode((c >> 6) | 192);- result += String.fromCharCode((c & 63) | 128);- } else {- result += String.fromCharCode((c >> 12) | 224);- result += String.fromCharCode(((c >> 6) & 63) | 128);- result += String.fromCharCode((c & 63) | 128);- }- }-- return result;- };-- var base64 = function (text) {- var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';-- text = utf8(text);- var result = '',- chr1, chr2, chr3,- enc1, enc2, enc3, enc4,- i = 0;-- do {- chr1 = text.charCodeAt(i++);- chr2 = text.charCodeAt(i++);- chr3 = text.charCodeAt(i++);-- enc1 = chr1 >> 2;- enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);- enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);- enc4 = chr3 & 63;-- if(isNaN(chr2)) {- enc3 = enc4 = 64;- } else if(isNaN(chr3)) {- enc4 = 64;- }-- result +=- keyStr.charAt(enc1) +- keyStr.charAt(enc2) +- keyStr.charAt(enc3) +- keyStr.charAt(enc4);- chr1 = chr2 = chr3 = '';- enc1 = enc2 = enc3 = enc4 = '';- } while(i < text.length);-- return result;- };-- var mergeHeaders = function () {- // Use the first header object as base.- var result = arguments[0];-- // Iterate through the remaining header objects and add them.- for(var i = 1; i < arguments.length; i++) {- var currentHeaders = arguments[i];- for(var header in currentHeaders) {- if(currentHeaders.hasOwnProperty(header)) {- result[header] = currentHeaders[header];- }- }- }-- // Return the merged headers.- return result;- };-- var ajax = function (method, url, options, callback) {- // Adjust parameters.- if(typeof options === 'function') {- callback = options;- options = {};- }-- // Set default parameter values.- options.cache = options.cache || false;- options.data = options.data || {};- options.headers = options.headers || {};- options.jsonp = options.jsonp || false;- options.async = options.async === undefined ? true : options.async;-- // Merge the various header objects.- var headers = mergeHeaders({- 'accept': '*/*',- 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'- }, ajax.headers, options.headers);-- // Encode the data according to the content-type.- var payload;- if (headers['content-type'] === 'application/json') {- payload = JSON.stringify(options.data);- } else {- payload = encodeUsingUrlEncoding(options.data);- }-- // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call- // if neccessary.- if(method === 'GET') {- // Setup the query string.- var queryString = [];- if(payload) {- queryString.push(payload);- payload = null;- }-- // Handle caching.- if(!options.cache) {- queryString.push('_=' + (new Date()).getTime());- }-- // If neccessary prepare the query string for a JSONP call.- if(options.jsonp) {- queryString.push('callback=' + options.jsonp);- queryString.push('jsonp=' + options.jsonp);- }-- // Merge the query string and attach it to the url.- queryString = queryString.join('&');- if (queryString.length > 1) {- if (url.indexOf('?') > -1) {- url += '&' + queryString;- } else {- url += '?' + queryString;- }- }-- // Make a JSONP call if neccessary.- if(options.jsonp) {- var head = document.getElementsByTagName('head')[0];- var script = document.createElement('script');- script.type = 'text/javascript';- script.src = url;- head.appendChild(script);- return;- }- }-- // Since we got here, it is no JSONP request, so make a normal XHR request.- getXhr(function (err, xhr) {- if(err) return callback(err);-- // Open the request.- xhr.open(method, url, options.async);-- // Set the request headers.- for(var header in headers) {- if(headers.hasOwnProperty(header)) {- xhr.setRequestHeader(header, headers[header]);- }- }-- // Handle the request events.- xhr.onreadystatechange = function () {- if(xhr.readyState === 4) {- var data = xhr.responseText || '';-- // If no callback is given, return.- if(!callback) {- return;- }-- // Return an object that provides access to the data as text and JSON.- callback(xhr.status, {- text: function () {- return data;- },-- json: function () {- try {- return JSON.parse(data)- } catch (e) {- f.error('Can not parse JSON. URL: ' + url);- return {};- }- }- });- }- };-- // Actually send the XHR request.- xhr.send(payload);- });- };-- // Define the external interface.- var http = {- authBasic: function (username, password) {- ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);- },-- connect: function (url, options, callback) {- return ajax('CONNECT', url, options, callback);- },-- del: function (url, options, callback) {- return ajax('DELETE', url, options, callback);- },-- get: function (url, options, callback) {- return ajax('GET', url, options, callback);- },-- head: function (url, options, callback) {- return ajax('HEAD', url, options, callback);- },-- headers: function (headers) {- ajax.headers = headers || {};- },-- isAllowed: function (url, verb, callback) {- this.options(url, function (status, data) {- callback(data.text().indexOf(verb) !== -1);- });- },-- options: function (url, options, callback) {- return ajax('OPTIONS', url, options, callback);- },-- patch: function (url, options, callback) {- return ajax('PATCH', url, options, callback);- },-- post: function (url, options, callback) {- return ajax('POST', url, options, callback);- },-- put: function (url, options, callback) {- return ajax('PUT', url, options, callback);- },-- trace: function (url, options, callback) {- return ajax('TRACE', url, options, callback);- }- };--- var methode = options.type ? options.type.toLowerCase() : 'get';-- http[methode](options.url, options, function (status, data) {- // file: protocol always gives status code 0, so check for data- if (status === 200 || (status === 0 && data.text())) {- options.success(data.json(), status, null);- } else {- options.error(data.text(), status, null);- }- });- }-- var _cookie = {- create: function(name,value,minutes,domain) {- var expires;- if (minutes) {- var date = new Date();- date.setTime(date.getTime()+(minutes*60*1000));- expires = "; expires="+date.toGMTString();- }- else expires = "";- domain = (domain)? "domain="+domain+";" : "";- document.cookie = name+"="+value+expires+";"+domain+"path=/";- },-- read: function(name) {- var nameEQ = name + "=";- var ca = document.cookie.split(';');- for(var i=0;i < ca.length;i++) {- var c = ca[i];- while (c.charAt(0)==' ') c = c.substring(1,c.length);- if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);- }- return null;- },-- remove: function(name) {- this.create(name,"",-1);- }- };-- var cookie_noop = {- create: function(name,value,minutes,domain) {},- read: function(name) { return null; },- remove: function(name) {}- };---- // move dependent functions to a container so that- // they can be overriden easier in no jquery environment (node.js)- var f = {- extend: $ ? $.extend : _extend,- deepExtend: _deepExtend,- each: $ ? $.each : _each,- ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),- cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,- detectLanguage: detectLanguage,- escape: _escape,- log: function(str) {- if (o.debug && typeof console !== "undefined") console.log(str);- },- error: function(str) {- if (typeof console !== "undefined") console.error(str);- },- getCountyIndexOfLng: function(lng) {- var lng_index = 0;- if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;- return lng_index;- },- toLanguages: function(lng) {- var log = this.log;-- function applyCase(l) {- var ret = l;-- if (typeof l === 'string' && l.indexOf('-') > -1) {- var parts = l.split('-');-- ret = o.lowerCaseLng ?- parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :- parts[0].toLowerCase() + '-' + parts[1].toUpperCase();- } else {- ret = o.lowerCaseLng ? l.toLowerCase() : l;- }-- return ret;- }-- var languages = [];- var whitelist = o.lngWhitelist || false;- var addLanguage = function(language){- //reject langs not whitelisted- if(!whitelist || whitelist.indexOf(language) > -1){- languages.push(language);- }else{- log('rejecting non-whitelisted language: ' + language);- }- };- if (typeof lng === 'string' && lng.indexOf('-') > -1) {- var parts = lng.split('-');-- if (o.load !== 'unspecific') addLanguage(applyCase(lng));- if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));- } else {- addLanguage(applyCase(lng));- }-- for (var i = 0; i < o.fallbackLng.length; i++) {- if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));- }- return languages;- },- regexEscape: function(str) {- return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");- },- regexReplacementEscape: function(strOrFn) {- if (typeof strOrFn === 'string') {- return strOrFn.replace(/\$/g, "$$$$");- } else {- return strOrFn;- }- },- localStorage: {- setItem: function(key, value) {- if (window.localStorage) {- try {- window.localStorage.setItem(key, value);- } catch (e) {- f.log('failed to set value for key "' + key + '" to localStorage.');- }- }- }- }- };- function init(options, cb) {-- if (typeof options === 'function') {- cb = options;- options = {};- }- options = options || {};-- // override defaults with passed in options- f.extend(o, options);- delete o.fixLng; /* passed in each time */-- // override functions: .log(), .detectLanguage(), etc- if (o.functions) {- delete o.functions;- f.extend(f, options.functions);- }-- // create namespace object if namespace is passed in as string- if (typeof o.ns == 'string') {- o.ns = { namespaces: [o.ns], defaultNs: o.ns};- }-- // fallback namespaces- if (typeof o.fallbackNS == 'string') {- o.fallbackNS = [o.fallbackNS];- }-- // fallback languages- if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {- o.fallbackLng = [o.fallbackLng];- }-- // escape prefix/suffix- o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);- o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);-- if (!o.lng) o.lng = f.detectLanguage();-- languages = f.toLanguages(o.lng);- currentLng = languages[0];- f.log('currentLng set to: ' + currentLng);-- if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid- f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);- }- if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {- f.localStorage.setItem('i18next_lng', currentLng);- }-- var lngTranslate = translate;- if (options.fixLng) {- lngTranslate = function(key, options) {- options = options || {};- options.lng = options.lng || lngTranslate.lng;- return translate(key, options);- };- lngTranslate.lng = currentLng;- }-- pluralExtensions.setCurrentLng(currentLng);-- // add JQuery extensions- if ($ && o.setJqueryExt) addJqueryFunct();-- // jQuery deferred- var deferred;- if ($ && $.Deferred) {- deferred = $.Deferred();- }-- // return immidiatly if res are passed in- if (o.resStore) {- resStore = o.resStore;- initialized = true;- if (cb) cb(lngTranslate);- if (deferred) deferred.resolve(lngTranslate);- if (deferred) return deferred.promise();- return;- }-- // languages to load- var lngsToLoad = f.toLanguages(o.lng);- if (typeof o.preload === 'string') o.preload = [o.preload];- for (var i = 0, l = o.preload.length; i < l; i++) {- var pres = f.toLanguages(o.preload[i]);- for (var y = 0, len = pres.length; y < len; y++) {- if (lngsToLoad.indexOf(pres[y]) < 0) {- lngsToLoad.push(pres[y]);- }- }- }-- // else load them- i18n.sync.load(lngsToLoad, o, function(err, store) {- resStore = store;- initialized = true;-- if (cb) cb(lngTranslate);- if (deferred) deferred.resolve(lngTranslate);- });-- if (deferred) return deferred.promise();- }- function preload(lngs, cb) {- if (typeof lngs === 'string') lngs = [lngs];- for (var i = 0, l = lngs.length; i < l; i++) {- if (o.preload.indexOf(lngs[i]) < 0) {- o.preload.push(lngs[i]);- }- }- return init(cb);- }-- function addResourceBundle(lng, ns, resources, deep) {- if (typeof ns !== 'string') {- resources = ns;- ns = o.ns.defaultNs;- } else if (o.ns.namespaces.indexOf(ns) < 0) {- o.ns.namespaces.push(ns);- }-- resStore[lng] = resStore[lng] || {};- resStore[lng][ns] = resStore[lng][ns] || {};-- if (deep) {- f.deepExtend(resStore[lng][ns], resources);- } else {- f.extend(resStore[lng][ns], resources);- }- }-- function hasResourceBundle(lng, ns) {- if (typeof ns !== 'string') {- ns = o.ns.defaultNs;- }-- resStore[lng] = resStore[lng] || {};- var res = resStore[lng][ns] || {};-- var hasValues = false;- for(var prop in res) {- if (res.hasOwnProperty(prop)) {- hasValues = true;- }- }-- return hasValues;- }-- function removeResourceBundle(lng, ns) {- if (typeof ns !== 'string') {- ns = o.ns.defaultNs;- }-- resStore[lng] = resStore[lng] || {};- resStore[lng][ns] = {};- }-- function addResource(lng, ns, key, value) {- if (typeof ns !== 'string') {- resource = ns;- ns = o.ns.defaultNs;- } else if (o.ns.namespaces.indexOf(ns) < 0) {- o.ns.namespaces.push(ns);- }-- resStore[lng] = resStore[lng] || {};- resStore[lng][ns] = resStore[lng][ns] || {};-- var keys = key.split(o.keyseparator);- var x = 0;- var node = resStore[lng][ns];- var origRef = node;-- while (keys[x]) {- if (x == keys.length - 1)- node[keys[x]] = value;- else {- if (node[keys[x]] == null)- node[keys[x]] = {};-- node = node[keys[x]];- }- x++;- }- }-- function addResources(lng, ns, resources) {- if (typeof ns !== 'string') {- resource = ns;- ns = o.ns.defaultNs;- } else if (o.ns.namespaces.indexOf(ns) < 0) {- o.ns.namespaces.push(ns);- }-- for (var m in resources) {- if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);- }- }-- function setDefaultNamespace(ns) {- o.ns.defaultNs = ns;- }-- function loadNamespace(namespace, cb) {- loadNamespaces([namespace], cb);- }-- function loadNamespaces(namespaces, cb) {- var opts = {- dynamicLoad: o.dynamicLoad,- resGetPath: o.resGetPath,- getAsync: o.getAsync,- customLoad: o.customLoad,- ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */- };-- // languages to load- var lngsToLoad = f.toLanguages(o.lng);- if (typeof o.preload === 'string') o.preload = [o.preload];- for (var i = 0, l = o.preload.length; i < l; i++) {- var pres = f.toLanguages(o.preload[i]);- for (var y = 0, len = pres.length; y < len; y++) {- if (lngsToLoad.indexOf(pres[y]) < 0) {- lngsToLoad.push(pres[y]);- }- }- }-- // check if we have to load- var lngNeedLoad = [];- for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {- var needLoad = false;- var resSet = resStore[lngsToLoad[a]];- if (resSet) {- for (var b = 0, lenB = namespaces.length; b < lenB; b++) {- if (!resSet[namespaces[b]]) needLoad = true;- }- } else {- needLoad = true;- }-- if (needLoad) lngNeedLoad.push(lngsToLoad[a]);- }-- if (lngNeedLoad.length) {- i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {- var todo = namespaces.length * lngNeedLoad.length;-- // load each file individual- f.each(namespaces, function(nsIndex, nsValue) {-- // append namespace to namespace array- if (o.ns.namespaces.indexOf(nsValue) < 0) {- o.ns.namespaces.push(nsValue);- }-- f.each(lngNeedLoad, function(lngIndex, lngValue) {- resStore[lngValue] = resStore[lngValue] || {};- resStore[lngValue][nsValue] = store[lngValue][nsValue];-- todo--; // wait for all done befor callback- if (todo === 0 && cb) {- if (o.useLocalStorage) i18n.sync._storeLocal(resStore);- cb();- }- });- });- });- } else {- if (cb) cb();- }- }-- function setLng(lng, options, cb) {- if (typeof options === 'function') {- cb = options;- options = {};- } else if (!options) {- options = {};- }-- options.lng = lng;- return init(options, cb);- }-- function lng() {- return currentLng;- }-- function reload(cb) {- resStore = {};- setLng(currentLng, cb);- }- function addJqueryFunct() {- // $.t shortcut- $.t = $.t || translate;-- function parse(ele, key, options) {- if (key.length === 0) return;-- var attr = 'text';-- if (key.indexOf('[') === 0) {- var parts = key.split(']');- key = parts[1];- attr = parts[0].substr(1, parts[0].length-1);- }-- if (key.indexOf(';') === key.length-1) {- key = key.substr(0, key.length-2);- }-- var optionsToUse;- if (attr === 'html') {- optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;- ele.html($.t(key, optionsToUse));- } else if (attr === 'text') {- optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;- ele.text($.t(key, optionsToUse));- } else if (attr === 'prepend') {- optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;- ele.prepend($.t(key, optionsToUse));- } else if (attr === 'append') {- optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;- ele.append($.t(key, optionsToUse));- } else if (attr.indexOf("data-") === 0) {- var dataAttr = attr.substr(("data-").length);- optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;- var translated = $.t(key, optionsToUse);- //we change into the data cache- ele.data(dataAttr, translated);- //we change into the dom- ele.attr(attr, translated);- } else {- optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;- ele.attr(attr, $.t(key, optionsToUse));- }- }-- function localize(ele, options) {- var key = ele.attr(o.selectorAttr);- if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();- if (!key) return;-- var target = ele- , targetSelector = ele.data("i18n-target");- if (targetSelector) {- target = ele.find(targetSelector) || ele;- }-- if (!options && o.useDataAttrOptions === true) {- options = ele.data("i18n-options");- }- options = options || {};-- if (key.indexOf(';') >= 0) {- var keys = key.split(';');-- $.each(keys, function(m, k) {- if (k !== '') parse(target, k, options);- });-- } else {- parse(target, key, options);- }-- if (o.useDataAttrOptions === true) ele.data("i18n-options", options);- }-- // fn- $.fn.i18n = function (options) {- return this.each(function() {- // localize element itself- localize($(this), options);-- // localize childs- var elements = $(this).find('[' + o.selectorAttr + ']');- elements.each(function() {- localize($(this), options);- });- });- };- }- function applyReplacement(str, replacementHash, nestedKey, options) {- if (!str) return str;-- options = options || replacementHash; // first call uses replacement hash combined with options- if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;-- var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped- , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped- , unEscapingSuffix = 'HTML'+suffix;-- var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;- f.each(hash, function(key, value) {- var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;- if (typeof value === 'object' && value !== null) {- str = applyReplacement(str, value, nextKey, options);- } else {- if (options.escapeInterpolation || o.escapeInterpolation) {- str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));- str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));- } else {- str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));- }- // str = options.escapeInterpolation;- }- });- return str;- }-- // append it to functions- f.applyReplacement = applyReplacement;-- function applyReuse(translated, options) {- var comma = ',';- var options_open = '{';- var options_close = '}';-- var opts = f.extend({}, options);- delete opts.postProcess;-- while (translated.indexOf(o.reusePrefix) != -1) {- replacementCounter++;- if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion- var index_of_opening = translated.lastIndexOf(o.reusePrefix);- var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;- var token = translated.substring(index_of_opening, index_of_end_of_closing);- var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');-- if (index_of_end_of_closing <= index_of_opening) {- f.error('there is an missing closing in following translation value', translated);- return '';- }-- if (token_without_symbols.indexOf(comma) != -1) {- var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);- if (token_without_symbols.indexOf(options_open, index_of_token_end_of_closing) != -1 && token_without_symbols.indexOf(options_close, index_of_token_end_of_closing) != -1) {- var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);- var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;- try {- opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));- token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);- } catch (e) {- }- }- }-- var translated_token = _translate(token_without_symbols, opts);- translated = translated.replace(token, f.regexReplacementEscape(translated_token));- }- return translated;- }-- function hasContext(options) {- return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));- }-- function needsPlural(options, lng) {- return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);- }-- function needsIndefiniteArticle(options) {- return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);- }-- function exists(key, options) {- options = options || {};-- var notFound = _getDefaultValue(key, options)- , found = _find(key, options);-- return found !== undefined || found === notFound;- }-- function translate(key, options) {- options = options || {};-- if (!initialized) {- f.log('i18next not finished initialization. you might have called t function before loading resources finished.')- return options.defaultValue || '';- };- replacementCounter = 0;- return _translate.apply(null, arguments);- }-- function _getDefaultValue(key, options) {- return (options.defaultValue !== undefined) ? options.defaultValue : key;- }-- function _injectSprintfProcessor() {-- var values = [];-- // mh: build array from second argument onwards- for (var i = 1; i < arguments.length; i++) {- values.push(arguments[i]);- }-- return {- postProcess: 'sprintf',- sprintf: values- };- }-- function _translate(potentialKeys, options) {- if (options && typeof options !== 'object') {- if (o.shortcutFunction === 'sprintf') {- // mh: gettext like sprintf syntax found, automatically create sprintf processor- options = _injectSprintfProcessor.apply(null, arguments);- } else if (o.shortcutFunction === 'defaultValue') {- options = {- defaultValue: options- }- }- } else {- options = options || {};- }-- if (typeof o.defaultVariables === 'object') {- options = f.extend({}, o.defaultVariables, options);- }-- if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';-- if (typeof potentialKeys === 'string') {- potentialKeys = [potentialKeys];- }-- var key = potentialKeys[0];-- if (potentialKeys.length > 1) {- for (var i = 0; i < potentialKeys.length; i++) {- key = potentialKeys[i];- if (exists(key, options)) {- break;- }- }- }-- var notFound = _getDefaultValue(key, options)- , found = _find(key, options)- , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages- , ns = options.ns || o.ns.defaultNs- , parts;-- // split ns and key- if (key.indexOf(o.nsseparator) > -1) {- parts = key.split(o.nsseparator);- ns = parts[0];- key = parts[1];- }-- if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {- if (options.lng) {- o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);- } else {- o.missingKeyHandler(o.lng, ns, key, notFound, lngs);- }- }-- var postProcessor = options.postProcess || o.postProcess;- if (found !== undefined && postProcessor) {- if (postProcessors[postProcessor]) {- found = postProcessors[postProcessor](found, key, options);- }- }-- // process notFound if function exists- var splitNotFound = notFound;- if (notFound.indexOf(o.nsseparator) > -1) {- parts = notFound.split(o.nsseparator);- splitNotFound = parts[1];- }- if (splitNotFound === key && o.parseMissingKey) {- notFound = o.parseMissingKey(notFound);- }-- if (found === undefined) {- notFound = applyReplacement(notFound, options);- notFound = applyReuse(notFound, options);-- if (postProcessor && postProcessors[postProcessor]) {- var val = _getDefaultValue(key, options);- found = postProcessors[postProcessor](val, key, options);- }- }-- return (found !== undefined) ? found : notFound;- }-- function _find(key, options) {- options = options || {};-- var optionWithoutCount, translated- , notFound = _getDefaultValue(key, options)- , lngs = languages;-- if (!resStore) { return notFound; } // no resStore to translate from-- // CI mode- if (lngs[0].toLowerCase() === 'cimode') return notFound;-- // passed in lng- if (options.lngs) lngs = options.lngs;- if (options.lng) {- lngs = f.toLanguages(options.lng, options.fallbackLng);-- if (!resStore[lngs[0]]) {- var oldAsync = o.getAsync;- o.getAsync = false;-- i18n.sync.load(lngs, o, function(err, store) {- f.extend(resStore, store);- o.getAsync = oldAsync;- });- }- }-- var ns = options.ns || o.ns.defaultNs;- if (key.indexOf(o.nsseparator) > -1) {- var parts = key.split(o.nsseparator);- ns = parts[0];- key = parts[1];- }-- if (hasContext(options)) {- optionWithoutCount = f.extend({}, options);- delete optionWithoutCount.context;- optionWithoutCount.defaultValue = o.contextNotFound;-- var contextKey = ns + o.nsseparator + key + '_' + options.context;-- translated = translate(contextKey, optionWithoutCount);- if (translated != o.contextNotFound) {- return applyReplacement(translated, { context: options.context }); // apply replacement for context only- } // else continue translation with original/nonContext key- }-- if (needsPlural(options, lngs[0])) {- optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);- delete optionWithoutCount.count;- delete optionWithoutCount.lng;- optionWithoutCount.defaultValue = o.pluralNotFound;-- var pluralKey;- if (!pluralExtensions.needsPlural(lngs[0], options.count)) {- pluralKey = ns + o.nsseparator + key;- } else {- pluralKey = ns + o.nsseparator + key + o.pluralSuffix;- var pluralExtension = pluralExtensions.get(lngs[0], options.count);- if (pluralExtension >= 0) {- pluralKey = pluralKey + '_' + pluralExtension;- } else if (pluralExtension === 1) {- pluralKey = ns + o.nsseparator + key; // singular- }- }-- translated = translate(pluralKey, optionWithoutCount);-- if (translated != o.pluralNotFound) {- return applyReplacement(translated, {- count: options.count,- interpolationPrefix: options.interpolationPrefix,- interpolationSuffix: options.interpolationSuffix- }); // apply replacement for count only- } else if (lngs.length > 1) {- // remove failed lng- var clone = lngs.slice();- clone.shift();- options = f.extend(options, { lngs: clone });- delete options.lng;- // retry with fallbacks- translated = translate(ns + o.nsseparator + key, options);- if (translated != o.pluralNotFound) return translated;- } else {- return translated;- }- }-- if (needsIndefiniteArticle(options)) {- var optionsWithoutIndef = f.extend({}, options);- delete optionsWithoutIndef.indefinite_article;- optionsWithoutIndef.defaultValue = o.indefiniteNotFound;- // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false- var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");- translated = translate(indefiniteKey, optionsWithoutIndef);- if (translated != o.indefiniteNotFound) {- return translated;- }- }-- var found;- var keys = key.split(o.keyseparator);- for (var i = 0, len = lngs.length; i < len; i++ ) {- if (found !== undefined) break;-- var l = lngs[i];-- var x = 0;- var value = resStore[l] && resStore[l][ns];- while (keys[x]) {- value = value && value[keys[x]];- x++;- }- if (value !== undefined) {- var valueType = Object.prototype.toString.apply(value);- if (typeof value === 'string') {- value = applyReplacement(value, options);- value = applyReuse(value, options);- } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {- value = value.join('\n');- value = applyReplacement(value, options);- value = applyReuse(value, options);- } else if (value === null && o.fallbackOnNull === true) {- value = undefined;- } else if (value !== null) {- if (!o.returnObjectTrees && !options.returnObjectTrees) {- if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {- value = o.objectTreeKeyHandler(key, value, l, ns, options);- } else {- value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +- 'returned an object instead of string.';- f.log(value);- }- } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {- var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy- f.each(value, function(m) {- copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);- });- value = copy;- }- }-- if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)- value = undefined;-- found = value;- }- }-- if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {- // set flag for fallback lookup - avoid recursion- options.isFallbackLookup = true;-- if (o.fallbackNS.length) {-- for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {- found = _find(o.fallbackNS[y] + o.nsseparator + key, options);-- if (found || (found==="" && o.fallbackOnEmpty === false)) {- /* compare value without namespace */- var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found- , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;-- if (foundValue !== notFoundValue) break;- }- }- } else {- found = _find(key, options); // fallback to default NS- }- options.isFallbackLookup = false;- }-- return found;- }- function detectLanguage() {- var detectedLng;- var whitelist = o.lngWhitelist || [];- var userLngChoices = [];-- // get from qs- var qsParm = [];- if (typeof window !== 'undefined') {- (function() {- var query = window.location.search.substring(1);- var params = query.split('&');- for (var i=0; i<params.length; i++) {- var pos = params[i].indexOf('=');- if (pos > 0) {- var key = params[i].substring(0,pos);- if (key == o.detectLngQS) {- userLngChoices.push(params[i].substring(pos+1));- }- }- }- })();- }-- // get from cookie- if (o.useCookie && typeof document !== 'undefined') {- var c = f.cookie.read(o.cookieName);- if (c) userLngChoices.push(c);- }-- // get from localStorage- if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {- userLngChoices.push(window.localStorage.getItem('i18next_lng'));- }-- // get from navigator- if (typeof navigator !== 'undefined') {- if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating- for (var i=0;i<navigator.languages.length;i++) {- userLngChoices.push(navigator.languages[i]);- }- }- if (navigator.userLanguage) {- userLngChoices.push(navigator.userLanguage);- }- if (navigator.language) {- userLngChoices.push(navigator.language);- }- }-- (function() {- for (var i=0;i<userLngChoices.length;i++) {- var lng = userLngChoices[i];-- if (lng.indexOf('-') > -1) {- var parts = lng.split('-');- lng = o.lowerCaseLng ?- parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :- parts[0].toLowerCase() + '-' + parts[1].toUpperCase();- }-- if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {- detectedLng = lng;- break;- }- }- })();-- //fallback- if (!detectedLng){- detectedLng = o.fallbackLng[0];- }-- return detectedLng;- }- // definition http://translate.sourceforge.net/wiki/l10n/pluralforms-- /* [code, name, numbers, pluralsType] */- var _rules = [- ["ach", "Acholi", [1,2], 1],- ["af", "Afrikaans",[1,2], 2],- ["ak", "Akan", [1,2], 1],- ["am", "Amharic", [1,2], 1],- ["an", "Aragonese",[1,2], 2],- ["ar", "Arabic", [0,1,2,3,11,100],5],- ["arn", "Mapudungun",[1,2], 1],- ["ast", "Asturian", [1,2], 2],- ["ay", "Aymará", [1], 3],- ["az", "Azerbaijani",[1,2],2],- ["be", "Belarusian",[1,2,5],4],- ["bg", "Bulgarian",[1,2], 2],- ["bn", "Bengali", [1,2], 2],- ["bo", "Tibetan", [1], 3],- ["br", "Breton", [1,2], 1],- ["bs", "Bosnian", [1,2,5],4],- ["ca", "Catalan", [1,2], 2],- ["cgg", "Chiga", [1], 3],- ["cs", "Czech", [1,2,5],6],- ["csb", "Kashubian",[1,2,5],7],- ["cy", "Welsh", [1,2,3,8],8],- ["da", "Danish", [1,2], 2],- ["de", "German", [1,2], 2],- ["dev", "Development Fallback", [1,2], 2],- ["dz", "Dzongkha", [1], 3],- ["el", "Greek", [1,2], 2],- ["en", "English", [1,2], 2],- ["eo", "Esperanto",[1,2], 2],- ["es", "Spanish", [1,2], 2],- ["es_ar","Argentinean Spanish", [1,2], 2],- ["et", "Estonian", [1,2], 2],- ["eu", "Basque", [1,2], 2],- ["fa", "Persian", [1], 3],- ["fi", "Finnish", [1,2], 2],- ["fil", "Filipino", [1,2], 1],- ["fo", "Faroese", [1,2], 2],- ["fr", "French", [1,2], 9],- ["fur", "Friulian", [1,2], 2],- ["fy", "Frisian", [1,2], 2],- ["ga", "Irish", [1,2,3,7,11],10],- ["gd", "Scottish Gaelic",[1,2,3,20],11],- ["gl", "Galician", [1,2], 2],- ["gu", "Gujarati", [1,2], 2],- ["gun", "Gun", [1,2], 1],- ["ha", "Hausa", [1,2], 2],- ["he", "Hebrew", [1,2], 2],- ["hi", "Hindi", [1,2], 2],- ["hr", "Croatian", [1,2,5],4],- ["hu", "Hungarian",[1,2], 2],- ["hy", "Armenian", [1,2], 2],- ["ia", "Interlingua",[1,2],2],- ["id", "Indonesian",[1], 3],- ["is", "Icelandic",[1,2], 12],- ["it", "Italian", [1,2], 2],- ["ja", "Japanese", [1], 3],- ["jbo", "Lojban", [1], 3],- ["jv", "Javanese", [0,1], 13],- ["ka", "Georgian", [1], 3],- ["kk", "Kazakh", [1], 3],- ["km", "Khmer", [1], 3],- ["kn", "Kannada", [1,2], 2],- ["ko", "Korean", [1], 3],- ["ku", "Kurdish", [1,2], 2],- ["kw", "Cornish", [1,2,3,4],14],- ["ky", "Kyrgyz", [1], 3],- ["lb", "Letzeburgesch",[1,2],2],- ["ln", "Lingala", [1,2], 1],- ["lo", "Lao", [1], 3],- ["lt", "Lithuanian",[1,2,10],15],- ["lv", "Latvian", [1,2,0],16],- ["mai", "Maithili", [1,2], 2],- ["mfe", "Mauritian Creole",[1,2],1],- ["mg", "Malagasy", [1,2], 1],- ["mi", "Maori", [1,2], 1],- ["mk", "Macedonian",[1,2],17],- ["ml", "Malayalam",[1,2], 2],- ["mn", "Mongolian",[1,2], 2],- ["mnk", "Mandinka", [0,1,2],18],- ["mr", "Marathi", [1,2], 2],- ["ms", "Malay", [1], 3],- ["mt", "Maltese", [1,2,11,20],19],- ["nah", "Nahuatl", [1,2], 2],- ["nap", "Neapolitan",[1,2], 2],- ["nb", "Norwegian Bokmal",[1,2],2],- ["ne", "Nepali", [1,2], 2],- ["nl", "Dutch", [1,2], 2],- ["nn", "Norwegian Nynorsk",[1,2],2],- ["no", "Norwegian",[1,2], 2],- ["nso", "Northern Sotho",[1,2],2],- ["oc", "Occitan", [1,2], 1],- ["or", "Oriya", [2,1], 2],- ["pa", "Punjabi", [1,2], 2],- ["pap", "Papiamento",[1,2], 2],- ["pl", "Polish", [1,2,5],7],- ["pms", "Piemontese",[1,2], 2],- ["ps", "Pashto", [1,2], 2],- ["pt", "Portuguese",[1,2], 2],- ["pt_br","Brazilian Portuguese",[1,2], 2],- ["rm", "Romansh", [1,2], 2],- ["ro", "Romanian", [1,2,20],20],- ["ru", "Russian", [1,2,5],4],- ["sah", "Yakut", [1], 3],- ["sco", "Scots", [1,2], 2],- ["se", "Northern Sami",[1,2], 2],- ["si", "Sinhala", [1,2], 2],- ["sk", "Slovak", [1,2,5],6],- ["sl", "Slovenian",[5,1,2,3],21],- ["so", "Somali", [1,2], 2],- ["son", "Songhay", [1,2], 2],- ["sq", "Albanian", [1,2], 2],- ["sr", "Serbian", [1,2,5],4],- ["su", "Sundanese",[1], 3],- ["sv", "Swedish", [1,2], 2],- ["sw", "Swahili", [1,2], 2],- ["ta", "Tamil", [1,2], 2],- ["te", "Telugu", [1,2], 2],- ["tg", "Tajik", [1,2], 1],- ["th", "Thai", [1], 3],- ["ti", "Tigrinya", [1,2], 1],- ["tk", "Turkmen", [1,2], 2],- ["tr", "Turkish", [1,2], 1],- ["tt", "Tatar", [1], 3],- ["ug", "Uyghur", [1], 3],- ["uk", "Ukrainian",[1,2,5],4],- ["ur", "Urdu", [1,2], 2],- ["uz", "Uzbek", [1,2], 1],- ["vi", "Vietnamese",[1], 3],- ["wa", "Walloon", [1,2], 1],- ["wo", "Wolof", [1], 3],- ["yo", "Yoruba", [1,2], 2],- ["zh", "Chinese", [1], 3]- ];-- var _rulesPluralsTypes = {- 1: function(n) {return Number(n > 1);},- 2: function(n) {return Number(n != 1);},- 3: function(n) {return 0;},- 4: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},- 5: function(n) {return Number(n===0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 ? 4 : 5);},- 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},- 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},- 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},- 9: function(n) {return Number(n >= 2);},- 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},- 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},- 12: function(n) {return Number(n%10!=1 || n%100==11);},- 13: function(n) {return Number(n !== 0);},- 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},- 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},- 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},- 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},- 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},- 19: function(n) {return Number(n==1 ? 0 : n===0 || ( n%100>1 && n%100<11) ? 1 : (n%100>10 && n%100<20 ) ? 2 : 3);},- 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},- 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }- };-- var pluralExtensions = {-- rules: (function () {- var l, rules = {};- for (l=_rules.length; l-- ;) {- rules[_rules[l][0]] = {- name: _rules[l][1],- numbers: _rules[l][2],- plurals: _rulesPluralsTypes[_rules[l][3]]- }- }- return rules;- }()),-- // you can add your own pluralExtensions- addRule: function(lng, obj) {- pluralExtensions.rules[lng] = obj;- },-- setCurrentLng: function(lng) {- if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {- var parts = lng.split('-');-- pluralExtensions.currentRule = {- lng: lng,- rule: pluralExtensions.rules[parts[0]]- };- }- },-- needsPlural: function(lng, count) {- var parts = lng.split('-');-- var ext;- if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {- ext = pluralExtensions.currentRule.rule;- } else {- ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];- }-- if (ext && ext.numbers.length <= 1) {- return false;- } else {- return this.get(lng, count) !== 1;- }- },-- get: function(lng, count) {- var parts = lng.split('-');-- function getResult(l, c) {- var ext;- if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {- ext = pluralExtensions.currentRule.rule;- } else {- ext = pluralExtensions.rules[l];- }- if (ext) {- var i;- if (ext.noAbs) {- i = ext.plurals(c);- } else {- i = ext.plurals(Math.abs(c));- }-- var number = ext.numbers[i];- if (ext.numbers.length === 2 && ext.numbers[0] === 1) {- if (number === 2) {- number = -1; // regular plural- } else if (number === 1) {- number = 1; // singular- }- }//console.log(count + '-' + number);- return number;- } else {- return c === 1 ? '1' : '-1';- }- }-- return getResult(parts[f.getCountyIndexOfLng(lng)], count);- }-- };- var postProcessors = {};- var addPostProcessor = function(name, fc) {- postProcessors[name] = fc;- };- // sprintf support- var sprintf = (function() {- function get_type(variable) {- return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();- }- function str_repeat(input, multiplier) {- for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}- return output.join('');- }-- var str_format = function() {- if (!str_format.cache.hasOwnProperty(arguments[0])) {- str_format.cache[arguments[0]] = str_format.parse(arguments[0]);- }- return str_format.format.call(null, str_format.cache[arguments[0]], arguments);- };-- str_format.format = function(parse_tree, argv) {- var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;- for (i = 0; i < tree_length; i++) {- node_type = get_type(parse_tree[i]);- if (node_type === 'string') {- output.push(parse_tree[i]);- }- else if (node_type === 'array') {- match = parse_tree[i]; // convenience purposes only- if (match[2]) { // keyword argument- arg = argv[cursor];- for (k = 0; k < match[2].length; k++) {- if (!arg.hasOwnProperty(match[2][k])) {- throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));- }- arg = arg[match[2][k]];- }- }- else if (match[1]) { // positional argument (explicit)- arg = argv[match[1]];- }- else { // positional argument (implicit)- arg = argv[cursor++];- }-- if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {- throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));- }- switch (match[8]) {- case 'b': arg = arg.toString(2); break;- case 'c': arg = String.fromCharCode(arg); break;- case 'd': arg = parseInt(arg, 10); break;- case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;- case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;- case 'o': arg = arg.toString(8); break;- case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;- case 'u': arg = Math.abs(arg); break;- case 'x': arg = arg.toString(16); break;- case 'X': arg = arg.toString(16).toUpperCase(); break;- }- arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);- pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';- pad_length = match[6] - String(arg).length;- pad = match[6] ? str_repeat(pad_character, pad_length) : '';- output.push(match[5] ? arg + pad : pad + arg);- }- }- return output.join('');- };-- str_format.cache = {};-- str_format.parse = function(fmt) {- var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;- while (_fmt) {- if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {- parse_tree.push(match[0]);- }- else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {- parse_tree.push('%');- }- else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {- if (match[2]) {- arg_names |= 1;- var field_list = [], replacement_field = match[2], field_match = [];- if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {- field_list.push(field_match[1]);- while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {- if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {- field_list.push(field_match[1]);- }- else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {- field_list.push(field_match[1]);- }- else {- throw('[sprintf] huh?');- }- }- }- else {- throw('[sprintf] huh?');- }- match[2] = field_list;- }- else {- arg_names |= 2;- }- if (arg_names === 3) {- throw('[sprintf] mixing positional and named placeholders is not (yet) supported');- }- parse_tree.push(match);- }- else {- throw('[sprintf] huh?');- }- _fmt = _fmt.substring(match[0].length);- }- return parse_tree;- };-- return str_format;- })();-- var vsprintf = function(fmt, argv) {- argv.unshift(fmt);- return sprintf.apply(null, argv);- };-- addPostProcessor("sprintf", function(val, key, opts) {- if (!opts.sprintf) return val;-- if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {- return vsprintf(val, opts.sprintf);- } else if (typeof opts.sprintf === 'object') {- return sprintf(val, opts.sprintf);- }-- return val;- });- // public api interface- i18n.init = init;- i18n.setLng = setLng;- i18n.preload = preload;- i18n.addResourceBundle = addResourceBundle;- i18n.hasResourceBundle = hasResourceBundle;- i18n.addResource = addResource;- i18n.addResources = addResources;- i18n.removeResourceBundle = removeResourceBundle;- i18n.loadNamespace = loadNamespace;- i18n.loadNamespaces = loadNamespaces;- i18n.setDefaultNamespace = setDefaultNamespace;- i18n.t = translate;- i18n.translate = translate;- i18n.exists = exists;- i18n.detectLanguage = f.detectLanguage;- i18n.pluralExtensions = pluralExtensions;- i18n.sync = sync;- i18n.functions = f;- i18n.lng = lng;- i18n.addPostProcessor = addPostProcessor;- i18n.options = o;--})();-},{"jquery":"jquery"}],66:[function(require,module,exports){-// Top level file is just a mixin of submodules & constants-'use strict';--var assign = require('./lib/utils/common').assign;--var deflate = require('./lib/deflate');-var inflate = require('./lib/inflate');-var constants = require('./lib/zlib/constants');--var pako = {};--assign(pako, deflate, inflate, constants);--module.exports = pako;-},{"./lib/deflate":67,"./lib/inflate":68,"./lib/utils/common":69,"./lib/zlib/constants":72}],67:[function(require,module,exports){-'use strict';---var zlib_deflate = require('./zlib/deflate.js');-var utils = require('./utils/common');-var strings = require('./utils/strings');-var msg = require('./zlib/messages');-var zstream = require('./zlib/zstream');--var toString = Object.prototype.toString;--/* Public constants ==========================================================*/-/* ===========================================================================*/--var Z_NO_FLUSH = 0;-var Z_FINISH = 4;--var Z_OK = 0;-var Z_STREAM_END = 1;--var Z_DEFAULT_COMPRESSION = -1;--var Z_DEFAULT_STRATEGY = 0;--var Z_DEFLATED = 8;--/* ===========================================================================*/-+process.on = noop;+process.addListener = noop;+process.once = noop;+process.off = noop;+process.removeListener = noop;+process.removeAllListeners = noop;+process.emit = noop;-/**- * class Deflate- *- * Generic JS-style wrapper for zlib calls. If you don't need- * streaming behaviour - use more simple functions: [[deflate]],- * [[deflateRaw]] and [[gzip]].- **/+process.binding = function (name) {+ throw new Error('process.binding is not supported');+};-/* internal- * Deflate.chunks -> Array- *- * Chunks of output data, if [[Deflate#onData]] not overriden.- **/+// TODO(shtylman)+process.cwd = function () { return '/' };+process.chdir = function (dir) {+ throw new Error('process.chdir is not supported');+};+process.umask = function() { return 0; };-/**- * Deflate.result -> Uint8Array|Array- *- * Compressed result, generated by default [[Deflate#onData]]- * and [[Deflate#onEnd]] handlers. Filled after you push last chunk- * (call [[Deflate#push]] with `Z_FINISH` / `true` param).- **/+},{}],65:[function(require,module,exports){+// Copyright Joyent, Inc. and other Node contributors.+//+// Permission is hereby granted, free of charge, to any person obtaining a+// copy of this software and associated documentation files (the+// "Software"), to deal in the Software without restriction, including+// without limitation the rights to use, copy, modify, merge, publish,+// distribute, sublicense, and/or sell copies of the Software, and to permit+// persons to whom the Software is furnished to do so, subject to the+// following conditions:+//+// The above copyright notice and this permission notice shall be included+// in all copies or substantial portions of the Software.+//+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE+// USE OR OTHER DEALINGS IN THE SOFTWARE.-/**- * Deflate.err -> Number- *- * Error code after deflate finished. 0 (Z_OK) on success.- * You will not need it in real life, because deflate errors- * are possible only on wrong options or bad `onData` / `onEnd`- * custom handlers.- **/+function EventEmitter() {+ this._events = this._events || {};+ this._maxListeners = this._maxListeners || undefined;+}+module.exports = EventEmitter;-/**- * Deflate.msg -> String- *- * Error message, if [[Deflate.err]] != 0- **/+// Backwards-compat with node 0.10.x+EventEmitter.EventEmitter = EventEmitter;+EventEmitter.prototype._events = undefined;+EventEmitter.prototype._maxListeners = undefined;-/**- * new Deflate(options)- * - options (Object): zlib deflate options.- *- * Creates new deflator instance with specified params. Throws exception- * on bad params. Supported options:- *- * - `level`- * - `windowBits`- * - `memLevel`- * - `strategy`- *- * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)- * for more information on these.- *- * Additional options, for internal needs:- *- * - `chunkSize` - size of generated data chunks (16K by default)- * - `raw` (Boolean) - do raw deflate- * - `gzip` (Boolean) - create gzip wrapper- * - `to` (String) - if equal to 'string', then result will be "binary string"- * (each char code [0..255])- * - `header` (Object) - custom header for gzip- * - `text` (Boolean) - true if compressed data believed to be text- * - `time` (Number) - modification time, unix timestamp- * - `os` (Number) - operation system code- * - `extra` (Array) - array of bytes with extra data (max 65536)- * - `name` (String) - file name (binary string)- * - `comment` (String) - comment (binary string)- * - `hcrc` (Boolean) - true if header crc should be added- *- * ##### Example:- *- * ```javascript- * var pako = require('pako')- * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])- * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);- *- * var deflate = new pako.Deflate({ level: 3});- *- * deflate.push(chunk1, false);- * deflate.push(chunk2, true); // true -> last chunk- *- * if (deflate.err) { throw new Error(deflate.err); }- *- * console.log(deflate.result);- * ```- **/-var Deflate = function(options) {+// By default EventEmitters will print a warning if more than 10 listeners are+// added to it. This is a useful default which helps finding memory leaks.+EventEmitter.defaultMaxListeners = 10;- this.options = utils.assign({- level: Z_DEFAULT_COMPRESSION,- method: Z_DEFLATED,- chunkSize: 16384,- windowBits: 15,- memLevel: 8,- strategy: Z_DEFAULT_STRATEGY,- to: ''- }, options || {});+// Obviously not all Emitters should be limited to 10. This function allows+// that to be increased. Set to zero for unlimited.+EventEmitter.prototype.setMaxListeners = function(n) {+ if (!isNumber(n) || n < 0 || isNaN(n))+ throw TypeError('n must be a positive number');+ this._maxListeners = n;+ return this;+};- var opt = this.options;+EventEmitter.prototype.emit = function(type) {+ var er, handler, len, args, i, listeners;- if (opt.raw && (opt.windowBits > 0)) {- opt.windowBits = -opt.windowBits;- }+ if (!this._events)+ this._events = {};- else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {- opt.windowBits += 16;+ // If there is no 'error' event listener then throw.+ if (type === 'error') {+ if (!this._events.error ||+ (isObject(this._events.error) && !this._events.error.length)) {+ er = arguments[1];+ if (er instanceof Error) {+ throw er; // Unhandled 'error' event+ }+ throw TypeError('Uncaught, unspecified "error" event.');+ }}- this.err = 0; // error code, if happens (0 = Z_OK)- this.msg = ''; // error message- this.ended = false; // used to avoid multiple onEnd() calls- this.chunks = []; // chunks of compressed data-- this.strm = new zstream();- this.strm.avail_out = 0;+ handler = this._events[type];- var status = zlib_deflate.deflateInit2(- this.strm,- opt.level,- opt.method,- opt.windowBits,- opt.memLevel,- opt.strategy- );+ if (isUndefined(handler))+ return false;- if (status !== Z_OK) {- throw new Error(msg[status]);- }+ if (isFunction(handler)) {+ switch (arguments.length) {+ // fast cases+ case 1:+ handler.call(this);+ break;+ case 2:+ handler.call(this, arguments[1]);+ break;+ case 3:+ handler.call(this, arguments[1], arguments[2]);+ break;+ // slower+ default:+ len = arguments.length;+ args = new Array(len - 1);+ for (i = 1; i < len; i++)+ args[i - 1] = arguments[i];+ handler.apply(this, args);+ }+ } else if (isObject(handler)) {+ len = arguments.length;+ args = new Array(len - 1);+ for (i = 1; i < len; i++)+ args[i - 1] = arguments[i];- if (opt.header) {- zlib_deflate.deflateSetHeader(this.strm, opt.header);+ listeners = handler.slice();+ len = listeners.length;+ for (i = 0; i < len; i++)+ listeners[i].apply(this, args);}++ return true;};-/**- * Deflate#push(data[, mode]) -> Boolean- * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be- * converted to utf8 byte sequence.- * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.- * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.- *- * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with- * new compressed chunks. Returns `true` on success. The last data block must have- * mode Z_FINISH (or `true`). That flush internal pending buffers and call- * [[Deflate#onEnd]].- *- * On fail call [[Deflate#onEnd]] with error code and return false.- *- * We strongly recommend to use `Uint8Array` on input for best speed (output- * array format is detected automatically). Also, don't skip last param and always- * use the same type in your code (boolean or number). That will improve JS speed.- *- * For regular `Array`-s make sure all elements are [0..255].- *- * ##### Example- *- * ```javascript- * push(chunk, false); // push one of data chunks- * ...- * push(chunk, true); // push last chunk- * ```- **/-Deflate.prototype.push = function(data, mode) {- var strm = this.strm;- var chunkSize = this.options.chunkSize;- var status, _mode;+EventEmitter.prototype.addListener = function(type, listener) {+ var m;- if (this.ended) { return false; }+ if (!isFunction(listener))+ throw TypeError('listener must be a function');- _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);+ if (!this._events)+ this._events = {};- // Convert data if needed- if (typeof data === 'string') {- // If we need to compress text, change encoding to utf8.- strm.input = strings.string2buf(data);- } else if (toString.call(data) === '[object ArrayBuffer]') {- strm.input = new Uint8Array(data);- } else {- strm.input = data;- }+ // To avoid recursion in the case that type === "newListener"! Before+ // adding it to the listeners, first emit "newListener".+ if (this._events.newListener)+ this.emit('newListener', type,+ isFunction(listener.listener) ?+ listener.listener : listener);- strm.next_in = 0;- strm.avail_in = strm.input.length;+ if (!this._events[type])+ // Optimize the case of one listener. Don't need the extra array object.+ this._events[type] = listener;+ else if (isObject(this._events[type]))+ // If we've already got an array, just append.+ this._events[type].push(listener);+ else+ // Adding the second element, need to change to array.+ this._events[type] = [this._events[type], listener];- do {- if (strm.avail_out === 0) {- strm.output = new utils.Buf8(chunkSize);- strm.next_out = 0;- strm.avail_out = chunkSize;+ // Check for listener leak+ if (isObject(this._events[type]) && !this._events[type].warned) {+ var m;+ if (!isUndefined(this._maxListeners)) {+ m = this._maxListeners;+ } else {+ m = EventEmitter.defaultMaxListeners;}- status = zlib_deflate.deflate(strm, _mode); /* no bad return value */- if (status !== Z_STREAM_END && status !== Z_OK) {- this.onEnd(status);- this.ended = true;- return false;- }- if (strm.avail_out === 0 || (strm.avail_in === 0 && _mode === Z_FINISH)) {- if (this.options.to === 'string') {- this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));- } else {- this.onData(utils.shrinkBuf(strm.output, strm.next_out));+ if (m && m > 0 && this._events[type].length > m) {+ this._events[type].warned = true;+ console.error('(node) warning: possible EventEmitter memory ' ++ 'leak detected. %d listeners added. ' ++ 'Use emitter.setMaxListeners() to increase limit.',+ this._events[type].length);+ if (typeof console.trace === 'function') {+ // not supported in IE 10+ console.trace();}}- } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);-- // Finalize on the last chunk.- if (_mode === Z_FINISH) {- status = zlib_deflate.deflateEnd(this.strm);- this.onEnd(status);- this.ended = true;- return status === Z_OK;}- return true;+ return this;};+EventEmitter.prototype.on = EventEmitter.prototype.addListener;-/**- * Deflate#onData(chunk) -> Void- * - chunk (Uint8Array|Array|String): ouput data. Type of array depends- * on js engine support. When string output requested, each chunk- * will be string.- *- * By default, stores data blocks in `chunks[]` property and glue- * those in `onEnd`. Override this handler, if you need another behaviour.- **/-Deflate.prototype.onData = function(chunk) {- this.chunks.push(chunk);-};+EventEmitter.prototype.once = function(type, listener) {+ if (!isFunction(listener))+ throw TypeError('listener must be a function');+ var fired = false;-/**- * Deflate#onEnd(status) -> Void- * - status (Number): deflate status. 0 (Z_OK) on success,- * other if not.- *- * Called once after you tell deflate that input stream complete- * or error happenned. By default - join collected chunks,- * free memory and fill `results` / `err` properties.- **/-Deflate.prototype.onEnd = function(status) {- // On success - join- if (status === Z_OK) {- if (this.options.to === 'string') {- this.result = this.chunks.join('');- } else {- this.result = utils.flattenChunks(this.chunks);+ function g() {+ this.removeListener(type, g);++ if (!fired) {+ fired = true;+ listener.apply(this, arguments);}}- this.chunks = [];- this.err = status;- this.msg = this.strm.msg;++ g.listener = listener;+ this.on(type, g);++ return this;};+// emits a 'removeListener' event iff the listener was removed+EventEmitter.prototype.removeListener = function(type, listener) {+ var list, position, length, i;-/**- * deflate(data[, options]) -> Uint8Array|Array|String- * - data (Uint8Array|Array|String): input data to compress.- * - options (Object): zlib deflate options.- *- * Compress `data` with deflate alrorythm and `options`.- *- * Supported options are:- *- * - level- * - windowBits- * - memLevel- * - strategy- *- * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)- * for more information on these.- *- * Sugar (options):- *- * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify- * negative windowBits implicitly.- * - `to` (String) - if equal to 'string', then result will be "binary string"- * (each char code [0..255])- *- * ##### Example:- *- * ```javascript- * var pako = require('pako')- * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);- *- * console.log(pako.deflate(data));- * ```- **/-function deflate(input, options) {- var deflator = new Deflate(options);+ if (!isFunction(listener))+ throw TypeError('listener must be a function');- deflator.push(input, true);+ if (!this._events || !this._events[type])+ return this;- // That will never happens, if you don't cheat with options :)- if (deflator.err) { throw deflator.msg; }+ list = this._events[type];+ length = list.length;+ position = -1;- return deflator.result;-}+ if (list === listener ||+ (isFunction(list.listener) && list.listener === listener)) {+ delete this._events[type];+ if (this._events.removeListener)+ this.emit('removeListener', type, listener);+ } else if (isObject(list)) {+ for (i = length; i-- > 0;) {+ if (list[i] === listener ||+ (list[i].listener && list[i].listener === listener)) {+ position = i;+ break;+ }+ }-/**- * deflateRaw(data[, options]) -> Uint8Array|Array|String- * - data (Uint8Array|Array|String): input data to compress.- * - options (Object): zlib deflate options.- *- * The same as [[deflate]], but creates raw data, without wrapper- * (header and adler32 crc).- **/-function deflateRaw(input, options) {- options = options || {};- options.raw = true;- return deflate(input, options);-}+ if (position < 0)+ return this;+ if (list.length === 1) {+ list.length = 0;+ delete this._events[type];+ } else {+ list.splice(position, 1);+ }-/**- * gzip(data[, options]) -> Uint8Array|Array|String- * - data (Uint8Array|Array|String): input data to compress.- * - options (Object): zlib deflate options.- *- * The same as [[deflate]], but create gzip wrapper instead of- * deflate one.- **/-function gzip(input, options) {- options = options || {};- options.gzip = true;- return deflate(input, options);-}+ if (this._events.removeListener)+ this.emit('removeListener', type, listener);+ }+ return this;+};-exports.Deflate = Deflate;-exports.deflate = deflate;-exports.deflateRaw = deflateRaw;-exports.gzip = gzip;-},{"./utils/common":69,"./utils/strings":70,"./zlib/deflate.js":74,"./zlib/messages":79,"./zlib/zstream":81}],68:[function(require,module,exports){-'use strict';+EventEmitter.prototype.removeAllListeners = function(type) {+ var key, listeners;+ if (!this._events)+ return this;-var zlib_inflate = require('./zlib/inflate.js');-var utils = require('./utils/common');-var strings = require('./utils/strings');-var c = require('./zlib/constants');-var msg = require('./zlib/messages');-var zstream = require('./zlib/zstream');-var gzheader = require('./zlib/gzheader');+ // not listening for removeListener, no need to emit+ if (!this._events.removeListener) {+ if (arguments.length === 0)+ this._events = {};+ else if (this._events[type])+ delete this._events[type];+ return this;+ }-var toString = Object.prototype.toString;+ // emit removeListener for all listeners on all events+ if (arguments.length === 0) {+ for (key in this._events) {+ if (key === 'removeListener') continue;+ this.removeAllListeners(key);+ }+ this.removeAllListeners('removeListener');+ this._events = {};+ return this;+ }-/**- * class Inflate- *- * Generic JS-style wrapper for zlib calls. If you don't need- * streaming behaviour - use more simple functions: [[inflate]]- * and [[inflateRaw]].- **/+ listeners = this._events[type];-/* internal- * inflate.chunks -> Array- *- * Chunks of output data, if [[Inflate#onData]] not overriden.- **/+ if (isFunction(listeners)) {+ this.removeListener(type, listeners);+ } else {+ // LIFO order+ while (listeners.length)+ this.removeListener(type, listeners[listeners.length - 1]);+ }+ delete this._events[type];-/**- * Inflate.result -> Uint8Array|Array|String- *- * Uncompressed result, generated by default [[Inflate#onData]]- * and [[Inflate#onEnd]] handlers. Filled after you push last chunk- * (call [[Inflate#push]] with `Z_FINISH` / `true` param).- **/+ return this;+};-/**- * Inflate.err -> Number- *- * Error code after inflate finished. 0 (Z_OK) on success.- * Should be checked if broken data possible.- **/+EventEmitter.prototype.listeners = function(type) {+ var ret;+ if (!this._events || !this._events[type])+ ret = [];+ else if (isFunction(this._events[type]))+ ret = [this._events[type]];+ else+ ret = this._events[type].slice();+ return ret;+};-/**- * Inflate.msg -> String- *- * Error message, if [[Inflate.err]] != 0- **/+EventEmitter.listenerCount = function(emitter, type) {+ var ret;+ if (!emitter._events || !emitter._events[type])+ ret = 0;+ else if (isFunction(emitter._events[type]))+ ret = 1;+ else+ ret = emitter._events[type].length;+ return ret;+};+function isFunction(arg) {+ return typeof arg === 'function';+}-/**- * new Inflate(options)- * - options (Object): zlib inflate options.- *- * Creates new inflator instance with specified params. Throws exception- * on bad params. Supported options:- *- * - `windowBits`- *- * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)- * for more information on these.- *- * Additional options, for internal needs:- *- * - `chunkSize` - size of generated data chunks (16K by default)- * - `raw` (Boolean) - do raw inflate- * - `to` (String) - if equal to 'string', then result will be converted- * from utf8 to utf16 (javascript) string. When string output requested,- * chunk length can differ from `chunkSize`, depending on content.- *- * By default, when no options set, autodetect deflate/gzip data format via- * wrapper header.- *- * ##### Example:- *- * ```javascript- * var pako = require('pako')- * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])- * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);- *- * var inflate = new pako.Inflate({ level: 3});- *- * inflate.push(chunk1, false);- * inflate.push(chunk2, true); // true -> last chunk- *- * if (inflate.err) { throw new Error(inflate.err); }- *- * console.log(inflate.result);- * ```- **/-var Inflate = function(options) {+function isNumber(arg) {+ return typeof arg === 'number';+}- this.options = utils.assign({- chunkSize: 16384,- windowBits: 0,- to: ''- }, options || {});+function isObject(arg) {+ return typeof arg === 'object' && arg !== null;+}- var opt = this.options;+function isUndefined(arg) {+ return arg === void 0;+}- // Force window size for `raw` data, if not set directly,- // because we have no header for autodetect.- if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {- opt.windowBits = -opt.windowBits;- if (opt.windowBits === 0) { opt.windowBits = -15; }- }+},{}],66:[function(require,module,exports){+// i18next, v1.7.7+// Copyright (c)2014 Jan Mühlemann (jamuhl).+// Distributed under MIT license+// http://i18next.com+(function() {++ // add indexOf to non ECMA-262 standard compliant browsers+ if (!Array.prototype.indexOf) {+ Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {+ "use strict";+ if (this == null) {+ throw new TypeError();+ }+ var t = Object(this);+ var len = t.length >>> 0;+ if (len === 0) {+ return -1;+ }+ var n = 0;+ if (arguments.length > 0) {+ n = Number(arguments[1]);+ if (n != n) { // shortcut for verifying if it's NaN+ n = 0;+ } else if (n != 0 && n != Infinity && n != -Infinity) {+ n = (n > 0 || -1) * Math.floor(Math.abs(n));+ }+ }+ if (n >= len) {+ return -1;+ }+ var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);+ for (; k < len; k++) {+ if (k in t && t[k] === searchElement) {+ return k;+ }+ }+ return -1;+ }+ }++ // add lastIndexOf to non ECMA-262 standard compliant browsers+ if (!Array.prototype.lastIndexOf) {+ Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {+ "use strict";+ if (this == null) {+ throw new TypeError();+ }+ var t = Object(this);+ var len = t.length >>> 0;+ if (len === 0) {+ return -1;+ }+ var n = len;+ if (arguments.length > 1) {+ n = Number(arguments[1]);+ if (n != n) {+ n = 0;+ } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {+ n = (n > 0 || -1) * Math.floor(Math.abs(n));+ }+ }+ var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);+ for (; k >= 0; k--) {+ if (k in t && t[k] === searchElement) {+ return k;+ }+ }+ return -1;+ };+ }++ // Add string trim for IE8.+ if (typeof String.prototype.trim !== 'function') {+ String.prototype.trim = function() {+ return this.replace(/^\s+|\s+$/g, '');+ }+ }++ var root = this+ , $ = root.jQuery || root.Zepto+ , i18n = {}+ , resStore = {}+ , currentLng+ , replacementCounter = 0+ , languages = []+ , initialized = false+ , sync = {};- // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate- if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&- !(options && options.windowBits)) {- opt.windowBits += 32;- }- // Gzip header has no info about windows size, we can do autodetect only- // for deflate. So, if window size not set, force it to max when gzip possible- if ((opt.windowBits > 15) && (opt.windowBits < 48)) {- // bit 3 (16) -> gzipped data- // bit 4 (32) -> autodetect gzip/deflate- if ((opt.windowBits & 15) === 0) {- opt.windowBits |= 15;++ // Export the i18next object for **CommonJS**.+ // If we're not in CommonJS, add `i18n` to the+ // global object or to jquery.+ if (typeof module !== 'undefined' && module.exports) {+ if (!$) {+ try {+ $ = require('jquery');+ } catch(e) {+ // just ignore+ }+ }+ if ($) {+ $.i18n = $.i18n || i18n;+ }+ module.exports = i18n;+ } else {+ if ($) {+ $.i18n = $.i18n || i18n;+ }++ root.i18n = root.i18n || i18n;+ }+ sync = {++ load: function(lngs, options, cb) {+ if (options.useLocalStorage) {+ sync._loadLocal(lngs, options, function(err, store) {+ var missingLngs = [];+ for (var i = 0, len = lngs.length; i < len; i++) {+ if (!store[lngs[i]]) missingLngs.push(lngs[i]);+ }++ if (missingLngs.length > 0) {+ sync._fetch(missingLngs, options, function(err, fetched) {+ f.extend(store, fetched);+ sync._storeLocal(fetched);++ cb(null, store);+ });+ } else {+ cb(null, store);+ }+ });+ } else {+ sync._fetch(lngs, options, function(err, store){+ cb(null, store);+ });+ }+ },++ _loadLocal: function(lngs, options, cb) {+ var store = {}+ , nowMS = new Date().getTime();++ if(window.localStorage) {++ var todo = lngs.length;++ f.each(lngs, function(key, lng) {+ var local = window.localStorage.getItem('res_' + lng);++ if (local) {+ local = JSON.parse(local);++ if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {+ store[lng] = local;+ }+ }++ todo--; // wait for all done befor callback+ if (todo === 0) cb(null, store);+ });+ }+ },++ _storeLocal: function(store) {+ if(window.localStorage) {+ for (var m in store) {+ store[m].i18nStamp = new Date().getTime();+ f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));+ }+ }+ return;+ },++ _fetch: function(lngs, options, cb) {+ var ns = options.ns+ , store = {};++ if (!options.dynamicLoad) {+ var todo = ns.namespaces.length * lngs.length+ , errors;++ // load each file individual+ f.each(ns.namespaces, function(nsIndex, nsValue) {+ f.each(lngs, function(lngIndex, lngValue) {++ // Call this once our translation has returned.+ var loadComplete = function(err, data) {+ if (err) {+ errors = errors || [];+ errors.push(err);+ }+ store[lngValue] = store[lngValue] || {};+ store[lngValue][nsValue] = data;++ todo--; // wait for all done befor callback+ if (todo === 0) cb(errors, store);+ };++ if(typeof options.customLoad == 'function'){+ // Use the specified custom callback.+ options.customLoad(lngValue, nsValue, options, loadComplete);+ } else {+ //~ // Use our inbuilt sync.+ sync._fetchOne(lngValue, nsValue, options, loadComplete);+ }+ });+ });+ } else {+ // Call this once our translation has returned.+ var loadComplete = function(err, data) {+ cb(null, data);+ };++ if(typeof options.customLoad == 'function'){+ // Use the specified custom callback.+ options.customLoad(lngs, ns.namespaces, options, loadComplete);+ } else {+ var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });+ // load all needed stuff once+ f.ajax({+ url: url,+ success: function(data, status, xhr) {+ f.log('loaded: ' + url);+ loadComplete(null, data);+ },+ error : function(xhr, status, error) {+ f.log('failed loading: ' + url);+ loadComplete('failed loading resource.json error: ' + error);+ },+ dataType: "json",+ async : options.getAsync+ });+ }+ }+ },++ _fetchOne: function(lng, ns, options, done) {+ var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });+ f.ajax({+ url: url,+ success: function(data, status, xhr) {+ f.log('loaded: ' + url);+ done(null, data);+ },+ error : function(xhr, status, error) {+ if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {+ // file loaded but invalid json, stop waste time !+ f.error('There is a typo in: ' + url);+ } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {+ f.log('Does not exist: ' + url);+ } else {+ var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);+ f.log(theStatus + ' when loading ' + url);+ }++ done(error, {});+ },+ dataType: "json",+ async : options.getAsync+ });+ },++ postMissing: function(lng, ns, key, defaultValue, lngs) {+ var payload = {};+ payload[key] = defaultValue;++ var urls = [];++ if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {+ for (var i = 0; i < o.fallbackLng.length; i++) {+ urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});+ }+ } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {+ urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});+ } else if (o.sendMissingTo === 'all') {+ for (var i = 0, l = lngs.length; i < l; i++) {+ urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});+ }+ }++ for (var y = 0, len = urls.length; y < len; y++) {+ var item = urls[y];+ f.ajax({+ url: item.url,+ type: o.sendType,+ data: payload,+ success: function(data, status, xhr) {+ f.log('posted missing key \'' + key + '\' to: ' + item.url);++ // add key to resStore+ var keys = key.split('.');+ var x = 0;+ var value = resStore[item.lng][ns];+ while (keys[x]) {+ if (x === keys.length - 1) {+ value = value[keys[x]] = defaultValue;+ } else {+ value = value[keys[x]] = value[keys[x]] || {};+ }+ x++;+ }+ },+ error : function(xhr, status, error) {+ f.log('failed posting missing key \'' + key + '\' to: ' + item.url);+ },+ dataType: "json",+ async : o.postAsync+ });+ }+ },++ reload: reload+ };+ // defaults+ var o = {+ lng: undefined,+ load: 'all',+ preload: [],+ lowerCaseLng: false,+ returnObjectTrees: false,+ fallbackLng: ['dev'],+ fallbackNS: [],+ detectLngQS: 'setLng',+ detectLngFromLocalStorage: false,+ ns: 'translation',+ fallbackOnNull: true,+ fallbackOnEmpty: false,+ fallbackToDefaultNS: false,+ nsseparator: ':',+ keyseparator: '.',+ selectorAttr: 'data-i18n',+ debug: false,++ resGetPath: 'locales/__lng__/__ns__.json',+ resPostPath: 'locales/add/__lng__/__ns__',++ getAsync: true,+ postAsync: true,++ resStore: undefined,+ useLocalStorage: false,+ localStorageExpirationTime: 7*24*60*60*1000,++ dynamicLoad: false,+ sendMissing: false,+ sendMissingTo: 'fallback', // current | all+ sendType: 'POST',++ interpolationPrefix: '__',+ interpolationSuffix: '__',+ defaultVariables: false,+ reusePrefix: '$t(',+ reuseSuffix: ')',+ pluralSuffix: '_plural',+ pluralNotFound: ['plural_not_found', Math.random()].join(''),+ contextNotFound: ['context_not_found', Math.random()].join(''),+ escapeInterpolation: false,+ indefiniteSuffix: '_indefinite',+ indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),++ setJqueryExt: true,+ defaultValueFromContent: true,+ useDataAttrOptions: false,+ cookieExpirationTime: undefined,+ useCookie: true,+ cookieName: 'i18next',+ cookieDomain: undefined,++ objectTreeKeyHandler: undefined,+ postProcess: undefined,+ parseMissingKey: undefined,+ missingKeyHandler: sync.postMissing,++ shortcutFunction: 'sprintf' // or: defaultValue+ };+ function _extend(target, source) {+ if (!source || typeof source === 'function') {+ return target;+ }++ for (var attr in source) { target[attr] = source[attr]; }+ return target;+ }++ function _deepExtend(target, source) {+ for (var prop in source)+ if (prop in target)+ _deepExtend(target[prop], source[prop]);+ else+ target[prop] = source[prop];+ return target;+ }++ function _each(object, callback, args) {+ var name, i = 0,+ length = object.length,+ isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";++ if (args) {+ if (isObj) {+ for (name in object) {+ if (callback.apply(object[name], args) === false) {+ break;+ }+ }+ } else {+ for ( ; i < length; ) {+ if (callback.apply(object[i++], args) === false) {+ break;+ }+ }+ }++ // A special, fast, case for the most common use of each+ } else {+ if (isObj) {+ for (name in object) {+ if (callback.call(object[name], name, object[name]) === false) {+ break;+ }+ }+ } else {+ for ( ; i < length; ) {+ if (callback.call(object[i], i, object[i++]) === false) {+ break;+ }+ }+ }+ }++ return object;+ }++ var _entityMap = {+ "&": "&",+ "<": "<",+ ">": ">",+ '"': '"',+ "'": ''',+ "/": '/'+ };++ function _escape(data) {+ if (typeof data === 'string') {+ return data.replace(/[&<>"'\/]/g, function (s) {+ return _entityMap[s];+ });+ }else{+ return data;+ }+ }++ function _ajax(options) {++ // v0.5.0 of https://github.com/goloroden/http.js+ var getXhr = function (callback) {+ // Use the native XHR object if the browser supports it.+ if (window.XMLHttpRequest) {+ return callback(null, new XMLHttpRequest());+ } else if (window.ActiveXObject) {+ // In Internet Explorer check for ActiveX versions of the XHR object.+ try {+ return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));+ } catch (e) {+ return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));+ }+ }++ // If no XHR support was found, throw an error.+ return callback(new Error());+ };++ var encodeUsingUrlEncoding = function (data) {+ if(typeof data === 'string') {+ return data;+ }++ var result = [];+ for(var dataItem in data) {+ if(data.hasOwnProperty(dataItem)) {+ result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));+ }+ }++ return result.join('&');+ };++ var utf8 = function (text) {+ text = text.replace(/\r\n/g, '\n');+ var result = '';++ for(var i = 0; i < text.length; i++) {+ var c = text.charCodeAt(i);++ if(c < 128) {+ result += String.fromCharCode(c);+ } else if((c > 127) && (c < 2048)) {+ result += String.fromCharCode((c >> 6) | 192);+ result += String.fromCharCode((c & 63) | 128);+ } else {+ result += String.fromCharCode((c >> 12) | 224);+ result += String.fromCharCode(((c >> 6) & 63) | 128);+ result += String.fromCharCode((c & 63) | 128);+ }+ }++ return result;+ };++ var base64 = function (text) {+ var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';++ text = utf8(text);+ var result = '',+ chr1, chr2, chr3,+ enc1, enc2, enc3, enc4,+ i = 0;++ do {+ chr1 = text.charCodeAt(i++);+ chr2 = text.charCodeAt(i++);+ chr3 = text.charCodeAt(i++);++ enc1 = chr1 >> 2;+ enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);+ enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);+ enc4 = chr3 & 63;++ if(isNaN(chr2)) {+ enc3 = enc4 = 64;+ } else if(isNaN(chr3)) {+ enc4 = 64;+ }++ result +=+ keyStr.charAt(enc1) ++ keyStr.charAt(enc2) ++ keyStr.charAt(enc3) ++ keyStr.charAt(enc4);+ chr1 = chr2 = chr3 = '';+ enc1 = enc2 = enc3 = enc4 = '';+ } while(i < text.length);++ return result;+ };++ var mergeHeaders = function () {+ // Use the first header object as base.+ var result = arguments[0];++ // Iterate through the remaining header objects and add them.+ for(var i = 1; i < arguments.length; i++) {+ var currentHeaders = arguments[i];+ for(var header in currentHeaders) {+ if(currentHeaders.hasOwnProperty(header)) {+ result[header] = currentHeaders[header];+ }+ }+ }++ // Return the merged headers.+ return result;+ };++ var ajax = function (method, url, options, callback) {+ // Adjust parameters.+ if(typeof options === 'function') {+ callback = options;+ options = {};+ }++ // Set default parameter values.+ options.cache = options.cache || false;+ options.data = options.data || {};+ options.headers = options.headers || {};+ options.jsonp = options.jsonp || false;+ options.async = options.async === undefined ? true : options.async;++ // Merge the various header objects.+ var headers = mergeHeaders({+ 'accept': '*/*',+ 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'+ }, ajax.headers, options.headers);++ // Encode the data according to the content-type.+ var payload;+ if (headers['content-type'] === 'application/json') {+ payload = JSON.stringify(options.data);+ } else {+ payload = encodeUsingUrlEncoding(options.data);+ }++ // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call+ // if neccessary.+ if(method === 'GET') {+ // Setup the query string.+ var queryString = [];+ if(payload) {+ queryString.push(payload);+ payload = null;+ }++ // Handle caching.+ if(!options.cache) {+ queryString.push('_=' + (new Date()).getTime());+ }++ // If neccessary prepare the query string for a JSONP call.+ if(options.jsonp) {+ queryString.push('callback=' + options.jsonp);+ queryString.push('jsonp=' + options.jsonp);+ }++ // Merge the query string and attach it to the url.+ queryString = queryString.join('&');+ if (queryString.length > 1) {+ if (url.indexOf('?') > -1) {+ url += '&' + queryString;+ } else {+ url += '?' + queryString;+ }+ }++ // Make a JSONP call if neccessary.+ if(options.jsonp) {+ var head = document.getElementsByTagName('head')[0];+ var script = document.createElement('script');+ script.type = 'text/javascript';+ script.src = url;+ head.appendChild(script);+ return;+ }+ }++ // Since we got here, it is no JSONP request, so make a normal XHR request.+ getXhr(function (err, xhr) {+ if(err) return callback(err);++ // Open the request.+ xhr.open(method, url, options.async);++ // Set the request headers.+ for(var header in headers) {+ if(headers.hasOwnProperty(header)) {+ xhr.setRequestHeader(header, headers[header]);+ }+ }++ // Handle the request events.+ xhr.onreadystatechange = function () {+ if(xhr.readyState === 4) {+ var data = xhr.responseText || '';++ // If no callback is given, return.+ if(!callback) {+ return;+ }++ // Return an object that provides access to the data as text and JSON.+ callback(xhr.status, {+ text: function () {+ return data;+ },++ json: function () {+ try {+ return JSON.parse(data)+ } catch (e) {+ f.error('Can not parse JSON. URL: ' + url);+ return {};+ }+ }+ });+ }+ };++ // Actually send the XHR request.+ xhr.send(payload);+ });+ };++ // Define the external interface.+ var http = {+ authBasic: function (username, password) {+ ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);+ },++ connect: function (url, options, callback) {+ return ajax('CONNECT', url, options, callback);+ },++ del: function (url, options, callback) {+ return ajax('DELETE', url, options, callback);+ },++ get: function (url, options, callback) {+ return ajax('GET', url, options, callback);+ },++ head: function (url, options, callback) {+ return ajax('HEAD', url, options, callback);+ },++ headers: function (headers) {+ ajax.headers = headers || {};+ },++ isAllowed: function (url, verb, callback) {+ this.options(url, function (status, data) {+ callback(data.text().indexOf(verb) !== -1);+ });+ },++ options: function (url, options, callback) {+ return ajax('OPTIONS', url, options, callback);+ },++ patch: function (url, options, callback) {+ return ajax('PATCH', url, options, callback);+ },++ post: function (url, options, callback) {+ return ajax('POST', url, options, callback);+ },++ put: function (url, options, callback) {+ return ajax('PUT', url, options, callback);+ },++ trace: function (url, options, callback) {+ return ajax('TRACE', url, options, callback);+ }+ };+++ var methode = options.type ? options.type.toLowerCase() : 'get';++ http[methode](options.url, options, function (status, data) {+ // file: protocol always gives status code 0, so check for data+ if (status === 200 || (status === 0 && data.text())) {+ options.success(data.json(), status, null);+ } else {+ options.error(data.text(), status, null);+ }+ });+ }++ var _cookie = {+ create: function(name,value,minutes,domain) {+ var expires;+ if (minutes) {+ var date = new Date();+ date.setTime(date.getTime()+(minutes*60*1000));+ expires = "; expires="+date.toGMTString();+ }+ else expires = "";+ domain = (domain)? "domain="+domain+";" : "";+ document.cookie = name+"="+value+expires+";"+domain+"path=/";+ },++ read: function(name) {+ var nameEQ = name + "=";+ var ca = document.cookie.split(';');+ for(var i=0;i < ca.length;i++) {+ var c = ca[i];+ while (c.charAt(0)==' ') c = c.substring(1,c.length);+ if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);+ }+ return null;+ },++ remove: function(name) {+ this.create(name,"",-1);+ }+ };++ var cookie_noop = {+ create: function(name,value,minutes,domain) {},+ read: function(name) { return null; },+ remove: function(name) {}+ };++++ // move dependent functions to a container so that+ // they can be overriden easier in no jquery environment (node.js)+ var f = {+ extend: $ ? $.extend : _extend,+ deepExtend: _deepExtend,+ each: $ ? $.each : _each,+ ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),+ cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,+ detectLanguage: detectLanguage,+ escape: _escape,+ log: function(str) {+ if (o.debug && typeof console !== "undefined") console.log(str);+ },+ error: function(str) {+ if (typeof console !== "undefined") console.error(str);+ },+ getCountyIndexOfLng: function(lng) {+ var lng_index = 0;+ if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;+ return lng_index;+ },+ toLanguages: function(lng) {+ var log = this.log;++ function applyCase(l) {+ var ret = l;++ if (typeof l === 'string' && l.indexOf('-') > -1) {+ var parts = l.split('-');++ ret = o.lowerCaseLng ?+ parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :+ parts[0].toLowerCase() + '-' + parts[1].toUpperCase();+ } else {+ ret = o.lowerCaseLng ? l.toLowerCase() : l;+ }++ return ret;+ }++ var languages = [];+ var whitelist = o.lngWhitelist || false;+ var addLanguage = function(language){+ //reject langs not whitelisted+ if(!whitelist || whitelist.indexOf(language) > -1){+ languages.push(language);+ }else{+ log('rejecting non-whitelisted language: ' + language);+ }+ };+ if (typeof lng === 'string' && lng.indexOf('-') > -1) {+ var parts = lng.split('-');++ if (o.load !== 'unspecific') addLanguage(applyCase(lng));+ if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));+ } else {+ addLanguage(applyCase(lng));+ }++ for (var i = 0; i < o.fallbackLng.length; i++) {+ if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));+ }+ return languages;+ },+ regexEscape: function(str) {+ return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");+ },+ regexReplacementEscape: function(strOrFn) {+ if (typeof strOrFn === 'string') {+ return strOrFn.replace(/\$/g, "$$$$");+ } else {+ return strOrFn;+ }+ },+ localStorage: {+ setItem: function(key, value) {+ if (window.localStorage) {+ try {+ window.localStorage.setItem(key, value);+ } catch (e) {+ f.log('failed to set value for key "' + key + '" to localStorage.');+ }+ }+ }+ }+ };+ function init(options, cb) {++ if (typeof options === 'function') {+ cb = options;+ options = {};+ }+ options = options || {};++ // override defaults with passed in options+ f.extend(o, options);+ delete o.fixLng; /* passed in each time */++ // override functions: .log(), .detectLanguage(), etc+ if (o.functions) {+ delete o.functions;+ f.extend(f, options.functions);+ }++ // create namespace object if namespace is passed in as string+ if (typeof o.ns == 'string') {+ o.ns = { namespaces: [o.ns], defaultNs: o.ns};+ }++ // fallback namespaces+ if (typeof o.fallbackNS == 'string') {+ o.fallbackNS = [o.fallbackNS];+ }++ // fallback languages+ if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {+ o.fallbackLng = [o.fallbackLng];+ }++ // escape prefix/suffix+ o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);+ o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);++ if (!o.lng) o.lng = f.detectLanguage();++ languages = f.toLanguages(o.lng);+ currentLng = languages[0];+ f.log('currentLng set to: ' + currentLng);++ if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid+ f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);+ }+ if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {+ f.localStorage.setItem('i18next_lng', currentLng);+ }++ var lngTranslate = translate;+ if (options.fixLng) {+ lngTranslate = function(key, options) {+ options = options || {};+ options.lng = options.lng || lngTranslate.lng;+ return translate(key, options);+ };+ lngTranslate.lng = currentLng;+ }++ pluralExtensions.setCurrentLng(currentLng);++ // add JQuery extensions+ if ($ && o.setJqueryExt) addJqueryFunct();++ // jQuery deferred+ var deferred;+ if ($ && $.Deferred) {+ deferred = $.Deferred();+ }++ // return immidiatly if res are passed in+ if (o.resStore) {+ resStore = o.resStore;+ initialized = true;+ if (cb) cb(lngTranslate);+ if (deferred) deferred.resolve(lngTranslate);+ if (deferred) return deferred.promise();+ return;+ }++ // languages to load+ var lngsToLoad = f.toLanguages(o.lng);+ if (typeof o.preload === 'string') o.preload = [o.preload];+ for (var i = 0, l = o.preload.length; i < l; i++) {+ var pres = f.toLanguages(o.preload[i]);+ for (var y = 0, len = pres.length; y < len; y++) {+ if (lngsToLoad.indexOf(pres[y]) < 0) {+ lngsToLoad.push(pres[y]);+ }+ }+ }++ // else load them+ i18n.sync.load(lngsToLoad, o, function(err, store) {+ resStore = store;+ initialized = true;++ if (cb) cb(lngTranslate);+ if (deferred) deferred.resolve(lngTranslate);+ });++ if (deferred) return deferred.promise();}- }-- this.err = 0; // error code, if happens (0 = Z_OK)- this.msg = ''; // error message- this.ended = false; // used to avoid multiple onEnd() calls- this.chunks = []; // chunks of compressed data-- this.strm = new zstream();- this.strm.avail_out = 0;-- var status = zlib_inflate.inflateInit2(- this.strm,- opt.windowBits- );-- if (status !== c.Z_OK) {- throw new Error(msg[status]);- }-- this.header = new gzheader();-- zlib_inflate.inflateGetHeader(this.strm, this.header);-};--/**- * Inflate#push(data[, mode]) -> Boolean- * - data (Uint8Array|Array|ArrayBuffer|String): input data- * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.- * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.- *- * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with- * new output chunks. Returns `true` on success. The last data block must have- * mode Z_FINISH (or `true`). That flush internal pending buffers and call- * [[Inflate#onEnd]].- *- * On fail call [[Inflate#onEnd]] with error code and return false.- *- * We strongly recommend to use `Uint8Array` on input for best speed (output- * format is detected automatically). Also, don't skip last param and always- * use the same type in your code (boolean or number). That will improve JS speed.- *- * For regular `Array`-s make sure all elements are [0..255].- *- * ##### Example- *- * ```javascript- * push(chunk, false); // push one of data chunks- * ...- * push(chunk, true); // push last chunk- * ```- **/-Inflate.prototype.push = function(data, mode) {- var strm = this.strm;- var chunkSize = this.options.chunkSize;- var status, _mode;- var next_out_utf8, tail, utf8str;-- if (this.ended) { return false; }- _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);-- // Convert data if needed- if (typeof data === 'string') {- // Only binary strings can be decompressed on practice- strm.input = strings.binstring2buf(data);- } else if (toString.call(data) === '[object ArrayBuffer]') {- strm.input = new Uint8Array(data);- } else {- strm.input = data;- }-- strm.next_in = 0;- strm.avail_in = strm.input.length;-- do {- if (strm.avail_out === 0) {- strm.output = new utils.Buf8(chunkSize);- strm.next_out = 0;- strm.avail_out = chunkSize;+ function preload(lngs, cb) {+ if (typeof lngs === 'string') lngs = [lngs];+ for (var i = 0, l = lngs.length; i < l; i++) {+ if (o.preload.indexOf(lngs[i]) < 0) {+ o.preload.push(lngs[i]);+ }+ }+ return init(cb);+ }++ function addResourceBundle(lng, ns, resources, deep) {+ if (typeof ns !== 'string') {+ resources = ns;+ ns = o.ns.defaultNs;+ } else if (o.ns.namespaces.indexOf(ns) < 0) {+ o.ns.namespaces.push(ns);+ }++ resStore[lng] = resStore[lng] || {};+ resStore[lng][ns] = resStore[lng][ns] || {};++ if (deep) {+ f.deepExtend(resStore[lng][ns], resources);+ } else {+ f.extend(resStore[lng][ns], resources);+ }+ }++ function hasResourceBundle(lng, ns) {+ if (typeof ns !== 'string') {+ ns = o.ns.defaultNs;+ }++ resStore[lng] = resStore[lng] || {};+ var res = resStore[lng][ns] || {};++ var hasValues = false;+ for(var prop in res) {+ if (res.hasOwnProperty(prop)) {+ hasValues = true;+ }+ }++ return hasValues;+ }++ function removeResourceBundle(lng, ns) {+ if (typeof ns !== 'string') {+ ns = o.ns.defaultNs;+ }++ resStore[lng] = resStore[lng] || {};+ resStore[lng][ns] = {};}-- status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */-- if (status !== c.Z_STREAM_END && status !== c.Z_OK) {- this.onEnd(status);- this.ended = true;- return false;++ function addResource(lng, ns, key, value) {+ if (typeof ns !== 'string') {+ resource = ns;+ ns = o.ns.defaultNs;+ } else if (o.ns.namespaces.indexOf(ns) < 0) {+ o.ns.namespaces.push(ns);+ }++ resStore[lng] = resStore[lng] || {};+ resStore[lng][ns] = resStore[lng][ns] || {};++ var keys = key.split(o.keyseparator);+ var x = 0;+ var node = resStore[lng][ns];+ var origRef = node;++ while (keys[x]) {+ if (x == keys.length - 1)+ node[keys[x]] = value;+ else {+ if (node[keys[x]] == null)+ node[keys[x]] = {};++ node = node[keys[x]];+ }+ x++;+ }}-- if (strm.next_out) {- if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && _mode === c.Z_FINISH)) {-- if (this.options.to === 'string') {-- next_out_utf8 = strings.utf8border(strm.output, strm.next_out);-- tail = strm.next_out - next_out_utf8;- utf8str = strings.buf2string(strm.output, next_out_utf8);-- // move tail- strm.next_out = tail;- strm.avail_out = chunkSize - tail;- if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }-- this.onData(utf8str);-- } else {- this.onData(utils.shrinkBuf(strm.output, strm.next_out));++ function addResources(lng, ns, resources) {+ if (typeof ns !== 'string') {+ resource = ns;+ ns = o.ns.defaultNs;+ } else if (o.ns.namespaces.indexOf(ns) < 0) {+ o.ns.namespaces.push(ns);+ }++ for (var m in resources) {+ if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);}- }}- } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);-- if (status === c.Z_STREAM_END) {- _mode = c.Z_FINISH;- }- // Finalize on the last chunk.- if (_mode === c.Z_FINISH) {- status = zlib_inflate.inflateEnd(this.strm);- this.onEnd(status);- this.ended = true;- return status === c.Z_OK;- }-- return true;-};---/**- * Inflate#onData(chunk) -> Void- * - chunk (Uint8Array|Array|String): ouput data. Type of array depends- * on js engine support. When string output requested, each chunk- * will be string.- *- * By default, stores data blocks in `chunks[]` property and glue- * those in `onEnd`. Override this handler, if you need another behaviour.- **/-Inflate.prototype.onData = function(chunk) {- this.chunks.push(chunk);-};---/**- * Inflate#onEnd(status) -> Void- * - status (Number): inflate status. 0 (Z_OK) on success,- * other if not.- *- * Called once after you tell inflate that input stream complete- * or error happenned. By default - join collected chunks,- * free memory and fill `results` / `err` properties.- **/-Inflate.prototype.onEnd = function(status) {- // On success - join- if (status === c.Z_OK) {- if (this.options.to === 'string') {- // Glue & convert here, until we teach pako to send- // utf8 alligned strings to onData- this.result = this.chunks.join('');- } else {- this.result = utils.flattenChunks(this.chunks);++ function setDefaultNamespace(ns) {+ o.ns.defaultNs = ns;}- }- this.chunks = [];- this.err = status;- this.msg = this.strm.msg;-};---/**- * inflate(data[, options]) -> Uint8Array|Array|String- * - data (Uint8Array|Array|String): input data to decompress.- * - options (Object): zlib inflate options.- *- * Decompress `data` with inflate/ungzip and `options`. Autodetect- * format via wrapper header by default. That's why we don't provide- * separate `ungzip` method.- *- * Supported options are:- *- * - windowBits- *- * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)- * for more information.- *- * Sugar (options):- *- * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify- * negative windowBits implicitly.- * - `to` (String) - if equal to 'string', then result will be converted- * from utf8 to utf16 (javascript) string. When string output requested,- * chunk length can differ from `chunkSize`, depending on content.- *- *- * ##### Example:- *- * ```javascript- * var pako = require('pako')- * , input = pako.deflate([1,2,3,4,5,6,7,8,9])- * , output;- *- * try {- * output = pako.inflate(input);- * } catch (err)- * console.log(err);- * }- * ```- **/-function inflate(input, options) {- var inflator = new Inflate(options);-- inflator.push(input, true);-- // That will never happens, if you don't cheat with options :)- if (inflator.err) { throw inflator.msg; }-- return inflator.result;-}---/**- * inflateRaw(data[, options]) -> Uint8Array|Array|String- * - data (Uint8Array|Array|String): input data to decompress.- * - options (Object): zlib inflate options.- *- * The same as [[inflate]], but creates raw data, without wrapper- * (header and adler32 crc).- **/-function inflateRaw(input, options) {- options = options || {};- options.raw = true;- return inflate(input, options);-}---/**- * ungzip(data[, options]) -> Uint8Array|Array|String- * - data (Uint8Array|Array|String): input data to decompress.- * - options (Object): zlib inflate options.- *- * Just shortcut to [[inflate]], because it autodetects format- * by header.content. Done for convenience.- **/---exports.Inflate = Inflate;-exports.inflate = inflate;-exports.inflateRaw = inflateRaw;-exports.ungzip = inflate;--},{"./utils/common":69,"./utils/strings":70,"./zlib/constants":72,"./zlib/gzheader":75,"./zlib/inflate.js":77,"./zlib/messages":79,"./zlib/zstream":81}],69:[function(require,module,exports){-'use strict';---var TYPED_OK = (typeof Uint8Array !== 'undefined') &&- (typeof Uint16Array !== 'undefined') &&- (typeof Int32Array !== 'undefined');---exports.assign = function (obj /*from1, from2, from3, ...*/) {- var sources = Array.prototype.slice.call(arguments, 1);- while (sources.length) {- var source = sources.shift();- if (!source) { continue; }-- if (typeof(source) !== 'object') {- throw new TypeError(source + 'must be non-object');++ function loadNamespace(namespace, cb) {+ loadNamespaces([namespace], cb);+ }++ function loadNamespaces(namespaces, cb) {+ var opts = {+ dynamicLoad: o.dynamicLoad,+ resGetPath: o.resGetPath,+ getAsync: o.getAsync,+ customLoad: o.customLoad,+ ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */+ };++ // languages to load+ var lngsToLoad = f.toLanguages(o.lng);+ if (typeof o.preload === 'string') o.preload = [o.preload];+ for (var i = 0, l = o.preload.length; i < l; i++) {+ var pres = f.toLanguages(o.preload[i]);+ for (var y = 0, len = pres.length; y < len; y++) {+ if (lngsToLoad.indexOf(pres[y]) < 0) {+ lngsToLoad.push(pres[y]);+ }+ }+ }++ // check if we have to load+ var lngNeedLoad = [];+ for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {+ var needLoad = false;+ var resSet = resStore[lngsToLoad[a]];+ if (resSet) {+ for (var b = 0, lenB = namespaces.length; b < lenB; b++) {+ if (!resSet[namespaces[b]]) needLoad = true;+ }+ } else {+ needLoad = true;+ }++ if (needLoad) lngNeedLoad.push(lngsToLoad[a]);+ }++ if (lngNeedLoad.length) {+ i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {+ var todo = namespaces.length * lngNeedLoad.length;++ // load each file individual+ f.each(namespaces, function(nsIndex, nsValue) {++ // append namespace to namespace array+ if (o.ns.namespaces.indexOf(nsValue) < 0) {+ o.ns.namespaces.push(nsValue);+ }++ f.each(lngNeedLoad, function(lngIndex, lngValue) {+ resStore[lngValue] = resStore[lngValue] || {};+ resStore[lngValue][nsValue] = store[lngValue][nsValue];++ todo--; // wait for all done befor callback+ if (todo === 0 && cb) {+ if (o.useLocalStorage) i18n.sync._storeLocal(resStore);+ cb();+ }+ });+ });+ });+ } else {+ if (cb) cb();+ }}-- for (var p in source) {- if (source.hasOwnProperty(p)) {- obj[p] = source[p];- }++ function setLng(lng, options, cb) {+ if (typeof options === 'function') {+ cb = options;+ options = {};+ } else if (!options) {+ options = {};+ }++ options.lng = lng;+ return init(options, cb);}- }-- return obj;-};---// reduce buffer size, avoiding mem copy-exports.shrinkBuf = function (buf, size) {- if (buf.length === size) { return buf; }- if (buf.subarray) { return buf.subarray(0, size); }- buf.length = size;- return buf;-};---var fnTyped = {- arraySet: function (dest, src, src_offs, len, dest_offs) {- if (src.subarray && dest.subarray) {- dest.set(src.subarray(src_offs, src_offs+len), dest_offs);- return;++ function lng() {+ return currentLng;}- // Fallback to ordinary array- for(var i=0; i<len; i++) {- dest[dest_offs + i] = src[src_offs + i];++ function reload(cb) {+ resStore = {};+ setLng(currentLng, cb);}- },- // Join array of chunks to single array.- flattenChunks: function(chunks) {- var i, l, len, pos, chunk, result;-- // calculate data length- len = 0;- for (i=0, l=chunks.length; i<l; i++) {- len += chunks[i].length;+ function addJqueryFunct() {+ // $.t shortcut+ $.t = $.t || translate;++ function parse(ele, key, options) {+ if (key.length === 0) return;++ var attr = 'text';++ if (key.indexOf('[') === 0) {+ var parts = key.split(']');+ key = parts[1];+ attr = parts[0].substr(1, parts[0].length-1);+ }++ if (key.indexOf(';') === key.length-1) {+ key = key.substr(0, key.length-2);+ }++ var optionsToUse;+ if (attr === 'html') {+ optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;+ ele.html($.t(key, optionsToUse));+ } else if (attr === 'text') {+ optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;+ ele.text($.t(key, optionsToUse));+ } else if (attr === 'prepend') {+ optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;+ ele.prepend($.t(key, optionsToUse));+ } else if (attr === 'append') {+ optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;+ ele.append($.t(key, optionsToUse));+ } else if (attr.indexOf("data-") === 0) {+ var dataAttr = attr.substr(("data-").length);+ optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;+ var translated = $.t(key, optionsToUse);+ //we change into the data cache+ ele.data(dataAttr, translated);+ //we change into the dom+ ele.attr(attr, translated);+ } else {+ optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;+ ele.attr(attr, $.t(key, optionsToUse));+ }+ }++ function localize(ele, options) {+ var key = ele.attr(o.selectorAttr);+ if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();+ if (!key) return;++ var target = ele+ , targetSelector = ele.data("i18n-target");+ if (targetSelector) {+ target = ele.find(targetSelector) || ele;+ }++ if (!options && o.useDataAttrOptions === true) {+ options = ele.data("i18n-options");+ }+ options = options || {};++ if (key.indexOf(';') >= 0) {+ var keys = key.split(';');++ $.each(keys, function(m, k) {+ if (k !== '') parse(target, k, options);+ });++ } else {+ parse(target, key, options);+ }++ if (o.useDataAttrOptions === true) ele.data("i18n-options", options);+ }++ // fn+ $.fn.i18n = function (options) {+ return this.each(function() {+ // localize element itself+ localize($(this), options);++ // localize childs+ var elements = $(this).find('[' + o.selectorAttr + ']');+ elements.each(function() {+ localize($(this), options);+ });+ });+ };}-- // join chunks- result = new Uint8Array(len);- pos = 0;- for (i=0, l=chunks.length; i<l; i++) {- chunk = chunks[i];- result.set(chunk, pos);- pos += chunk.length;+ function applyReplacement(str, replacementHash, nestedKey, options) {+ if (!str) return str;++ options = options || replacementHash; // first call uses replacement hash combined with options+ if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;++ var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped+ , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped+ , unEscapingSuffix = 'HTML'+suffix;++ var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;+ f.each(hash, function(key, value) {+ var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;+ if (typeof value === 'object' && value !== null) {+ str = applyReplacement(str, value, nextKey, options);+ } else {+ if (options.escapeInterpolation || o.escapeInterpolation) {+ str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));+ str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));+ } else {+ str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));+ }+ // str = options.escapeInterpolation;+ }+ });+ return str;+ }++ // append it to functions+ f.applyReplacement = applyReplacement;++ function applyReuse(translated, options) {+ var comma = ',';+ var options_open = '{';+ var options_close = '}';++ var opts = f.extend({}, options);+ delete opts.postProcess;++ while (translated.indexOf(o.reusePrefix) != -1) {+ replacementCounter++;+ if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion+ var index_of_opening = translated.lastIndexOf(o.reusePrefix);+ var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;+ var token = translated.substring(index_of_opening, index_of_end_of_closing);+ var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');++ if (index_of_end_of_closing <= index_of_opening) {+ f.error('there is an missing closing in following translation value', translated);+ return '';+ }++ if (token_without_symbols.indexOf(comma) != -1) {+ var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);+ if (token_without_symbols.indexOf(options_open, index_of_token_end_of_closing) != -1 && token_without_symbols.indexOf(options_close, index_of_token_end_of_closing) != -1) {+ var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);+ var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;+ try {+ opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));+ token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);+ } catch (e) {+ }+ }+ }++ var translated_token = _translate(token_without_symbols, opts);+ translated = translated.replace(token, f.regexReplacementEscape(translated_token));+ }+ return translated;}-- return result;- }-};--var fnUntyped = {- arraySet: function (dest, src, src_offs, len, dest_offs) {- for(var i=0; i<len; i++) {- dest[dest_offs + i] = src[src_offs + i];++ function hasContext(options) {+ return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));}- },- // Join array of chunks to single array.- flattenChunks: function(chunks) {- return [].concat.apply([], chunks);- }-};---// Enable/Disable typed arrays use, for testing-//-exports.setTyped = function (on) {- if (on) {- exports.Buf8 = Uint8Array;- exports.Buf16 = Uint16Array;- exports.Buf32 = Int32Array;- exports.assign(exports, fnTyped);- } else {- exports.Buf8 = Array;- exports.Buf16 = Array;- exports.Buf32 = Array;- exports.assign(exports, fnUntyped);- }-};--exports.setTyped(TYPED_OK);-},{}],70:[function(require,module,exports){-// String encode/decode helpers-'use strict';---var utils = require('./common');---// Quick check if we can use fast array to bin string conversion-//-// - apply(Array) can fail on Android 2.2-// - apply(Uint8Array) can fail on iOS 5.1 Safary-//-var STR_APPLY_OK = true;-var STR_APPLY_UIA_OK = true;--try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }-try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }---// Table with utf8 lengths (calculated by first byte of sequence)-// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,-// because max possible codepoint is 0x10ffff-var _utf8len = new utils.Buf8(256);-for (var i=0; i<256; i++) {- _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);-}-_utf8len[254]=_utf8len[254]=1; // Invalid sequence start---// convert string to array (typed, when possible)-exports.string2buf = function (str) {- var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;-- // count binary size- for (m_pos = 0; m_pos < str_len; m_pos++) {- c = str.charCodeAt(m_pos);- if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {- c2 = str.charCodeAt(m_pos+1);- if ((c2 & 0xfc00) === 0xdc00) {- c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);- m_pos++;- }++ function needsPlural(options, lng) {+ return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);}- buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;- }-- // allocate buffer- buf = new utils.Buf8(buf_len);-- // convert- for (i=0, m_pos = 0; i < buf_len; m_pos++) {- c = str.charCodeAt(m_pos);- if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {- c2 = str.charCodeAt(m_pos+1);- if ((c2 & 0xfc00) === 0xdc00) {- c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);- m_pos++;- }++ function needsIndefiniteArticle(options) {+ return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);}- if (c < 0x80) {- /* one byte */- buf[i++] = c;- } else if (c < 0x800) {- /* two bytes */- buf[i++] = 0xC0 | (c >>> 6);- buf[i++] = 0x80 | (c & 0x3f);- } else if (c < 0x10000) {- /* three bytes */- buf[i++] = 0xE0 | (c >>> 12);- buf[i++] = 0x80 | (c >>> 6 & 0x3f);- buf[i++] = 0x80 | (c & 0x3f);- } else {- /* four bytes */- buf[i++] = 0xf0 | (c >>> 18);- buf[i++] = 0x80 | (c >>> 12 & 0x3f);- buf[i++] = 0x80 | (c >>> 6 & 0x3f);- buf[i++] = 0x80 | (c & 0x3f);++ function exists(key, options) {+ options = options || {};++ var notFound = _getDefaultValue(key, options)+ , found = _find(key, options);++ return found !== undefined || found === notFound;}- }-- return buf;-};--// Helper (used in 2 places)-function buf2binstring(buf, len) {- // use fallback for big arrays to avoid stack overflow- if (len < 65537) {- if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {- return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));++ function translate(key, options) {+ options = options || {};++ if (!initialized) {+ f.log('i18next not finished initialization. you might have called t function before loading resources finished.')+ return options.defaultValue || '';+ };+ replacementCounter = 0;+ return _translate.apply(null, arguments);}- }-- var result = '';- for(var i=0; i < len; i++) {- result += String.fromCharCode(buf[i]);- }- return result;-}---// Convert byte array to binary string-exports.buf2binstring = function(buf) {- return buf2binstring(buf, buf.length);-};---// Convert binary string (typed, when possible)-exports.binstring2buf = function(str) {- var buf = new utils.Buf8(str.length);- for(var i=0, len=buf.length; i < len; i++) {- buf[i] = str.charCodeAt(i);- }- return buf;-};---// convert array to string-exports.buf2string = function (buf, max) {- var i, out, c, c_len;- var len = max || buf.length;-- // Reserve max possible length (2 words per char)- // NB: by unknown reasons, Array is significantly faster for- // String.fromCharCode.apply than Uint16Array.- var utf16buf = new Array(len*2);-- for (out=0, i=0; i<len;) {- c = buf[i++];- // quick process ascii- if (c < 0x80) { utf16buf[out++] = c; continue; }-- c_len = _utf8len[c];- // skip 5 & 6 byte codes- if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }-- // apply mask on first byte- c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;- // join the rest- while (c_len > 1 && i < len) {- c = (c << 6) | (buf[i++] & 0x3f);- c_len--;++ function _getDefaultValue(key, options) {+ return (options.defaultValue !== undefined) ? options.defaultValue : key;+ }++ function _injectSprintfProcessor() {++ var values = [];++ // mh: build array from second argument onwards+ for (var i = 1; i < arguments.length; i++) {+ values.push(arguments[i]);+ }++ return {+ postProcess: 'sprintf',+ sprintf: values+ };+ }++ function _translate(potentialKeys, options) {+ if (options && typeof options !== 'object') {+ if (o.shortcutFunction === 'sprintf') {+ // mh: gettext like sprintf syntax found, automatically create sprintf processor+ options = _injectSprintfProcessor.apply(null, arguments);+ } else if (o.shortcutFunction === 'defaultValue') {+ options = {+ defaultValue: options+ }+ }+ } else {+ options = options || {};+ }++ if (typeof o.defaultVariables === 'object') {+ options = f.extend({}, o.defaultVariables, options);+ }++ if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';++ if (typeof potentialKeys === 'string') {+ potentialKeys = [potentialKeys];+ }++ var key = potentialKeys[0];++ if (potentialKeys.length > 1) {+ for (var i = 0; i < potentialKeys.length; i++) {+ key = potentialKeys[i];+ if (exists(key, options)) {+ break;+ }+ }+ }++ var notFound = _getDefaultValue(key, options)+ , found = _find(key, options)+ , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages+ , ns = options.ns || o.ns.defaultNs+ , parts;++ // split ns and key+ if (key.indexOf(o.nsseparator) > -1) {+ parts = key.split(o.nsseparator);+ ns = parts[0];+ key = parts[1];+ }++ if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {+ if (options.lng) {+ o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);+ } else {+ o.missingKeyHandler(o.lng, ns, key, notFound, lngs);+ }+ }++ var postProcessor = options.postProcess || o.postProcess;+ if (found !== undefined && postProcessor) {+ if (postProcessors[postProcessor]) {+ found = postProcessors[postProcessor](found, key, options);+ }+ }++ // process notFound if function exists+ var splitNotFound = notFound;+ if (notFound.indexOf(o.nsseparator) > -1) {+ parts = notFound.split(o.nsseparator);+ splitNotFound = parts[1];+ }+ if (splitNotFound === key && o.parseMissingKey) {+ notFound = o.parseMissingKey(notFound);+ }++ if (found === undefined) {+ notFound = applyReplacement(notFound, options);+ notFound = applyReuse(notFound, options);++ if (postProcessor && postProcessors[postProcessor]) {+ var val = _getDefaultValue(key, options);+ found = postProcessors[postProcessor](val, key, options);+ }+ }++ return (found !== undefined) ? found : notFound;}-- // terminated by end of string?- if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }-- if (c < 0x10000) {- utf16buf[out++] = c;- } else {- c -= 0x10000;- utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);- utf16buf[out++] = 0xdc00 | (c & 0x3ff);++ function _find(key, options) {+ options = options || {};++ var optionWithoutCount, translated+ , notFound = _getDefaultValue(key, options)+ , lngs = languages;++ if (!resStore) { return notFound; } // no resStore to translate from++ // CI mode+ if (lngs[0].toLowerCase() === 'cimode') return notFound;++ // passed in lng+ if (options.lngs) lngs = options.lngs;+ if (options.lng) {+ lngs = f.toLanguages(options.lng, options.fallbackLng);++ if (!resStore[lngs[0]]) {+ var oldAsync = o.getAsync;+ o.getAsync = false;++ i18n.sync.load(lngs, o, function(err, store) {+ f.extend(resStore, store);+ o.getAsync = oldAsync;+ });+ }+ }++ var ns = options.ns || o.ns.defaultNs;+ if (key.indexOf(o.nsseparator) > -1) {+ var parts = key.split(o.nsseparator);+ ns = parts[0];+ key = parts[1];+ }++ if (hasContext(options)) {+ optionWithoutCount = f.extend({}, options);+ delete optionWithoutCount.context;+ optionWithoutCount.defaultValue = o.contextNotFound;++ var contextKey = ns + o.nsseparator + key + '_' + options.context;++ translated = translate(contextKey, optionWithoutCount);+ if (translated != o.contextNotFound) {+ return applyReplacement(translated, { context: options.context }); // apply replacement for context only+ } // else continue translation with original/nonContext key+ }++ if (needsPlural(options, lngs[0])) {+ optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);+ delete optionWithoutCount.count;+ delete optionWithoutCount.lng;+ optionWithoutCount.defaultValue = o.pluralNotFound;++ var pluralKey;+ if (!pluralExtensions.needsPlural(lngs[0], options.count)) {+ pluralKey = ns + o.nsseparator + key;+ } else {+ pluralKey = ns + o.nsseparator + key + o.pluralSuffix;+ var pluralExtension = pluralExtensions.get(lngs[0], options.count);+ if (pluralExtension >= 0) {+ pluralKey = pluralKey + '_' + pluralExtension;+ } else if (pluralExtension === 1) {+ pluralKey = ns + o.nsseparator + key; // singular+ }+ }++ translated = translate(pluralKey, optionWithoutCount);++ if (translated != o.pluralNotFound) {+ return applyReplacement(translated, {+ count: options.count,+ interpolationPrefix: options.interpolationPrefix,+ interpolationSuffix: options.interpolationSuffix+ }); // apply replacement for count only+ } else if (lngs.length > 1) {+ // remove failed lng+ var clone = lngs.slice();+ clone.shift();+ options = f.extend(options, { lngs: clone });+ delete options.lng;+ // retry with fallbacks+ translated = translate(ns + o.nsseparator + key, options);+ if (translated != o.pluralNotFound) return translated;+ } else {+ return translated;+ }+ }++ if (needsIndefiniteArticle(options)) {+ var optionsWithoutIndef = f.extend({}, options);+ delete optionsWithoutIndef.indefinite_article;+ optionsWithoutIndef.defaultValue = o.indefiniteNotFound;+ // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false+ var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");+ translated = translate(indefiniteKey, optionsWithoutIndef);+ if (translated != o.indefiniteNotFound) {+ return translated;+ }+ }++ var found;+ var keys = key.split(o.keyseparator);+ for (var i = 0, len = lngs.length; i < len; i++ ) {+ if (found !== undefined) break;++ var l = lngs[i];++ var x = 0;+ var value = resStore[l] && resStore[l][ns];+ while (keys[x]) {+ value = value && value[keys[x]];+ x++;+ }+ if (value !== undefined) {+ var valueType = Object.prototype.toString.apply(value);+ if (typeof value === 'string') {+ value = applyReplacement(value, options);+ value = applyReuse(value, options);+ } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {+ value = value.join('\n');+ value = applyReplacement(value, options);+ value = applyReuse(value, options);+ } else if (value === null && o.fallbackOnNull === true) {+ value = undefined;+ } else if (value !== null) {+ if (!o.returnObjectTrees && !options.returnObjectTrees) {+ if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {+ value = o.objectTreeKeyHandler(key, value, l, ns, options);+ } else {+ value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' ++ 'returned an object instead of string.';+ f.log(value);+ }+ } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {+ var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy+ f.each(value, function(m) {+ copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);+ });+ value = copy;+ }+ }++ if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)+ value = undefined;++ found = value;+ }+ }++ if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {+ // set flag for fallback lookup - avoid recursion+ options.isFallbackLookup = true;++ if (o.fallbackNS.length) {++ for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {+ found = _find(o.fallbackNS[y] + o.nsseparator + key, options);++ if (found || (found==="" && o.fallbackOnEmpty === false)) {+ /* compare value without namespace */+ var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found+ , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;++ if (foundValue !== notFoundValue) break;+ }+ }+ } else {+ found = _find(key, options); // fallback to default NS+ }+ options.isFallbackLookup = false;+ }++ return found;+ }+ function detectLanguage() {+ var detectedLng;+ var whitelist = o.lngWhitelist || [];+ var userLngChoices = [];++ // get from qs+ var qsParm = [];+ if (typeof window !== 'undefined') {+ (function() {+ var query = window.location.search.substring(1);+ var params = query.split('&');+ for (var i=0; i<params.length; i++) {+ var pos = params[i].indexOf('=');+ if (pos > 0) {+ var key = params[i].substring(0,pos);+ if (key == o.detectLngQS) {+ userLngChoices.push(params[i].substring(pos+1));+ }+ }+ }+ })();+ }++ // get from cookie+ if (o.useCookie && typeof document !== 'undefined') {+ var c = f.cookie.read(o.cookieName);+ if (c) userLngChoices.push(c);+ }++ // get from localStorage+ if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {+ userLngChoices.push(window.localStorage.getItem('i18next_lng'));+ }++ // get from navigator+ if (typeof navigator !== 'undefined') {+ if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating+ for (var i=0;i<navigator.languages.length;i++) {+ userLngChoices.push(navigator.languages[i]);+ }+ }+ if (navigator.userLanguage) {+ userLngChoices.push(navigator.userLanguage);+ }+ if (navigator.language) {+ userLngChoices.push(navigator.language);+ }+ }++ (function() {+ for (var i=0;i<userLngChoices.length;i++) {+ var lng = userLngChoices[i];++ if (lng.indexOf('-') > -1) {+ var parts = lng.split('-');+ lng = o.lowerCaseLng ?+ parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :+ parts[0].toLowerCase() + '-' + parts[1].toUpperCase();+ }++ if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {+ detectedLng = lng;+ break;+ }+ }+ })();++ //fallback+ if (!detectedLng){+ detectedLng = o.fallbackLng[0];+ }++ return detectedLng;}- }-- return buf2binstring(utf16buf, out);-};---// Calculate max possible position in utf8 buffer,-// that will not break sequence. If that's not possible-// - (very small limits) return max size as is.-//-// buf[] - utf8 bytes array-// max - length limit (mandatory);-exports.utf8border = function(buf, max) {- var pos;-- max = max || buf.length;- if (max > buf.length) { max = buf.length; }-- // go back from last position, until start of sequence found- pos = max-1;- while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }-- // Fuckup - very small and broken sequence,- // return max, because we should return something anyway.- if (pos < 0) { return max; }-- // If we came to start of buffer - that means vuffer is too small,- // return max too.- if (pos === 0) { return max; }-- return (pos + _utf8len[buf[pos]] > max) ? pos : max;-};--},{"./common":69}],71:[function(require,module,exports){-'use strict';--// Note: adler32 takes 12% for level 0 and 2% for level 6.-// It doesn't worth to make additional optimizationa as in original.-// Small size is preferable.--function adler32(adler, buf, len, pos) {- var s1 = (adler & 0xffff) |0- , s2 = ((adler >>> 16) & 0xffff) |0- , n = 0;-- while (len !== 0) {- // Set limit ~ twice less than 5552, to keep- // s2 in 31-bits, because we force signed ints.- // in other case %= will fail.- n = len > 2000 ? 2000 : len;- len -= n;-- do {- s1 = (s1 + buf[pos++]) |0;- s2 = (s2 + s1) |0;- } while (--n);-- s1 %= 65521;- s2 %= 65521;- }-- return (s1 | (s2 << 16)) |0;-}---module.exports = adler32;-},{}],72:[function(require,module,exports){-module.exports = {-- /* Allowed flush values; see deflate() and inflate() below for details */- Z_NO_FLUSH: 0,- Z_PARTIAL_FLUSH: 1,- Z_SYNC_FLUSH: 2,- Z_FULL_FLUSH: 3,- Z_FINISH: 4,- Z_BLOCK: 5,- Z_TREES: 6,-- /* Return codes for the compression/decompression functions. Negative values- * are errors, positive values are used for special but normal events.- */- Z_OK: 0,- Z_STREAM_END: 1,- Z_NEED_DICT: 2,- Z_ERRNO: -1,- Z_STREAM_ERROR: -2,- Z_DATA_ERROR: -3,- //Z_MEM_ERROR: -4,- Z_BUF_ERROR: -5,- //Z_VERSION_ERROR: -6,-- /* compression levels */- Z_NO_COMPRESSION: 0,- Z_BEST_SPEED: 1,- Z_BEST_COMPRESSION: 9,- Z_DEFAULT_COMPRESSION: -1,--- Z_FILTERED: 1,- Z_HUFFMAN_ONLY: 2,- Z_RLE: 3,- Z_FIXED: 4,- Z_DEFAULT_STRATEGY: 0,-- /* Possible values of the data_type field (though see inflate()) */- Z_BINARY: 0,- Z_TEXT: 1,- //Z_ASCII: 1, // = Z_TEXT (deprecated)- Z_UNKNOWN: 2,+ // definition http://translate.sourceforge.net/wiki/l10n/pluralforms++ /* [code, name, numbers, pluralsType] */+ var _rules = [+ ["ach", "Acholi", [1,2], 1],+ ["af", "Afrikaans",[1,2], 2],+ ["ak", "Akan", [1,2], 1],+ ["am", "Amharic", [1,2], 1],+ ["an", "Aragonese",[1,2], 2],+ ["ar", "Arabic", [0,1,2,3,11,100],5],+ ["arn", "Mapudungun",[1,2], 1],+ ["ast", "Asturian", [1,2], 2],+ ["ay", "Aymará", [1], 3],+ ["az", "Azerbaijani",[1,2],2],+ ["be", "Belarusian",[1,2,5],4],+ ["bg", "Bulgarian",[1,2], 2],+ ["bn", "Bengali", [1,2], 2],+ ["bo", "Tibetan", [1], 3],+ ["br", "Breton", [1,2], 1],+ ["bs", "Bosnian", [1,2,5],4],+ ["ca", "Catalan", [1,2], 2],+ ["cgg", "Chiga", [1], 3],+ ["cs", "Czech", [1,2,5],6],+ ["csb", "Kashubian",[1,2,5],7],+ ["cy", "Welsh", [1,2,3,8],8],+ ["da", "Danish", [1,2], 2],+ ["de", "German", [1,2], 2],+ ["dev", "Development Fallback", [1,2], 2],+ ["dz", "Dzongkha", [1], 3],+ ["el", "Greek", [1,2], 2],+ ["en", "English", [1,2], 2],+ ["eo", "Esperanto",[1,2], 2],+ ["es", "Spanish", [1,2], 2],+ ["es_ar","Argentinean Spanish", [1,2], 2],+ ["et", "Estonian", [1,2], 2],+ ["eu", "Basque", [1,2], 2],+ ["fa", "Persian", [1], 3],+ ["fi", "Finnish", [1,2], 2],+ ["fil", "Filipino", [1,2], 1],+ ["fo", "Faroese", [1,2], 2],+ ["fr", "French", [1,2], 9],+ ["fur", "Friulian", [1,2], 2],+ ["fy", "Frisian", [1,2], 2],+ ["ga", "Irish", [1,2,3,7,11],10],+ ["gd", "Scottish Gaelic",[1,2,3,20],11],+ ["gl", "Galician", [1,2], 2],+ ["gu", "Gujarati", [1,2], 2],+ ["gun", "Gun", [1,2], 1],+ ["ha", "Hausa", [1,2], 2],+ ["he", "Hebrew", [1,2], 2],+ ["hi", "Hindi", [1,2], 2],+ ["hr", "Croatian", [1,2,5],4],+ ["hu", "Hungarian",[1,2], 2],+ ["hy", "Armenian", [1,2], 2],+ ["ia", "Interlingua",[1,2],2],+ ["id", "Indonesian",[1], 3],+ ["is", "Icelandic",[1,2], 12],+ ["it", "Italian", [1,2], 2],+ ["ja", "Japanese", [1], 3],+ ["jbo", "Lojban", [1], 3],+ ["jv", "Javanese", [0,1], 13],+ ["ka", "Georgian", [1], 3],+ ["kk", "Kazakh", [1], 3],+ ["km", "Khmer", [1], 3],+ ["kn", "Kannada", [1,2], 2],+ ["ko", "Korean", [1], 3],+ ["ku", "Kurdish", [1,2], 2],+ ["kw", "Cornish", [1,2,3,4],14],+ ["ky", "Kyrgyz", [1], 3],+ ["lb", "Letzeburgesch",[1,2],2],+ ["ln", "Lingala", [1,2], 1],+ ["lo", "Lao", [1], 3],+ ["lt", "Lithuanian",[1,2,10],15],+ ["lv", "Latvian", [1,2,0],16],+ ["mai", "Maithili", [1,2], 2],+ ["mfe", "Mauritian Creole",[1,2],1],+ ["mg", "Malagasy", [1,2], 1],+ ["mi", "Maori", [1,2], 1],+ ["mk", "Macedonian",[1,2],17],+ ["ml", "Malayalam",[1,2], 2],+ ["mn", "Mongolian",[1,2], 2],+ ["mnk", "Mandinka", [0,1,2],18],+ ["mr", "Marathi", [1,2], 2],+ ["ms", "Malay", [1], 3],+ ["mt", "Maltese", [1,2,11,20],19],+ ["nah", "Nahuatl", [1,2], 2],+ ["nap", "Neapolitan",[1,2], 2],+ ["nb", "Norwegian Bokmal",[1,2],2],+ ["ne", "Nepali", [1,2], 2],+ ["nl", "Dutch", [1,2], 2],+ ["nn", "Norwegian Nynorsk",[1,2],2],+ ["no", "Norwegian",[1,2], 2],+ ["nso", "Northern Sotho",[1,2],2],+ ["oc", "Occitan", [1,2], 1],+ ["or", "Oriya", [2,1], 2],+ ["pa", "Punjabi", [1,2], 2],+ ["pap", "Papiamento",[1,2], 2],+ ["pl", "Polish", [1,2,5],7],+ ["pms", "Piemontese",[1,2], 2],+ ["ps", "Pashto", [1,2], 2],+ ["pt", "Portuguese",[1,2], 2],+ ["pt_br","Brazilian Portuguese",[1,2], 2],+ ["rm", "Romansh", [1,2], 2],+ ["ro", "Romanian", [1,2,20],20],+ ["ru", "Russian", [1,2,5],4],+ ["sah", "Yakut", [1], 3],+ ["sco", "Scots", [1,2], 2],+ ["se", "Northern Sami",[1,2], 2],+ ["si", "Sinhala", [1,2], 2],+ ["sk", "Slovak", [1,2,5],6],+ ["sl", "Slovenian",[5,1,2,3],21],+ ["so", "Somali", [1,2], 2],+ ["son", "Songhay", [1,2], 2],+ ["sq", "Albanian", [1,2], 2],+ ["sr", "Serbian", [1,2,5],4],+ ["su", "Sundanese",[1], 3],+ ["sv", "Swedish", [1,2], 2],+ ["sw", "Swahili", [1,2], 2],+ ["ta", "Tamil", [1,2], 2],+ ["te", "Telugu", [1,2], 2],+ ["tg", "Tajik", [1,2], 1],+ ["th", "Thai", [1], 3],+ ["ti", "Tigrinya", [1,2], 1],+ ["tk", "Turkmen", [1,2], 2],+ ["tr", "Turkish", [1,2], 1],+ ["tt", "Tatar", [1], 3],+ ["ug", "Uyghur", [1], 3],+ ["uk", "Ukrainian",[1,2,5],4],+ ["ur", "Urdu", [1,2], 2],+ ["uz", "Uzbek", [1,2], 1],+ ["vi", "Vietnamese",[1], 3],+ ["wa", "Walloon", [1,2], 1],+ ["wo", "Wolof", [1], 3],+ ["yo", "Yoruba", [1,2], 2],+ ["zh", "Chinese", [1], 3]+ ];++ var _rulesPluralsTypes = {+ 1: function(n) {return Number(n > 1);},+ 2: function(n) {return Number(n != 1);},+ 3: function(n) {return 0;},+ 4: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},+ 5: function(n) {return Number(n===0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 ? 4 : 5);},+ 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},+ 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},+ 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},+ 9: function(n) {return Number(n >= 2);},+ 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},+ 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},+ 12: function(n) {return Number(n%10!=1 || n%100==11);},+ 13: function(n) {return Number(n !== 0);},+ 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},+ 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},+ 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},+ 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},+ 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},+ 19: function(n) {return Number(n==1 ? 0 : n===0 || ( n%100>1 && n%100<11) ? 1 : (n%100>10 && n%100<20 ) ? 2 : 3);},+ 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},+ 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }+ };++ var pluralExtensions = {++ rules: (function () {+ var l, rules = {};+ for (l=_rules.length; l-- ;) {+ rules[_rules[l][0]] = {+ name: _rules[l][1],+ numbers: _rules[l][2],+ plurals: _rulesPluralsTypes[_rules[l][3]]+ }+ }+ return rules;+ }()),++ // you can add your own pluralExtensions+ addRule: function(lng, obj) {+ pluralExtensions.rules[lng] = obj;+ },++ setCurrentLng: function(lng) {+ if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {+ var parts = lng.split('-');++ pluralExtensions.currentRule = {+ lng: lng,+ rule: pluralExtensions.rules[parts[0]]+ };+ }+ },++ needsPlural: function(lng, count) {+ var parts = lng.split('-');++ var ext;+ if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {+ ext = pluralExtensions.currentRule.rule;+ } else {+ ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];+ }++ if (ext && ext.numbers.length <= 1) {+ return false;+ } else {+ return this.get(lng, count) !== 1;+ }+ },++ get: function(lng, count) {+ var parts = lng.split('-');++ function getResult(l, c) {+ var ext;+ if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {+ ext = pluralExtensions.currentRule.rule;+ } else {+ ext = pluralExtensions.rules[l];+ }+ if (ext) {+ var i;+ if (ext.noAbs) {+ i = ext.plurals(c);+ } else {+ i = ext.plurals(Math.abs(c));+ }++ var number = ext.numbers[i];+ if (ext.numbers.length === 2 && ext.numbers[0] === 1) {+ if (number === 2) {+ number = -1; // regular plural+ } else if (number === 1) {+ number = 1; // singular+ }+ }//console.log(count + '-' + number);+ return number;+ } else {+ return c === 1 ? '1' : '-1';+ }+ }++ return getResult(parts[f.getCountyIndexOfLng(lng)], count);+ }++ };+ var postProcessors = {};+ var addPostProcessor = function(name, fc) {+ postProcessors[name] = fc;+ };+ // sprintf support+ var sprintf = (function() {+ function get_type(variable) {+ return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();+ }+ function str_repeat(input, multiplier) {+ for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}+ return output.join('');+ }++ var str_format = function() {+ if (!str_format.cache.hasOwnProperty(arguments[0])) {+ str_format.cache[arguments[0]] = str_format.parse(arguments[0]);+ }+ return str_format.format.call(null, str_format.cache[arguments[0]], arguments);+ };++ str_format.format = function(parse_tree, argv) {+ var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;+ for (i = 0; i < tree_length; i++) {+ node_type = get_type(parse_tree[i]);+ if (node_type === 'string') {+ output.push(parse_tree[i]);+ }+ else if (node_type === 'array') {+ match = parse_tree[i]; // convenience purposes only+ if (match[2]) { // keyword argument+ arg = argv[cursor];+ for (k = 0; k < match[2].length; k++) {+ if (!arg.hasOwnProperty(match[2][k])) {+ throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));+ }+ arg = arg[match[2][k]];+ }+ }+ else if (match[1]) { // positional argument (explicit)+ arg = argv[match[1]];+ }+ else { // positional argument (implicit)+ arg = argv[cursor++];+ }++ if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {+ throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));+ }+ switch (match[8]) {+ case 'b': arg = arg.toString(2); break;+ case 'c': arg = String.fromCharCode(arg); break;+ case 'd': arg = parseInt(arg, 10); break;+ case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;+ case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;+ case 'o': arg = arg.toString(8); break;+ case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;+ case 'u': arg = Math.abs(arg); break;+ case 'x': arg = arg.toString(16); break;+ case 'X': arg = arg.toString(16).toUpperCase(); break;+ }+ arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);+ pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';+ pad_length = match[6] - String(arg).length;+ pad = match[6] ? str_repeat(pad_character, pad_length) : '';+ output.push(match[5] ? arg + pad : pad + arg);+ }+ }+ return output.join('');+ };++ str_format.cache = {};++ str_format.parse = function(fmt) {+ var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;+ while (_fmt) {+ if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {+ parse_tree.push(match[0]);+ }+ else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {+ parse_tree.push('%');+ }+ else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {+ if (match[2]) {+ arg_names |= 1;+ var field_list = [], replacement_field = match[2], field_match = [];+ if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {+ field_list.push(field_match[1]);+ while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {+ if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {+ field_list.push(field_match[1]);+ }+ else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {+ field_list.push(field_match[1]);+ }+ else {+ throw('[sprintf] huh?');+ }+ }+ }+ else {+ throw('[sprintf] huh?');+ }+ match[2] = field_list;+ }+ else {+ arg_names |= 2;+ }+ if (arg_names === 3) {+ throw('[sprintf] mixing positional and named placeholders is not (yet) supported');+ }+ parse_tree.push(match);+ }+ else {+ throw('[sprintf] huh?');+ }+ _fmt = _fmt.substring(match[0].length);+ }+ return parse_tree;+ };++ return str_format;+ })();++ var vsprintf = function(fmt, argv) {+ argv.unshift(fmt);+ return sprintf.apply(null, argv);+ };++ addPostProcessor("sprintf", function(val, key, opts) {+ if (!opts.sprintf) return val;++ if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {+ return vsprintf(val, opts.sprintf);+ } else if (typeof opts.sprintf === 'object') {+ return sprintf(val, opts.sprintf);+ }++ return val;+ });+ // public api interface+ i18n.init = init;+ i18n.setLng = setLng;+ i18n.preload = preload;+ i18n.addResourceBundle = addResourceBundle;+ i18n.hasResourceBundle = hasResourceBundle;+ i18n.addResource = addResource;+ i18n.addResources = addResources;+ i18n.removeResourceBundle = removeResourceBundle;+ i18n.loadNamespace = loadNamespace;+ i18n.loadNamespaces = loadNamespaces;+ i18n.setDefaultNamespace = setDefaultNamespace;+ i18n.t = translate;+ i18n.translate = translate;+ i18n.exists = exists;+ i18n.detectLanguage = f.detectLanguage;+ i18n.pluralExtensions = pluralExtensions;+ i18n.sync = sync;+ i18n.functions = f;+ i18n.lng = lng;+ i18n.addPostProcessor = addPostProcessor;+ i18n.options = o;- /* The deflate compression method */- Z_DEFLATED: 8- //Z_NULL: null // Use -1 or null inline, depending on var type-};-},{}],73:[function(require,module,exports){+})();+},{"jquery":"jquery"}],67:[function(require,module,exports){+// Top level file is just a mixin of submodules & constants'use strict';-// Note: we can't get significant speed boost here.-// So write code to minimize size - no pregenerated tables-// and array tools dependencies.---// Use ordinary array, since untyped makes no boost here-function makeTable() {- var c, table = [];-- for(var n =0; n < 256; n++){- c = n;- for(var k =0; k < 8; k++){- c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));- }- table[n] = c;- }-- return table;-}--// Create table on load. Just 255 signed longs. Not a problem.-var crcTable = makeTable();-+var assign = require('./lib/utils/common').assign;-function crc32(crc, buf, len, pos) {- var t = crcTable- , end = pos + len;+var deflate = require('./lib/deflate');+var inflate = require('./lib/inflate');+var constants = require('./lib/zlib/constants');- crc = crc ^ (-1);+var pako = {};- for (var i = pos; i < end; i++ ) {- crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];- }+assign(pako, deflate, inflate, constants);- return (crc ^ (-1)); // >>> 0;-}+module.exports = pako;+},{"./lib/deflate":68,"./lib/inflate":69,"./lib/utils/common":70,"./lib/zlib/constants":73}],68:[function(require,module,exports){+'use strict';-module.exports = crc32;-},{}],74:[function(require,module,exports){-'use strict';+var zlib_deflate = require('./zlib/deflate.js');+var utils = require('./utils/common');+var strings = require('./utils/strings');+var msg = require('./zlib/messages');+var zstream = require('./zlib/zstream');-var utils = require('../utils/common');-var trees = require('./trees');-var adler32 = require('./adler32');-var crc32 = require('./crc32');-var msg = require('./messages');+var toString = Object.prototype.toString;/* Public constants ==========================================================*//* ===========================================================================*/--/* Allowed flush values; see deflate() and inflate() below for details */var Z_NO_FLUSH = 0;-var Z_PARTIAL_FLUSH = 1;-//var Z_SYNC_FLUSH = 2;-var Z_FULL_FLUSH = 3;var Z_FINISH = 4;-var Z_BLOCK = 5;-//var Z_TREES = 6;--/* Return codes for the compression/decompression functions. Negative values- * are errors, positive values are used for special but normal events.- */var Z_OK = 0;var Z_STREAM_END = 1;-//var Z_NEED_DICT = 2;-//var Z_ERRNO = -1;-var Z_STREAM_ERROR = -2;-var Z_DATA_ERROR = -3;-//var Z_MEM_ERROR = -4;-var Z_BUF_ERROR = -5;-//var Z_VERSION_ERROR = -6;--/* compression levels */-//var Z_NO_COMPRESSION = 0;-//var Z_BEST_SPEED = 1;-//var Z_BEST_COMPRESSION = 9;var Z_DEFAULT_COMPRESSION = -1;--var Z_FILTERED = 1;-var Z_HUFFMAN_ONLY = 2;-var Z_RLE = 3;-var Z_FIXED = 4;var Z_DEFAULT_STRATEGY = 0;-/* Possible values of the data_type field (though see inflate()) */-//var Z_BINARY = 0;-//var Z_TEXT = 1;-//var Z_ASCII = 1; // = Z_TEXT-var Z_UNKNOWN = 2;---/* The deflate compression method */var Z_DEFLATED = 8;-/*============================================================================*/---var MAX_MEM_LEVEL = 9;-/* Maximum value for memLevel in deflateInit2 */-var MAX_WBITS = 15;-/* 32K LZ77 window */-var DEF_MEM_LEVEL = 8;---var LENGTH_CODES = 29;-/* number of length codes, not counting the special END_BLOCK code */-var LITERALS = 256;-/* number of literal bytes 0..255 */-var L_CODES = LITERALS + 1 + LENGTH_CODES;-/* number of Literal or Length codes, including the END_BLOCK code */-var D_CODES = 30;-/* number of distance codes */-var BL_CODES = 19;-/* number of codes used to transfer the bit lengths */-var HEAP_SIZE = 2*L_CODES + 1;-/* maximum heap size */-var MAX_BITS = 15;-/* All codes must not exceed MAX_BITS bits */+/* ===========================================================================*/-var MIN_MATCH = 3;-var MAX_MATCH = 258;-var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);-var PRESET_DICT = 0x20;+/**+ * class Deflate+ *+ * Generic JS-style wrapper for zlib calls. If you don't need+ * streaming behaviour - use more simple functions: [[deflate]],+ * [[deflateRaw]] and [[gzip]].+ **/-var INIT_STATE = 42;-var EXTRA_STATE = 69;-var NAME_STATE = 73;-var COMMENT_STATE = 91;-var HCRC_STATE = 103;-var BUSY_STATE = 113;-var FINISH_STATE = 666;+/* internal+ * Deflate.chunks -> Array+ *+ * Chunks of output data, if [[Deflate#onData]] not overriden.+ **/-var BS_NEED_MORE = 1; /* block not completed, need more input or more output */-var BS_BLOCK_DONE = 2; /* block flush performed */-var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */-var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */+/**+ * Deflate.result -> Uint8Array|Array+ *+ * Compressed result, generated by default [[Deflate#onData]]+ * and [[Deflate#onEnd]] handlers. Filled after you push last chunk+ * (call [[Deflate#push]] with `Z_FINISH` / `true` param).+ **/-var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.+/**+ * Deflate.err -> Number+ *+ * Error code after deflate finished. 0 (Z_OK) on success.+ * You will not need it in real life, because deflate errors+ * are possible only on wrong options or bad `onData` / `onEnd`+ * custom handlers.+ **/-function err(strm, errorCode) {- strm.msg = msg[errorCode];- return errorCode;-}+/**+ * Deflate.msg -> String+ *+ * Error message, if [[Deflate.err]] != 0+ **/-function rank(f) {- return ((f) << 1) - ((f) > 4 ? 9 : 0);-}-function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }+/**+ * new Deflate(options)+ * - options (Object): zlib deflate options.+ *+ * Creates new deflator instance with specified params. Throws exception+ * on bad params. Supported options:+ *+ * - `level`+ * - `windowBits`+ * - `memLevel`+ * - `strategy`+ *+ * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)+ * for more information on these.+ *+ * Additional options, for internal needs:+ *+ * - `chunkSize` - size of generated data chunks (16K by default)+ * - `raw` (Boolean) - do raw deflate+ * - `gzip` (Boolean) - create gzip wrapper+ * - `to` (String) - if equal to 'string', then result will be "binary string"+ * (each char code [0..255])+ * - `header` (Object) - custom header for gzip+ * - `text` (Boolean) - true if compressed data believed to be text+ * - `time` (Number) - modification time, unix timestamp+ * - `os` (Number) - operation system code+ * - `extra` (Array) - array of bytes with extra data (max 65536)+ * - `name` (String) - file name (binary string)+ * - `comment` (String) - comment (binary string)+ * - `hcrc` (Boolean) - true if header crc should be added+ *+ * ##### Example:+ *+ * ```javascript+ * var pako = require('pako')+ * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])+ * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);+ *+ * var deflate = new pako.Deflate({ level: 3});+ *+ * deflate.push(chunk1, false);+ * deflate.push(chunk2, true); // true -> last chunk+ *+ * if (deflate.err) { throw new Error(deflate.err); }+ *+ * console.log(deflate.result);+ * ```+ **/+var Deflate = function(options) {+ this.options = utils.assign({+ level: Z_DEFAULT_COMPRESSION,+ method: Z_DEFLATED,+ chunkSize: 16384,+ windowBits: 15,+ memLevel: 8,+ strategy: Z_DEFAULT_STRATEGY,+ to: ''+ }, options || {});-/* =========================================================================- * Flush as much pending output as possible. All deflate() output goes- * through this function so some applications may wish to modify it- * to avoid allocating a large strm->output buffer and copying into it.- * (See also read_buf()).- */-function flush_pending(strm) {- var s = strm.state;+ var opt = this.options;- //_tr_flush_bits(s);- var len = s.pending;- if (len > strm.avail_out) {- len = strm.avail_out;+ if (opt.raw && (opt.windowBits > 0)) {+ opt.windowBits = -opt.windowBits;}- if (len === 0) { return; }- utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);- strm.next_out += len;- s.pending_out += len;- strm.total_out += len;- strm.avail_out -= len;- s.pending -= len;- if (s.pending === 0) {- s.pending_out = 0;+ else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {+ opt.windowBits += 16;}-}---function flush_block_only (s, last) {- trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);- s.block_start = s.strstart;- flush_pending(s.strm);-}+ this.err = 0; // error code, if happens (0 = Z_OK)+ this.msg = ''; // error message+ this.ended = false; // used to avoid multiple onEnd() calls+ this.chunks = []; // chunks of compressed data-function put_byte(s, b) {- s.pending_buf[s.pending++] = b;-}+ this.strm = new zstream();+ this.strm.avail_out = 0;+ var status = zlib_deflate.deflateInit2(+ this.strm,+ opt.level,+ opt.method,+ opt.windowBits,+ opt.memLevel,+ opt.strategy+ );-/* =========================================================================- * Put a short in the pending buffer. The 16-bit value is put in MSB order.- * IN assertion: the stream state is correct and there is enough room in- * pending_buf.- */-function putShortMSB(s, b) {-// put_byte(s, (Byte)(b >> 8));-// put_byte(s, (Byte)(b & 0xff));- s.pending_buf[s.pending++] = (b >>> 8) & 0xff;- s.pending_buf[s.pending++] = b & 0xff;-}+ if (status !== Z_OK) {+ throw new Error(msg[status]);+ }+ if (opt.header) {+ zlib_deflate.deflateSetHeader(this.strm, opt.header);+ }+};-/* ===========================================================================- * Read a new buffer from the current input stream, update the adler32- * and total number of bytes read. All deflate() input goes through- * this function so some applications may wish to modify it to avoid- * allocating a large strm->input buffer and copying from it.- * (See also flush_pending()).- */-function read_buf(strm, buf, start, size) {- var len = strm.avail_in;+/**+ * Deflate#push(data[, mode]) -> Boolean+ * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be+ * converted to utf8 byte sequence.+ * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.+ * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.+ *+ * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with+ * new compressed chunks. Returns `true` on success. The last data block must have+ * mode Z_FINISH (or `true`). That flush internal pending buffers and call+ * [[Deflate#onEnd]].+ *+ * On fail call [[Deflate#onEnd]] with error code and return false.+ *+ * We strongly recommend to use `Uint8Array` on input for best speed (output+ * array format is detected automatically). Also, don't skip last param and always+ * use the same type in your code (boolean or number). That will improve JS speed.+ *+ * For regular `Array`-s make sure all elements are [0..255].+ *+ * ##### Example+ *+ * ```javascript+ * push(chunk, false); // push one of data chunks+ * ...+ * push(chunk, true); // push last chunk+ * ```+ **/+Deflate.prototype.push = function(data, mode) {+ var strm = this.strm;+ var chunkSize = this.options.chunkSize;+ var status, _mode;- if (len > size) { len = size; }- if (len === 0) { return 0; }+ if (this.ended) { return false; }- strm.avail_in -= len;+ _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);- utils.arraySet(buf, strm.input, strm.next_in, len, start);- if (strm.state.wrap === 1) {- strm.adler = adler32(strm.adler, buf, len, start);+ // Convert data if needed+ if (typeof data === 'string') {+ // If we need to compress text, change encoding to utf8.+ strm.input = strings.string2buf(data);+ } else if (toString.call(data) === '[object ArrayBuffer]') {+ strm.input = new Uint8Array(data);+ } else {+ strm.input = data;}- else if (strm.state.wrap === 2) {- strm.adler = crc32(strm.adler, buf, len, start);- }+ strm.next_in = 0;+ strm.avail_in = strm.input.length;- strm.next_in += len;- strm.total_in += len;+ do {+ if (strm.avail_out === 0) {+ strm.output = new utils.Buf8(chunkSize);+ strm.next_out = 0;+ strm.avail_out = chunkSize;+ }+ status = zlib_deflate.deflate(strm, _mode); /* no bad return value */- return len;-}+ if (status !== Z_STREAM_END && status !== Z_OK) {+ this.onEnd(status);+ this.ended = true;+ return false;+ }+ if (strm.avail_out === 0 || (strm.avail_in === 0 && _mode === Z_FINISH)) {+ if (this.options.to === 'string') {+ this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));+ } else {+ this.onData(utils.shrinkBuf(strm.output, strm.next_out));+ }+ }+ } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);+ // Finalize on the last chunk.+ if (_mode === Z_FINISH) {+ status = zlib_deflate.deflateEnd(this.strm);+ this.onEnd(status);+ this.ended = true;+ return status === Z_OK;+ }-/* ===========================================================================- * Set match_start to the longest match starting at the given string and- * return its length. Matches shorter or equal to prev_length are discarded,- * in which case the result is equal to prev_length and match_start is- * garbage.- * IN assertions: cur_match is the head of the hash chain for the current- * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1- * OUT assertion: the match length is not greater than s->lookahead.- */-function longest_match(s, cur_match) {- var chain_length = s.max_chain_length; /* max hash chain length */- var scan = s.strstart; /* current string */- var match; /* matched string */- var len; /* length of current match */- var best_len = s.prev_length; /* best match length so far */- var nice_match = s.nice_match; /* stop if match long enough */- var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?- s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;+ return true;+};- var _win = s.window; // shortcut- var wmask = s.w_mask;- var prev = s.prev;+/**+ * Deflate#onData(chunk) -> Void+ * - chunk (Uint8Array|Array|String): ouput data. Type of array depends+ * on js engine support. When string output requested, each chunk+ * will be string.+ *+ * By default, stores data blocks in `chunks[]` property and glue+ * those in `onEnd`. Override this handler, if you need another behaviour.+ **/+Deflate.prototype.onData = function(chunk) {+ this.chunks.push(chunk);+};- /* Stop when cur_match becomes <= limit. To simplify the code,- * we prevent matches with the string of window index 0.- */- var strend = s.strstart + MAX_MATCH;- var scan_end1 = _win[scan + best_len - 1];- var scan_end = _win[scan + best_len];+/**+ * Deflate#onEnd(status) -> Void+ * - status (Number): deflate status. 0 (Z_OK) on success,+ * other if not.+ *+ * Called once after you tell deflate that input stream complete+ * or error happenned. By default - join collected chunks,+ * free memory and fill `results` / `err` properties.+ **/+Deflate.prototype.onEnd = function(status) {+ // On success - join+ if (status === Z_OK) {+ if (this.options.to === 'string') {+ this.result = this.chunks.join('');+ } else {+ this.result = utils.flattenChunks(this.chunks);+ }+ }+ this.chunks = [];+ this.err = status;+ this.msg = this.strm.msg;+};- /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.- * It is easy to get rid of this optimization if necessary.- */- // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");- /* Do not waste too much time if we already have a good match: */- if (s.prev_length >= s.good_match) {- chain_length >>= 2;- }- /* Do not look for matches beyond the end of the input. This is necessary- * to make deflate deterministic.- */- if (nice_match > s.lookahead) { nice_match = s.lookahead; }+/**+ * deflate(data[, options]) -> Uint8Array|Array|String+ * - data (Uint8Array|Array|String): input data to compress.+ * - options (Object): zlib deflate options.+ *+ * Compress `data` with deflate alrorythm and `options`.+ *+ * Supported options are:+ *+ * - level+ * - windowBits+ * - memLevel+ * - strategy+ *+ * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)+ * for more information on these.+ *+ * Sugar (options):+ *+ * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify+ * negative windowBits implicitly.+ * - `to` (String) - if equal to 'string', then result will be "binary string"+ * (each char code [0..255])+ *+ * ##### Example:+ *+ * ```javascript+ * var pako = require('pako')+ * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);+ *+ * console.log(pako.deflate(data));+ * ```+ **/+function deflate(input, options) {+ var deflator = new Deflate(options);- // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");+ deflator.push(input, true);- do {- // Assert(cur_match < s->strstart, "no future");- match = cur_match;+ // That will never happens, if you don't cheat with options :)+ if (deflator.err) { throw deflator.msg; }- /* Skip to next match if the match length cannot increase- * or if the match length is less than 2. Note that the checks below- * for insufficient lookahead only occur occasionally for performance- * reasons. Therefore uninitialized memory will be accessed, and- * conditional jumps will be made that depend on those values.- * However the length of the match is limited to the lookahead, so- * the output of deflate is not affected by the uninitialized values.- */+ return deflator.result;+}- if (_win[match + best_len] !== scan_end ||- _win[match + best_len - 1] !== scan_end1 ||- _win[match] !== _win[scan] ||- _win[++match] !== _win[scan + 1]) {- continue;- }- /* The check at best_len-1 can be removed because it will be made- * again later. (This heuristic is not always a win.)- * It is not necessary to compare scan[2] and match[2] since they- * are always equal when the other bytes match, given that- * the hash keys are equal and that HASH_BITS >= 8.- */- scan += 2;- match++;- // Assert(*scan == *match, "match[2]?");+/**+ * deflateRaw(data[, options]) -> Uint8Array|Array|String+ * - data (Uint8Array|Array|String): input data to compress.+ * - options (Object): zlib deflate options.+ *+ * The same as [[deflate]], but creates raw data, without wrapper+ * (header and adler32 crc).+ **/+function deflateRaw(input, options) {+ options = options || {};+ options.raw = true;+ return deflate(input, options);+}- /* We check for insufficient lookahead only every 8th comparison;- * the 256th check will be made at strstart+258.- */- do {- /*jshint noempty:false*/- } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&- _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&- _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&- _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&- scan < strend);- // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");+/**+ * gzip(data[, options]) -> Uint8Array|Array|String+ * - data (Uint8Array|Array|String): input data to compress.+ * - options (Object): zlib deflate options.+ *+ * The same as [[deflate]], but create gzip wrapper instead of+ * deflate one.+ **/+function gzip(input, options) {+ options = options || {};+ options.gzip = true;+ return deflate(input, options);+}- len = MAX_MATCH - (strend - scan);- scan = strend - MAX_MATCH;- if (len > best_len) {- s.match_start = cur_match;- best_len = len;- if (len >= nice_match) {- break;- }- scan_end1 = _win[scan + best_len - 1];- scan_end = _win[scan + best_len];- }- } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);+exports.Deflate = Deflate;+exports.deflate = deflate;+exports.deflateRaw = deflateRaw;+exports.gzip = gzip;+},{"./utils/common":70,"./utils/strings":71,"./zlib/deflate.js":75,"./zlib/messages":80,"./zlib/zstream":82}],69:[function(require,module,exports){+'use strict';- if (best_len <= s.lookahead) {- return best_len;- }- return s.lookahead;-}+var zlib_inflate = require('./zlib/inflate.js');+var utils = require('./utils/common');+var strings = require('./utils/strings');+var c = require('./zlib/constants');+var msg = require('./zlib/messages');+var zstream = require('./zlib/zstream');+var gzheader = require('./zlib/gzheader');++var toString = Object.prototype.toString;-/* ===========================================================================- * Fill the window when the lookahead becomes insufficient.- * Updates strstart and lookahead.+/**+ * class Inflate*- * IN assertion: lookahead < MIN_LOOKAHEAD- * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD- * At least one byte has been read, or avail_in == 0; reads are- * performed for at least two bytes (required for the zip translate_eol- * option -- not supported here).- */-function fill_window(s) {- var _w_size = s.w_size;- var p, n, m, more, str;+ * Generic JS-style wrapper for zlib calls. If you don't need+ * streaming behaviour - use more simple functions: [[inflate]]+ * and [[inflateRaw]].+ **/- //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");+/* internal+ * inflate.chunks -> Array+ *+ * Chunks of output data, if [[Inflate#onData]] not overriden.+ **/- do {- more = s.window_size - s.lookahead - s.strstart;+/**+ * Inflate.result -> Uint8Array|Array|String+ *+ * Uncompressed result, generated by default [[Inflate#onData]]+ * and [[Inflate#onEnd]] handlers. Filled after you push last chunk+ * (call [[Inflate#push]] with `Z_FINISH` / `true` param).+ **/- // JS ints have 32 bit, block below not needed- /* Deal with !@#$% 64K limit: */- //if (sizeof(int) <= 2) {- // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {- // more = wsize;- //- // } else if (more == (unsigned)(-1)) {- // /* Very unlikely, but possible on 16 bit machine if- // * strstart == 0 && lookahead == 1 (input done a byte at time)- // */- // more--;- // }- //}+/**+ * Inflate.err -> Number+ *+ * Error code after inflate finished. 0 (Z_OK) on success.+ * Should be checked if broken data possible.+ **/+/**+ * Inflate.msg -> String+ *+ * Error message, if [[Inflate.err]] != 0+ **/- /* If the window is almost full and there is insufficient lookahead,- * move the upper half to the lower one to make room in the upper half.- */- if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {- utils.arraySet(s.window, s.window, _w_size, _w_size, 0);- s.match_start -= _w_size;- s.strstart -= _w_size;- /* we now have strstart >= MAX_DIST */- s.block_start -= _w_size;+/**+ * new Inflate(options)+ * - options (Object): zlib inflate options.+ *+ * Creates new inflator instance with specified params. Throws exception+ * on bad params. Supported options:+ *+ * - `windowBits`+ *+ * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)+ * for more information on these.+ *+ * Additional options, for internal needs:+ *+ * - `chunkSize` - size of generated data chunks (16K by default)+ * - `raw` (Boolean) - do raw inflate+ * - `to` (String) - if equal to 'string', then result will be converted+ * from utf8 to utf16 (javascript) string. When string output requested,+ * chunk length can differ from `chunkSize`, depending on content.+ *+ * By default, when no options set, autodetect deflate/gzip data format via+ * wrapper header.+ *+ * ##### Example:+ *+ * ```javascript+ * var pako = require('pako')+ * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])+ * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);+ *+ * var inflate = new pako.Inflate({ level: 3});+ *+ * inflate.push(chunk1, false);+ * inflate.push(chunk2, true); // true -> last chunk+ *+ * if (inflate.err) { throw new Error(inflate.err); }+ *+ * console.log(inflate.result);+ * ```+ **/+var Inflate = function(options) {++ this.options = utils.assign({+ chunkSize: 16384,+ windowBits: 0,+ to: ''+ }, options || {});- /* Slide the hash table (could be avoided with 32 bit values- at the expense of memory usage). We slide even when level == 0- to keep the hash table consistent if we switch back to level > 0- later. (Using level 0 permanently is not an optimal usage of- zlib, so we don't care about this pathological case.)- */+ var opt = this.options;- n = s.hash_size;- p = n;- do {- m = s.head[--p];- s.head[p] = (m >= _w_size ? m - _w_size : 0);- } while (--n);+ // Force window size for `raw` data, if not set directly,+ // because we have no header for autodetect.+ if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {+ opt.windowBits = -opt.windowBits;+ if (opt.windowBits === 0) { opt.windowBits = -15; }+ }- n = _w_size;- p = n;- do {- m = s.prev[--p];- s.prev[p] = (m >= _w_size ? m - _w_size : 0);- /* If n is not on any hash chain, prev[n] is garbage but- * its value will never be used.- */- } while (--n);+ // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate+ if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&+ !(options && options.windowBits)) {+ opt.windowBits += 32;+ }- more += _w_size;- }- if (s.strm.avail_in === 0) {- break;+ // Gzip header has no info about windows size, we can do autodetect only+ // for deflate. So, if window size not set, force it to max when gzip possible+ if ((opt.windowBits > 15) && (opt.windowBits < 48)) {+ // bit 3 (16) -> gzipped data+ // bit 4 (32) -> autodetect gzip/deflate+ if ((opt.windowBits & 15) === 0) {+ opt.windowBits |= 15;}+ }- /* If there was no sliding:- * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&- * more == window_size - lookahead - strstart- * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)- * => more >= window_size - 2*WSIZE + 2- * In the BIG_MEM or MMAP case (not yet supported),- * window_size == input_size + MIN_LOOKAHEAD &&- * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.- * Otherwise, window_size == 2*WSIZE so more >= 2.- * If there was sliding, more >= WSIZE. So in all cases, more >= 2.- */- //Assert(more >= 2, "more < 2");- n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);- s.lookahead += n;+ this.err = 0; // error code, if happens (0 = Z_OK)+ this.msg = ''; // error message+ this.ended = false; // used to avoid multiple onEnd() calls+ this.chunks = []; // chunks of compressed data- /* Initialize the hash value now that we have some input: */- if (s.lookahead + s.insert >= MIN_MATCH) {- str = s.strstart - s.insert;- s.ins_h = s.window[str];+ this.strm = new zstream();+ this.strm.avail_out = 0;- /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;-//#if MIN_MATCH != 3-// Call update_hash() MIN_MATCH-3 more times-//#endif- while (s.insert) {- /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;+ var status = zlib_inflate.inflateInit2(+ this.strm,+ opt.windowBits+ );- s.prev[str & s.w_mask] = s.head[s.ins_h];- s.head[s.ins_h] = str;- str++;- s.insert--;- if (s.lookahead + s.insert < MIN_MATCH) {- break;- }- }- }- /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,- * but this is not important since only literal bytes will be emitted.- */+ if (status !== c.Z_OK) {+ throw new Error(msg[status]);+ }- } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);+ this.header = new gzheader();- /* If the WIN_INIT bytes after the end of the current data have never been- * written, then zero those bytes in order to avoid memory check reports of- * the use of uninitialized (or uninitialised as Julian writes) bytes by- * the longest match routines. Update the high water mark for the next- * time through here. WIN_INIT is set to MAX_MATCH since the longest match- * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.- */-// if (s.high_water < s.window_size) {-// var curr = s.strstart + s.lookahead;-// var init = 0;-//-// if (s.high_water < curr) {-// /* Previous high water mark below current data -- zero WIN_INIT-// * bytes or up to end of window, whichever is less.-// */-// init = s.window_size - curr;-// if (init > WIN_INIT)-// init = WIN_INIT;-// zmemzero(s->window + curr, (unsigned)init);-// s->high_water = curr + init;-// }-// else if (s->high_water < (ulg)curr + WIN_INIT) {-// /* High water mark at or above current data, but below current data-// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up-// * to end of window, whichever is less.-// */-// init = (ulg)curr + WIN_INIT - s->high_water;-// if (init > s->window_size - s->high_water)-// init = s->window_size - s->high_water;-// zmemzero(s->window + s->high_water, (unsigned)init);-// s->high_water += init;-// }-// }-//-// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,-// "not enough room for search");-}+ zlib_inflate.inflateGetHeader(this.strm, this.header);+};-/* ===========================================================================- * Copy without compression as much as possible from the input stream, return- * the current block state.- * This function does not insert new strings in the dictionary since- * uncompressible data is probably not useful. This function is used- * only for the level=0 compression option.- * NOTE: this function should be optimized to avoid extra copying from- * window to pending_buf.- */-function deflate_stored(s, flush) {- /* Stored blocks are limited to 0xffff bytes, pending_buf is limited- * to pending_buf_size, and each stored block has a 5 byte header:- */- var max_block_size = 0xffff;+/**+ * Inflate#push(data[, mode]) -> Boolean+ * - data (Uint8Array|Array|ArrayBuffer|String): input data+ * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.+ * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.+ *+ * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with+ * new output chunks. Returns `true` on success. The last data block must have+ * mode Z_FINISH (or `true`). That flush internal pending buffers and call+ * [[Inflate#onEnd]].+ *+ * On fail call [[Inflate#onEnd]] with error code and return false.+ *+ * We strongly recommend to use `Uint8Array` on input for best speed (output+ * format is detected automatically). Also, don't skip last param and always+ * use the same type in your code (boolean or number). That will improve JS speed.+ *+ * For regular `Array`-s make sure all elements are [0..255].+ *+ * ##### Example+ *+ * ```javascript+ * push(chunk, false); // push one of data chunks+ * ...+ * push(chunk, true); // push last chunk+ * ```+ **/+Inflate.prototype.push = function(data, mode) {+ var strm = this.strm;+ var chunkSize = this.options.chunkSize;+ var status, _mode;+ var next_out_utf8, tail, utf8str;- if (max_block_size > s.pending_buf_size - 5) {- max_block_size = s.pending_buf_size - 5;+ if (this.ended) { return false; }+ _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);++ // Convert data if needed+ if (typeof data === 'string') {+ // Only binary strings can be decompressed on practice+ strm.input = strings.binstring2buf(data);+ } else if (toString.call(data) === '[object ArrayBuffer]') {+ strm.input = new Uint8Array(data);+ } else {+ strm.input = data;}- /* Copy as much as possible from input to output: */- for (;;) {- /* Fill the window as much as possible: */- if (s.lookahead <= 1) {+ strm.next_in = 0;+ strm.avail_in = strm.input.length;- //Assert(s->strstart < s->w_size+MAX_DIST(s) ||- // s->block_start >= (long)s->w_size, "slide too late");-// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||-// s.block_start >= s.w_size)) {-// throw new Error("slide too late");-// }+ do {+ if (strm.avail_out === 0) {+ strm.output = new utils.Buf8(chunkSize);+ strm.next_out = 0;+ strm.avail_out = chunkSize;+ }- fill_window(s);- if (s.lookahead === 0 && flush === Z_NO_FLUSH) {- return BS_NEED_MORE;- }+ status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */- if (s.lookahead === 0) {- break;- }- /* flush the current block */+ if (status !== c.Z_STREAM_END && status !== c.Z_OK) {+ this.onEnd(status);+ this.ended = true;+ return false;}- //Assert(s->block_start >= 0L, "block gone");-// if (s.block_start < 0) throw new Error("block gone");- s.strstart += s.lookahead;- s.lookahead = 0;+ if (strm.next_out) {+ if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && _mode === c.Z_FINISH)) {- /* Emit a stored block if pending_buf will be full: */- var max_start = s.block_start + max_block_size;+ if (this.options.to === 'string') {- if (s.strstart === 0 || s.strstart >= max_start) {- /* strstart == 0 is possible when wraparound on 16-bit machine */- s.lookahead = s.strstart - max_start;- s.strstart = max_start;- /*** FLUSH_BLOCK(s, 0); ***/- flush_block_only(s, false);- if (s.strm.avail_out === 0) {- return BS_NEED_MORE;- }- /***/+ next_out_utf8 = strings.utf8border(strm.output, strm.next_out);++ tail = strm.next_out - next_out_utf8;+ utf8str = strings.buf2string(strm.output, next_out_utf8);++ // move tail+ strm.next_out = tail;+ strm.avail_out = chunkSize - tail;+ if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }+ this.onData(utf8str);- }- /* Flush if we may have to slide, otherwise block_start may become- * negative and the data will be gone:- */- if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {- /*** FLUSH_BLOCK(s, 0); ***/- flush_block_only(s, false);- if (s.strm.avail_out === 0) {- return BS_NEED_MORE;+ } else {+ this.onData(utils.shrinkBuf(strm.output, strm.next_out));+ }}- /***/}+ } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);++ if (status === c.Z_STREAM_END) {+ _mode = c.Z_FINISH;+ }+ // Finalize on the last chunk.+ if (_mode === c.Z_FINISH) {+ status = zlib_inflate.inflateEnd(this.strm);+ this.onEnd(status);+ this.ended = true;+ return status === c.Z_OK;}- s.insert = 0;+ return true;+};- if (flush === Z_FINISH) {- /*** FLUSH_BLOCK(s, 1); ***/- flush_block_only(s, true);- if (s.strm.avail_out === 0) {- return BS_FINISH_STARTED;- }- /***/- return BS_FINISH_DONE;- }- if (s.strstart > s.block_start) {- /*** FLUSH_BLOCK(s, 0); ***/- flush_block_only(s, false);- if (s.strm.avail_out === 0) {- return BS_NEED_MORE;+/**+ * Inflate#onData(chunk) -> Void+ * - chunk (Uint8Array|Array|String): ouput data. Type of array depends+ * on js engine support. When string output requested, each chunk+ * will be string.+ *+ * By default, stores data blocks in `chunks[]` property and glue+ * those in `onEnd`. Override this handler, if you need another behaviour.+ **/+Inflate.prototype.onData = function(chunk) {+ this.chunks.push(chunk);+};+++/**+ * Inflate#onEnd(status) -> Void+ * - status (Number): inflate status. 0 (Z_OK) on success,+ * other if not.+ *+ * Called once after you tell inflate that input stream complete+ * or error happenned. By default - join collected chunks,+ * free memory and fill `results` / `err` properties.+ **/+Inflate.prototype.onEnd = function(status) {+ // On success - join+ if (status === c.Z_OK) {+ if (this.options.to === 'string') {+ // Glue & convert here, until we teach pako to send+ // utf8 alligned strings to onData+ this.result = this.chunks.join('');+ } else {+ this.result = utils.flattenChunks(this.chunks);}- /***/}+ this.chunks = [];+ this.err = status;+ this.msg = this.strm.msg;+};- return BS_NEED_MORE;++/**+ * inflate(data[, options]) -> Uint8Array|Array|String+ * - data (Uint8Array|Array|String): input data to decompress.+ * - options (Object): zlib inflate options.+ *+ * Decompress `data` with inflate/ungzip and `options`. Autodetect+ * format via wrapper header by default. That's why we don't provide+ * separate `ungzip` method.+ *+ * Supported options are:+ *+ * - windowBits+ *+ * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)+ * for more information.+ *+ * Sugar (options):+ *+ * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify+ * negative windowBits implicitly.+ * - `to` (String) - if equal to 'string', then result will be converted+ * from utf8 to utf16 (javascript) string. When string output requested,+ * chunk length can differ from `chunkSize`, depending on content.+ *+ *+ * ##### Example:+ *+ * ```javascript+ * var pako = require('pako')+ * , input = pako.deflate([1,2,3,4,5,6,7,8,9])+ * , output;+ *+ * try {+ * output = pako.inflate(input);+ * } catch (err)+ * console.log(err);+ * }+ * ```+ **/+function inflate(input, options) {+ var inflator = new Inflate(options);++ inflator.push(input, true);++ // That will never happens, if you don't cheat with options :)+ if (inflator.err) { throw inflator.msg; }++ return inflator.result;}-/* ===========================================================================- * Compress as much as possible from the input stream, return the current- * block state.- * This function does not perform lazy evaluation of matches and inserts- * new strings in the dictionary only for unmatched strings or for short- * matches. It is used only for the fast compression options.- */-function deflate_fast(s, flush) {- var hash_head; /* head of the hash chain */- var bflush; /* set if current block must be flushed */- for (;;) {- /* Make sure that we always have enough lookahead, except- * at the end of the input file. We need MAX_MATCH bytes- * for the next match, plus MIN_MATCH bytes to insert the- * string following the next match.- */- if (s.lookahead < MIN_LOOKAHEAD) {- fill_window(s);- if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {- return BS_NEED_MORE;- }- if (s.lookahead === 0) {- break; /* flush the current block */- }- }+/**+ * inflateRaw(data[, options]) -> Uint8Array|Array|String+ * - data (Uint8Array|Array|String): input data to decompress.+ * - options (Object): zlib inflate options.+ *+ * The same as [[inflate]], but creates raw data, without wrapper+ * (header and adler32 crc).+ **/+function inflateRaw(input, options) {+ options = options || {};+ options.raw = true;+ return inflate(input, options);+}- /* Insert the string window[strstart .. strstart+2] in the- * dictionary, and set hash_head to the head of the hash chain:- */- hash_head = 0/*NIL*/;- if (s.lookahead >= MIN_MATCH) {- /*** INSERT_STRING(s, s.strstart, hash_head); ***/- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;- hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];- s.head[s.ins_h] = s.strstart;- /***/- }- /* Find the longest match, discarding those <= prev_length.- * At this point we have always match_length < MIN_MATCH- */- if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {- /* To simplify the code, we prevent matches with the string- * of window index 0 (in particular we have to avoid a match- * of the string with itself at the start of the input file).- */- s.match_length = longest_match(s, hash_head);- /* longest_match() sets match_start */- }- if (s.match_length >= MIN_MATCH) {- // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only+/**+ * ungzip(data[, options]) -> Uint8Array|Array|String+ * - data (Uint8Array|Array|String): input data to decompress.+ * - options (Object): zlib inflate options.+ *+ * Just shortcut to [[inflate]], because it autodetects format+ * by header.content. Done for convenience.+ **/- /*** _tr_tally_dist(s, s.strstart - s.match_start,- s.match_length - MIN_MATCH, bflush); ***/- bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);- s.lookahead -= s.match_length;+exports.Inflate = Inflate;+exports.inflate = inflate;+exports.inflateRaw = inflateRaw;+exports.ungzip = inflate;- /* Insert new strings in the hash table only if the match length- * is not too large. This saves time but degrades compression.- */- if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {- s.match_length--; /* string at strstart already in table */- do {- s.strstart++;- /*** INSERT_STRING(s, s.strstart, hash_head); ***/- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;- hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];- s.head[s.ins_h] = s.strstart;- /***/- /* strstart never exceeds WSIZE-MAX_MATCH, so there are- * always MIN_MATCH bytes ahead.- */- } while (--s.match_length !== 0);- s.strstart++;- } else- {- s.strstart += s.match_length;- s.match_length = 0;- s.ins_h = s.window[s.strstart];- /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;+},{"./utils/common":70,"./utils/strings":71,"./zlib/constants":73,"./zlib/gzheader":76,"./zlib/inflate.js":78,"./zlib/messages":80,"./zlib/zstream":82}],70:[function(require,module,exports){+'use strict';-//#if MIN_MATCH != 3-// Call UPDATE_HASH() MIN_MATCH-3 more times-//#endif- /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not- * matter since it will be recomputed at next deflate call.- */- }- } else {- /* No match, output a literal byte */- //Tracevv((stderr,"%c", s.window[s.strstart]));- /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/- bflush = trees._tr_tally(s, 0, s.window[s.strstart]);- s.lookahead--;- s.strstart++;+var TYPED_OK = (typeof Uint8Array !== 'undefined') &&+ (typeof Uint16Array !== 'undefined') &&+ (typeof Int32Array !== 'undefined');+++exports.assign = function (obj /*from1, from2, from3, ...*/) {+ var sources = Array.prototype.slice.call(arguments, 1);+ while (sources.length) {+ var source = sources.shift();+ if (!source) { continue; }++ if (typeof(source) !== 'object') {+ throw new TypeError(source + 'must be non-object');}- if (bflush) {- /*** FLUSH_BLOCK(s, 0); ***/- flush_block_only(s, false);- if (s.strm.avail_out === 0) {- return BS_NEED_MORE;++ for (var p in source) {+ if (source.hasOwnProperty(p)) {+ obj[p] = source[p];}- /***/}}- s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);- if (flush === Z_FINISH) {- /*** FLUSH_BLOCK(s, 1); ***/- flush_block_only(s, true);- if (s.strm.avail_out === 0) {- return BS_FINISH_STARTED;++ return obj;+};+++// reduce buffer size, avoiding mem copy+exports.shrinkBuf = function (buf, size) {+ if (buf.length === size) { return buf; }+ if (buf.subarray) { return buf.subarray(0, size); }+ buf.length = size;+ return buf;+};+++var fnTyped = {+ arraySet: function (dest, src, src_offs, len, dest_offs) {+ if (src.subarray && dest.subarray) {+ dest.set(src.subarray(src_offs, src_offs+len), dest_offs);+ return;}- /***/- return BS_FINISH_DONE;+ // Fallback to ordinary array+ for(var i=0; i<len; i++) {+ dest[dest_offs + i] = src[src_offs + i];+ }+ },+ // Join array of chunks to single array.+ flattenChunks: function(chunks) {+ var i, l, len, pos, chunk, result;++ // calculate data length+ len = 0;+ for (i=0, l=chunks.length; i<l; i++) {+ len += chunks[i].length;+ }++ // join chunks+ result = new Uint8Array(len);+ pos = 0;+ for (i=0, l=chunks.length; i<l; i++) {+ chunk = chunks[i];+ result.set(chunk, pos);+ pos += chunk.length;+ }++ return result;}- if (s.last_lit) {- /*** FLUSH_BLOCK(s, 0); ***/- flush_block_only(s, false);- if (s.strm.avail_out === 0) {- return BS_NEED_MORE;+};++var fnUntyped = {+ arraySet: function (dest, src, src_offs, len, dest_offs) {+ for(var i=0; i<len; i++) {+ dest[dest_offs + i] = src[src_offs + i];}- /***/+ },+ // Join array of chunks to single array.+ flattenChunks: function(chunks) {+ return [].concat.apply([], chunks);}- return BS_BLOCK_DONE;-}+};-/* ===========================================================================- * Same as above, but achieves better compression. We use a lazy- * evaluation for matches: a match is finally adopted only if there is- * no better match at the next window position.- */-function deflate_slow(s, flush) {- var hash_head; /* head of hash chain */- var bflush; /* set if current block must be flushed */- var max_insert;+// Enable/Disable typed arrays use, for testing+//+exports.setTyped = function (on) {+ if (on) {+ exports.Buf8 = Uint8Array;+ exports.Buf16 = Uint16Array;+ exports.Buf32 = Int32Array;+ exports.assign(exports, fnTyped);+ } else {+ exports.Buf8 = Array;+ exports.Buf16 = Array;+ exports.Buf32 = Array;+ exports.assign(exports, fnUntyped);+ }+};- /* Process the input block. */- for (;;) {- /* Make sure that we always have enough lookahead, except- * at the end of the input file. We need MAX_MATCH bytes- * for the next match, plus MIN_MATCH bytes to insert the- * string following the next match.- */- if (s.lookahead < MIN_LOOKAHEAD) {- fill_window(s);- if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {- return BS_NEED_MORE;- }- if (s.lookahead === 0) { break; } /* flush the current block */- }+exports.setTyped(TYPED_OK);+},{}],71:[function(require,module,exports){+// String encode/decode helpers+'use strict';- /* Insert the string window[strstart .. strstart+2] in the- * dictionary, and set hash_head to the head of the hash chain:- */- hash_head = 0/*NIL*/;- if (s.lookahead >= MIN_MATCH) {- /*** INSERT_STRING(s, s.strstart, hash_head); ***/- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;- hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];- s.head[s.ins_h] = s.strstart;- /***/- }- /* Find the longest match, discarding those <= prev_length.- */- s.prev_length = s.match_length;- s.prev_match = s.match_start;- s.match_length = MIN_MATCH-1;+var utils = require('./common');- if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&- s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {- /* To simplify the code, we prevent matches with the string- * of window index 0 (in particular we have to avoid a match- * of the string with itself at the start of the input file).- */- s.match_length = longest_match(s, hash_head);- /* longest_match() sets match_start */- if (s.match_length <= 5 &&- (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {+// Quick check if we can use fast array to bin string conversion+//+// - apply(Array) can fail on Android 2.2+// - apply(Uint8Array) can fail on iOS 5.1 Safary+//+var STR_APPLY_OK = true;+var STR_APPLY_UIA_OK = true;- /* If prev_match is also MIN_MATCH, match_start is garbage- * but we will ignore the current match anyway.- */- s.match_length = MIN_MATCH-1;- }- }- /* If there was a match at the previous step and the current- * match is not better, output the previous match:- */- if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {- max_insert = s.strstart + s.lookahead - MIN_MATCH;- /* Do not insert strings in hash table beyond this. */+try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }+try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }- //check_match(s, s.strstart-1, s.prev_match, s.prev_length);- /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,- s.prev_length - MIN_MATCH, bflush);***/- bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);- /* Insert in hash table all strings up to the end of the match.- * strstart-1 and strstart are already inserted. If there is not- * enough lookahead, the last two strings are not inserted in- * the hash table.- */- s.lookahead -= s.prev_length-1;- s.prev_length -= 2;- do {- if (++s.strstart <= max_insert) {- /*** INSERT_STRING(s, s.strstart, hash_head); ***/- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;- hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];- s.head[s.ins_h] = s.strstart;- /***/- }- } while (--s.prev_length !== 0);- s.match_available = 0;- s.match_length = MIN_MATCH-1;- s.strstart++;+// Table with utf8 lengths (calculated by first byte of sequence)+// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,+// because max possible codepoint is 0x10ffff+var _utf8len = new utils.Buf8(256);+for (var i=0; i<256; i++) {+ _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);+}+_utf8len[254]=_utf8len[254]=1; // Invalid sequence start- if (bflush) {- /*** FLUSH_BLOCK(s, 0); ***/- flush_block_only(s, false);- if (s.strm.avail_out === 0) {- return BS_NEED_MORE;- }- /***/- }- } else if (s.match_available) {- /* If there was no match at the previous position, output a- * single literal. If there was a match but the current match- * is longer, truncate the previous match to a single literal.- */- //Tracevv((stderr,"%c", s->window[s->strstart-1]));- /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/- bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);+// convert string to array (typed, when possible)+exports.string2buf = function (str) {+ var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;- if (bflush) {- /*** FLUSH_BLOCK_ONLY(s, 0) ***/- flush_block_only(s, false);- /***/+ // count binary size+ for (m_pos = 0; m_pos < str_len; m_pos++) {+ c = str.charCodeAt(m_pos);+ if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {+ c2 = str.charCodeAt(m_pos+1);+ if ((c2 & 0xfc00) === 0xdc00) {+ c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);+ m_pos++;}- s.strstart++;- s.lookahead--;- if (s.strm.avail_out === 0) {- return BS_NEED_MORE;+ }+ buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;+ }++ // allocate buffer+ buf = new utils.Buf8(buf_len);++ // convert+ for (i=0, m_pos = 0; i < buf_len; m_pos++) {+ c = str.charCodeAt(m_pos);+ if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {+ c2 = str.charCodeAt(m_pos+1);+ if ((c2 & 0xfc00) === 0xdc00) {+ c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);+ m_pos++;}+ }+ if (c < 0x80) {+ /* one byte */+ buf[i++] = c;+ } else if (c < 0x800) {+ /* two bytes */+ buf[i++] = 0xC0 | (c >>> 6);+ buf[i++] = 0x80 | (c & 0x3f);+ } else if (c < 0x10000) {+ /* three bytes */+ buf[i++] = 0xE0 | (c >>> 12);+ buf[i++] = 0x80 | (c >>> 6 & 0x3f);+ buf[i++] = 0x80 | (c & 0x3f);} else {- /* There is no previous match to compare with, wait for- * the next step to decide.- */- s.match_available = 1;- s.strstart++;- s.lookahead--;+ /* four bytes */+ buf[i++] = 0xf0 | (c >>> 18);+ buf[i++] = 0x80 | (c >>> 12 & 0x3f);+ buf[i++] = 0x80 | (c >>> 6 & 0x3f);+ buf[i++] = 0x80 | (c & 0x3f);}}- //Assert (flush != Z_NO_FLUSH, "no flush?");- if (s.match_available) {- //Tracevv((stderr,"%c", s->window[s->strstart-1]));- /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/- bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);- s.match_available = 0;- }- s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;- if (flush === Z_FINISH) {- /*** FLUSH_BLOCK(s, 1); ***/- flush_block_only(s, true);- if (s.strm.avail_out === 0) {- return BS_FINISH_STARTED;- }- /***/- return BS_FINISH_DONE;- }- if (s.last_lit) {- /*** FLUSH_BLOCK(s, 0); ***/- flush_block_only(s, false);- if (s.strm.avail_out === 0) {- return BS_NEED_MORE;+ return buf;+};++// Helper (used in 2 places)+function buf2binstring(buf, len) {+ // use fallback for big arrays to avoid stack overflow+ if (len < 65537) {+ if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {+ return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));}- /***/}- return BS_BLOCK_DONE;+ var result = '';+ for(var i=0; i < len; i++) {+ result += String.fromCharCode(buf[i]);+ }+ return result;}-/* ===========================================================================- * For Z_RLE, simply look for runs of bytes, generate matches only of distance- * one. Do not maintain a hash table. (It will be regenerated if this run of- * deflate switches away from Z_RLE.)- */-function deflate_rle(s, flush) {- var bflush; /* set if current block must be flushed */- var prev; /* byte at distance one to match */- var scan, strend; /* scan goes up to strend for length of run */+// Convert byte array to binary string+exports.buf2binstring = function(buf) {+ return buf2binstring(buf, buf.length);+};- var _win = s.window;- for (;;) {- /* Make sure that we always have enough lookahead, except- * at the end of the input file. We need MAX_MATCH bytes- * for the longest run, plus one for the unrolled loop.- */- if (s.lookahead <= MAX_MATCH) {- fill_window(s);- if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {- return BS_NEED_MORE;- }- if (s.lookahead === 0) { break; } /* flush the current block */- }+// Convert binary string (typed, when possible)+exports.binstring2buf = function(str) {+ var buf = new utils.Buf8(str.length);+ for(var i=0, len=buf.length; i < len; i++) {+ buf[i] = str.charCodeAt(i);+ }+ return buf;+};- /* See how many times the previous byte repeats */- s.match_length = 0;- if (s.lookahead >= MIN_MATCH && s.strstart > 0) {- scan = s.strstart - 1;- prev = _win[scan];- if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {- strend = s.strstart + MAX_MATCH;- do {- /*jshint noempty:false*/- } while (prev === _win[++scan] && prev === _win[++scan] &&- prev === _win[++scan] && prev === _win[++scan] &&- prev === _win[++scan] && prev === _win[++scan] &&- prev === _win[++scan] && prev === _win[++scan] &&- scan < strend);- s.match_length = MAX_MATCH - (strend - scan);- if (s.match_length > s.lookahead) {- s.match_length = s.lookahead;- }- }- //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");- }- /* Emit match if have run of MIN_MATCH or longer, else emit literal */- if (s.match_length >= MIN_MATCH) {- //check_match(s, s.strstart, s.strstart - 1, s.match_length);+// convert array to string+exports.buf2string = function (buf, max) {+ var i, out, c, c_len;+ var len = max || buf.length;- /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/- bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);+ // Reserve max possible length (2 words per char)+ // NB: by unknown reasons, Array is significantly faster for+ // String.fromCharCode.apply than Uint16Array.+ var utf16buf = new Array(len*2);- s.lookahead -= s.match_length;- s.strstart += s.match_length;- s.match_length = 0;- } else {- /* No match, output a literal byte */- //Tracevv((stderr,"%c", s->window[s->strstart]));- /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/- bflush = trees._tr_tally(s, 0, s.window[s.strstart]);+ for (out=0, i=0; i<len;) {+ c = buf[i++];+ // quick process ascii+ if (c < 0x80) { utf16buf[out++] = c; continue; }- s.lookahead--;- s.strstart++;- }- if (bflush) {- /*** FLUSH_BLOCK(s, 0); ***/- flush_block_only(s, false);- if (s.strm.avail_out === 0) {- return BS_NEED_MORE;- }- /***/- }- }- s.insert = 0;- if (flush === Z_FINISH) {- /*** FLUSH_BLOCK(s, 1); ***/- flush_block_only(s, true);- if (s.strm.avail_out === 0) {- return BS_FINISH_STARTED;+ c_len = _utf8len[c];+ // skip 5 & 6 byte codes+ if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }++ // apply mask on first byte+ c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;+ // join the rest+ while (c_len > 1 && i < len) {+ c = (c << 6) | (buf[i++] & 0x3f);+ c_len--;}- /***/- return BS_FINISH_DONE;- }- if (s.last_lit) {- /*** FLUSH_BLOCK(s, 0); ***/- flush_block_only(s, false);- if (s.strm.avail_out === 0) {- return BS_NEED_MORE;++ // terminated by end of string?+ if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }++ if (c < 0x10000) {+ utf16buf[out++] = c;+ } else {+ c -= 0x10000;+ utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);+ utf16buf[out++] = 0xdc00 | (c & 0x3ff);}- /***/}- return BS_BLOCK_DONE;-}-/* ===========================================================================- * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.- * (It will be regenerated if this run of deflate switches away from Huffman.)- */-function deflate_huff(s, flush) {- var bflush; /* set if current block must be flushed */+ return buf2binstring(utf16buf, out);+};- for (;;) {- /* Make sure that we have a literal to write. */- if (s.lookahead === 0) {- fill_window(s);- if (s.lookahead === 0) {- if (flush === Z_NO_FLUSH) {- return BS_NEED_MORE;- }- break; /* flush the current block */- }- }- /* Output a literal byte */- s.match_length = 0;- //Tracevv((stderr,"%c", s->window[s->strstart]));- /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/- bflush = trees._tr_tally(s, 0, s.window[s.strstart]);- s.lookahead--;- s.strstart++;- if (bflush) {- /*** FLUSH_BLOCK(s, 0); ***/- flush_block_only(s, false);- if (s.strm.avail_out === 0) {- return BS_NEED_MORE;- }- /***/- }- }- s.insert = 0;- if (flush === Z_FINISH) {- /*** FLUSH_BLOCK(s, 1); ***/- flush_block_only(s, true);- if (s.strm.avail_out === 0) {- return BS_FINISH_STARTED;- }- /***/- return BS_FINISH_DONE;- }- if (s.last_lit) {- /*** FLUSH_BLOCK(s, 0); ***/- flush_block_only(s, false);- if (s.strm.avail_out === 0) {- return BS_NEED_MORE;- }- /***/+// Calculate max possible position in utf8 buffer,+// that will not break sequence. If that's not possible+// - (very small limits) return max size as is.+//+// buf[] - utf8 bytes array+// max - length limit (mandatory);+exports.utf8border = function(buf, max) {+ var pos;++ max = max || buf.length;+ if (max > buf.length) { max = buf.length; }++ // go back from last position, until start of sequence found+ pos = max-1;+ while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }++ // Fuckup - very small and broken sequence,+ // return max, because we should return something anyway.+ if (pos < 0) { return max; }++ // If we came to start of buffer - that means vuffer is too small,+ // return max too.+ if (pos === 0) { return max; }++ return (pos + _utf8len[buf[pos]] > max) ? pos : max;+};++},{"./common":70}],72:[function(require,module,exports){+'use strict';++// Note: adler32 takes 12% for level 0 and 2% for level 6.+// It doesn't worth to make additional optimizationa as in original.+// Small size is preferable.++function adler32(adler, buf, len, pos) {+ var s1 = (adler & 0xffff) |0+ , s2 = ((adler >>> 16) & 0xffff) |0+ , n = 0;++ while (len !== 0) {+ // Set limit ~ twice less than 5552, to keep+ // s2 in 31-bits, because we force signed ints.+ // in other case %= will fail.+ n = len > 2000 ? 2000 : len;+ len -= n;++ do {+ s1 = (s1 + buf[pos++]) |0;+ s2 = (s2 + s1) |0;+ } while (--n);++ s1 %= 65521;+ s2 %= 65521;}- return BS_BLOCK_DONE;++ return (s1 | (s2 << 16)) |0;}-/* Values for max_lazy_match, good_match and max_chain_length, depending on- * the desired pack level (0..9). The values given below have been tuned to- * exclude worst case performance for pathological files. Better values may be- * found for specific files.- */-var Config = function (good_length, max_lazy, nice_length, max_chain, func) {- this.good_length = good_length;- this.max_lazy = max_lazy;- this.nice_length = nice_length;- this.max_chain = max_chain;- this.func = func;-};-var configuration_table;+module.exports = adler32;+},{}],73:[function(require,module,exports){+module.exports = {-configuration_table = [- /* good lazy nice chain */- new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */- new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */- new Config(4, 5, 16, 8, deflate_fast), /* 2 */- new Config(4, 6, 32, 32, deflate_fast), /* 3 */+ /* Allowed flush values; see deflate() and inflate() below for details */+ Z_NO_FLUSH: 0,+ Z_PARTIAL_FLUSH: 1,+ Z_SYNC_FLUSH: 2,+ Z_FULL_FLUSH: 3,+ Z_FINISH: 4,+ Z_BLOCK: 5,+ Z_TREES: 6,- new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */- new Config(8, 16, 32, 32, deflate_slow), /* 5 */- new Config(8, 16, 128, 128, deflate_slow), /* 6 */- new Config(8, 32, 128, 256, deflate_slow), /* 7 */- new Config(32, 128, 258, 1024, deflate_slow), /* 8 */- new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */-];+ /* Return codes for the compression/decompression functions. Negative values+ * are errors, positive values are used for special but normal events.+ */+ Z_OK: 0,+ Z_STREAM_END: 1,+ Z_NEED_DICT: 2,+ Z_ERRNO: -1,+ Z_STREAM_ERROR: -2,+ Z_DATA_ERROR: -3,+ //Z_MEM_ERROR: -4,+ Z_BUF_ERROR: -5,+ //Z_VERSION_ERROR: -6,+ /* compression levels */+ Z_NO_COMPRESSION: 0,+ Z_BEST_SPEED: 1,+ Z_BEST_COMPRESSION: 9,+ Z_DEFAULT_COMPRESSION: -1,-/* ===========================================================================- * Initialize the "longest match" routines for a new zlib stream- */-function lm_init(s) {- s.window_size = 2 * s.w_size;- /*** CLEAR_HASH(s); ***/- zero(s.head); // Fill with NIL (= 0);+ Z_FILTERED: 1,+ Z_HUFFMAN_ONLY: 2,+ Z_RLE: 3,+ Z_FIXED: 4,+ Z_DEFAULT_STRATEGY: 0,- /* Set the default configuration parameters:- */- s.max_lazy_match = configuration_table[s.level].max_lazy;- s.good_match = configuration_table[s.level].good_length;- s.nice_match = configuration_table[s.level].nice_length;- s.max_chain_length = configuration_table[s.level].max_chain;+ /* Possible values of the data_type field (though see inflate()) */+ Z_BINARY: 0,+ Z_TEXT: 1,+ //Z_ASCII: 1, // = Z_TEXT (deprecated)+ Z_UNKNOWN: 2,- s.strstart = 0;- s.block_start = 0;- s.lookahead = 0;- s.insert = 0;- s.match_length = s.prev_length = MIN_MATCH - 1;- s.match_available = 0;- s.ins_h = 0;-}+ /* The deflate compression method */+ Z_DEFLATED: 8+ //Z_NULL: null // Use -1 or null inline, depending on var type+};+},{}],74:[function(require,module,exports){+'use strict';+// Note: we can't get significant speed boost here.+// So write code to minimize size - no pregenerated tables+// and array tools dependencies.-function DeflateState() {- this.strm = null; /* pointer back to this zlib stream */- this.status = 0; /* as the name implies */- this.pending_buf = null; /* output still pending */- this.pending_buf_size = 0; /* size of pending_buf */- this.pending_out = 0; /* next pending byte to output to the stream */- this.pending = 0; /* nb of bytes in the pending buffer */- this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */- this.gzhead = null; /* gzip header information to write */- this.gzindex = 0; /* where in extra, name, or comment */- this.method = Z_DEFLATED; /* can only be DEFLATED */- this.last_flush = -1; /* value of flush param for previous deflate call */- this.w_size = 0; /* LZ77 window size (32K by default) */- this.w_bits = 0; /* log2(w_size) (8..16) */- this.w_mask = 0; /* w_size - 1 */+// Use ordinary array, since untyped makes no boost here+function makeTable() {+ var c, table = [];- this.window = null;- /* Sliding window. Input bytes are read into the second half of the window,- * and move to the first half later to keep a dictionary of at least wSize- * bytes. With this organization, matches are limited to a distance of- * wSize-MAX_MATCH bytes, but this ensures that IO is always- * performed with a length multiple of the block size.- */+ for(var n =0; n < 256; n++){+ c = n;+ for(var k =0; k < 8; k++){+ c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));+ }+ table[n] = c;+ }- this.window_size = 0;- /* Actual size of window: 2*wSize, except when the user input buffer- * is directly used as sliding window.- */+ return table;+}- this.prev = null;- /* Link to older string with same hash index. To limit the size of this- * array to 64K, this link is maintained only for the last 32K strings.- * An index in this array is thus a window index modulo 32K.- */+// Create table on load. Just 255 signed longs. Not a problem.+var crcTable = makeTable();- this.head = null; /* Heads of the hash chains or NIL. */- this.ins_h = 0; /* hash index of string to be inserted */- this.hash_size = 0; /* number of elements in hash table */- this.hash_bits = 0; /* log2(hash_size) */- this.hash_mask = 0; /* hash_size-1 */+function crc32(crc, buf, len, pos) {+ var t = crcTable+ , end = pos + len;- this.hash_shift = 0;- /* Number of bits by which ins_h must be shifted at each input- * step. It must be such that after MIN_MATCH steps, the oldest- * byte no longer takes part in the hash key, that is:- * hash_shift * MIN_MATCH >= hash_bits- */+ crc = crc ^ (-1);- this.block_start = 0;- /* Window position at the beginning of the current output block. Gets- * negative when the window is moved backwards.- */+ for (var i = pos; i < end; i++ ) {+ crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];+ }- this.match_length = 0; /* length of best match */- this.prev_match = 0; /* previous match */- this.match_available = 0; /* set if previous match exists */- this.strstart = 0; /* start of string to insert */- this.match_start = 0; /* start of matching string */- this.lookahead = 0; /* number of valid bytes ahead in window */+ return (crc ^ (-1)); // >>> 0;+}- this.prev_length = 0;- /* Length of the best match at previous step. Matches not greater than this- * are discarded. This is used in the lazy match evaluation.- */- this.max_chain_length = 0;- /* To speed up deflation, hash chains are never searched beyond this- * length. A higher limit improves compression ratio but degrades the- * speed.- */+module.exports = crc32;+},{}],75:[function(require,module,exports){+'use strict';- this.max_lazy_match = 0;- /* Attempt to find a better match only when the current match is strictly- * smaller than this value. This mechanism is used only for compression- * levels >= 4.- */- // That's alias to max_lazy_match, don't use directly- //this.max_insert_length = 0;- /* Insert new strings in the hash table only if the match length is not- * greater than this length. This saves time but degrades compression.- * max_insert_length is used only for compression levels <= 3.- */+var utils = require('../utils/common');+var trees = require('./trees');+var adler32 = require('./adler32');+var crc32 = require('./crc32');+var msg = require('./messages');- this.level = 0; /* compression level (1..9) */- this.strategy = 0; /* favor or force Huffman coding*/+/* Public constants ==========================================================*/+/* ===========================================================================*/+++/* Allowed flush values; see deflate() and inflate() below for details */+var Z_NO_FLUSH = 0;+var Z_PARTIAL_FLUSH = 1;+//var Z_SYNC_FLUSH = 2;+var Z_FULL_FLUSH = 3;+var Z_FINISH = 4;+var Z_BLOCK = 5;+//var Z_TREES = 6;+++/* Return codes for the compression/decompression functions. Negative values+ * are errors, positive values are used for special but normal events.+ */+var Z_OK = 0;+var Z_STREAM_END = 1;+//var Z_NEED_DICT = 2;+//var Z_ERRNO = -1;+var Z_STREAM_ERROR = -2;+var Z_DATA_ERROR = -3;+//var Z_MEM_ERROR = -4;+var Z_BUF_ERROR = -5;+//var Z_VERSION_ERROR = -6;- this.good_match = 0;- /* Use a faster search when the previous match is longer than this */- this.nice_match = 0; /* Stop searching when current match exceeds this */+/* compression levels */+//var Z_NO_COMPRESSION = 0;+//var Z_BEST_SPEED = 1;+//var Z_BEST_COMPRESSION = 9;+var Z_DEFAULT_COMPRESSION = -1;- /* used by trees.c: */- /* Didn't use ct_data typedef below to suppress compiler warning */+var Z_FILTERED = 1;+var Z_HUFFMAN_ONLY = 2;+var Z_RLE = 3;+var Z_FIXED = 4;+var Z_DEFAULT_STRATEGY = 0;- // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */- // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */- // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */+/* Possible values of the data_type field (though see inflate()) */+//var Z_BINARY = 0;+//var Z_TEXT = 1;+//var Z_ASCII = 1; // = Z_TEXT+var Z_UNKNOWN = 2;- // Use flat array of DOUBLE size, with interleaved fata,- // because JS does not support effective- this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);- this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);- this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);- zero(this.dyn_ltree);- zero(this.dyn_dtree);- zero(this.bl_tree);- this.l_desc = null; /* desc. for literal tree */- this.d_desc = null; /* desc. for distance tree */- this.bl_desc = null; /* desc. for bit length tree */+/* The deflate compression method */+var Z_DEFLATED = 8;- //ush bl_count[MAX_BITS+1];- this.bl_count = new utils.Buf16(MAX_BITS+1);- /* number of codes at each bit length for an optimal tree */+/*============================================================================*/- //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */- this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */- zero(this.heap);- this.heap_len = 0; /* number of elements in the heap */- this.heap_max = 0; /* element of largest frequency */- /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.- * The same heap array is used to build all trees.- */+var MAX_MEM_LEVEL = 9;+/* Maximum value for memLevel in deflateInit2 */+var MAX_WBITS = 15;+/* 32K LZ77 window */+var DEF_MEM_LEVEL = 8;- this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];- zero(this.depth);- /* Depth of each subtree used as tie breaker for trees of equal frequency- */- this.l_buf = 0; /* buffer index for literals or lengths */+var LENGTH_CODES = 29;+/* number of length codes, not counting the special END_BLOCK code */+var LITERALS = 256;+/* number of literal bytes 0..255 */+var L_CODES = LITERALS + 1 + LENGTH_CODES;+/* number of Literal or Length codes, including the END_BLOCK code */+var D_CODES = 30;+/* number of distance codes */+var BL_CODES = 19;+/* number of codes used to transfer the bit lengths */+var HEAP_SIZE = 2*L_CODES + 1;+/* maximum heap size */+var MAX_BITS = 15;+/* All codes must not exceed MAX_BITS bits */- this.lit_bufsize = 0;- /* Size of match buffer for literals/lengths. There are 4 reasons for- * limiting lit_bufsize to 64K:- * - frequencies can be kept in 16 bit counters- * - if compression is not successful for the first block, all input- * data is still in the window so we can still emit a stored block even- * when input comes from standard input. (This can also be done for- * all blocks if lit_bufsize is not greater than 32K.)- * - if compression is not successful for a file smaller than 64K, we can- * even emit a stored file instead of a stored block (saving 5 bytes).- * This is applicable only for zip (not gzip or zlib).- * - creating new Huffman trees less frequently may not provide fast- * adaptation to changes in the input data statistics. (Take for- * example a binary file with poorly compressible code followed by- * a highly compressible string table.) Smaller buffer sizes give- * fast adaptation but have of course the overhead of transmitting- * trees more frequently.- * - I can't count above 4- */+var MIN_MATCH = 3;+var MAX_MATCH = 258;+var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);- this.last_lit = 0; /* running index in l_buf */+var PRESET_DICT = 0x20;- this.d_buf = 0;- /* Buffer index for distances. To simplify the code, d_buf and l_buf have- * the same number of elements. To use different lengths, an extra flag- * array would be necessary.- */+var INIT_STATE = 42;+var EXTRA_STATE = 69;+var NAME_STATE = 73;+var COMMENT_STATE = 91;+var HCRC_STATE = 103;+var BUSY_STATE = 113;+var FINISH_STATE = 666;- this.opt_len = 0; /* bit length of current block with optimal trees */- this.static_len = 0; /* bit length of current block with static trees */- this.matches = 0; /* number of string matches in current block */- this.insert = 0; /* bytes at end of window left to insert */+var BS_NEED_MORE = 1; /* block not completed, need more input or more output */+var BS_BLOCK_DONE = 2; /* block flush performed */+var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */+var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */+var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.- this.bi_buf = 0;- /* Output buffer. bits are inserted starting at the bottom (least- * significant bits).- */- this.bi_valid = 0;- /* Number of valid bits in bi_buf. All bits above the last valid bit- * are always zero.- */+function err(strm, errorCode) {+ strm.msg = msg[errorCode];+ return errorCode;+}- // Used for window memory init. We safely ignore it for JS. That makes- // sense only for pointers and memory check tools.- //this.high_water = 0;- /* High water mark offset in window for initialized bytes -- bytes above- * this are set to zero in order to avoid memory check warnings when- * longest match routines access bytes past the input. This is then- * updated to the new high water mark.- */+function rank(f) {+ return ((f) << 1) - ((f) > 4 ? 9 : 0);}+function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }-function deflateResetKeep(strm) {- var s;- if (!strm || !strm.state) {- return err(strm, Z_STREAM_ERROR);+/* =========================================================================+ * Flush as much pending output as possible. All deflate() output goes+ * through this function so some applications may wish to modify it+ * to avoid allocating a large strm->output buffer and copying into it.+ * (See also read_buf()).+ */+function flush_pending(strm) {+ var s = strm.state;++ //_tr_flush_bits(s);+ var len = s.pending;+ if (len > strm.avail_out) {+ len = strm.avail_out;}+ if (len === 0) { return; }- strm.total_in = strm.total_out = 0;- strm.data_type = Z_UNKNOWN;+ utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);+ strm.next_out += len;+ s.pending_out += len;+ strm.total_out += len;+ strm.avail_out -= len;+ s.pending -= len;+ if (s.pending === 0) {+ s.pending_out = 0;+ }+}- s = strm.state;- s.pending = 0;- s.pending_out = 0;- if (s.wrap < 0) {- s.wrap = -s.wrap;- /* was made negative by deflate(..., Z_FINISH); */- }- s.status = (s.wrap ? INIT_STATE : BUSY_STATE);- strm.adler = (s.wrap === 2) ?- 0 // crc32(0, Z_NULL, 0)- :- 1; // adler32(0, Z_NULL, 0)- s.last_flush = Z_NO_FLUSH;- trees._tr_init(s);- return Z_OK;+function flush_block_only (s, last) {+ trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);+ s.block_start = s.strstart;+ flush_pending(s.strm);}-function deflateReset(strm) {- var ret = deflateResetKeep(strm);- if (ret === Z_OK) {- lm_init(strm.state);- }- return ret;+function put_byte(s, b) {+ s.pending_buf[s.pending++] = b;}-function deflateSetHeader(strm, head) {- if (!strm || !strm.state) { return Z_STREAM_ERROR; }- if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }- strm.state.gzhead = head;- return Z_OK;+/* =========================================================================+ * Put a short in the pending buffer. The 16-bit value is put in MSB order.+ * IN assertion: the stream state is correct and there is enough room in+ * pending_buf.+ */+function putShortMSB(s, b) {+// put_byte(s, (Byte)(b >> 8));+// put_byte(s, (Byte)(b & 0xff));+ s.pending_buf[s.pending++] = (b >>> 8) & 0xff;+ s.pending_buf[s.pending++] = b & 0xff;}-function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {- if (!strm) { // === Z_NULL- return Z_STREAM_ERROR;- }- var wrap = 1;+/* ===========================================================================+ * Read a new buffer from the current input stream, update the adler32+ * and total number of bytes read. All deflate() input goes through+ * this function so some applications may wish to modify it to avoid+ * allocating a large strm->input buffer and copying from it.+ * (See also flush_pending()).+ */+function read_buf(strm, buf, start, size) {+ var len = strm.avail_in;- if (level === Z_DEFAULT_COMPRESSION) {- level = 6;- }+ if (len > size) { len = size; }+ if (len === 0) { return 0; }- if (windowBits < 0) { /* suppress zlib wrapper */- wrap = 0;- windowBits = -windowBits;+ strm.avail_in -= len;++ utils.arraySet(buf, strm.input, strm.next_in, len, start);+ if (strm.state.wrap === 1) {+ strm.adler = adler32(strm.adler, buf, len, start);}- else if (windowBits > 15) {- wrap = 2; /* write gzip wrapper instead */- windowBits -= 16;+ else if (strm.state.wrap === 2) {+ strm.adler = crc32(strm.adler, buf, len, start);}+ strm.next_in += len;+ strm.total_in += len;++ return len;+}- if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||- windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||- strategy < 0 || strategy > Z_FIXED) {- return err(strm, Z_STREAM_ERROR);- }+/* ===========================================================================+ * Set match_start to the longest match starting at the given string and+ * return its length. Matches shorter or equal to prev_length are discarded,+ * in which case the result is equal to prev_length and match_start is+ * garbage.+ * IN assertions: cur_match is the head of the hash chain for the current+ * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1+ * OUT assertion: the match length is not greater than s->lookahead.+ */+function longest_match(s, cur_match) {+ var chain_length = s.max_chain_length; /* max hash chain length */+ var scan = s.strstart; /* current string */+ var match; /* matched string */+ var len; /* length of current match */+ var best_len = s.prev_length; /* best match length so far */+ var nice_match = s.nice_match; /* stop if match long enough */+ var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?+ s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;- if (windowBits === 8) {- windowBits = 9;- }- /* until 256-byte window bug fixed */+ var _win = s.window; // shortcut- var s = new DeflateState();+ var wmask = s.w_mask;+ var prev = s.prev;- strm.state = s;- s.strm = strm;+ /* Stop when cur_match becomes <= limit. To simplify the code,+ * we prevent matches with the string of window index 0.+ */- s.wrap = wrap;- s.gzhead = null;- s.w_bits = windowBits;- s.w_size = 1 << s.w_bits;- s.w_mask = s.w_size - 1;+ var strend = s.strstart + MAX_MATCH;+ var scan_end1 = _win[scan + best_len - 1];+ var scan_end = _win[scan + best_len];- s.hash_bits = memLevel + 7;- s.hash_size = 1 << s.hash_bits;- s.hash_mask = s.hash_size - 1;- s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);+ /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.+ * It is easy to get rid of this optimization if necessary.+ */+ // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");- s.window = new utils.Buf8(s.w_size * 2);- s.head = new utils.Buf16(s.hash_size);- s.prev = new utils.Buf16(s.w_size);+ /* Do not waste too much time if we already have a good match: */+ if (s.prev_length >= s.good_match) {+ chain_length >>= 2;+ }+ /* Do not look for matches beyond the end of the input. This is necessary+ * to make deflate deterministic.+ */+ if (nice_match > s.lookahead) { nice_match = s.lookahead; }- // Don't need mem init magic for JS.- //s.high_water = 0; /* nothing written to s->window yet */+ // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");- s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */+ do {+ // Assert(cur_match < s->strstart, "no future");+ match = cur_match;- s.pending_buf_size = s.lit_bufsize * 4;- s.pending_buf = new utils.Buf8(s.pending_buf_size);+ /* Skip to next match if the match length cannot increase+ * or if the match length is less than 2. Note that the checks below+ * for insufficient lookahead only occur occasionally for performance+ * reasons. Therefore uninitialized memory will be accessed, and+ * conditional jumps will be made that depend on those values.+ * However the length of the match is limited to the lookahead, so+ * the output of deflate is not affected by the uninitialized values.+ */- s.d_buf = s.lit_bufsize >> 1;- s.l_buf = (1 + 2) * s.lit_bufsize;+ if (_win[match + best_len] !== scan_end ||+ _win[match + best_len - 1] !== scan_end1 ||+ _win[match] !== _win[scan] ||+ _win[++match] !== _win[scan + 1]) {+ continue;+ }- s.level = level;- s.strategy = strategy;- s.method = method;+ /* The check at best_len-1 can be removed because it will be made+ * again later. (This heuristic is not always a win.)+ * It is not necessary to compare scan[2] and match[2] since they+ * are always equal when the other bytes match, given that+ * the hash keys are equal and that HASH_BITS >= 8.+ */+ scan += 2;+ match++;+ // Assert(*scan == *match, "match[2]?");- return deflateReset(strm);-}+ /* We check for insufficient lookahead only every 8th comparison;+ * the 256th check will be made at strstart+258.+ */+ do {+ /*jshint noempty:false*/+ } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&+ _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&+ _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&+ _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&+ scan < strend);-function deflateInit(strm, level) {- return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);-}+ // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");+ len = MAX_MATCH - (strend - scan);+ scan = strend - MAX_MATCH;-function deflate(strm, flush) {- var old_flush, s;- var beg, val; // for gzip header write only+ if (len > best_len) {+ s.match_start = cur_match;+ best_len = len;+ if (len >= nice_match) {+ break;+ }+ scan_end1 = _win[scan + best_len - 1];+ scan_end = _win[scan + best_len];+ }+ } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);- if (!strm || !strm.state ||- flush > Z_BLOCK || flush < 0) {- return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;+ if (best_len <= s.lookahead) {+ return best_len;}+ return s.lookahead;+}- s = strm.state;- if (!strm.output ||- (!strm.input && strm.avail_in !== 0) ||- (s.status === FINISH_STATE && flush !== Z_FINISH)) {- return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);- }+/* ===========================================================================+ * Fill the window when the lookahead becomes insufficient.+ * Updates strstart and lookahead.+ *+ * IN assertion: lookahead < MIN_LOOKAHEAD+ * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD+ * At least one byte has been read, or avail_in == 0; reads are+ * performed for at least two bytes (required for the zip translate_eol+ * option -- not supported here).+ */+function fill_window(s) {+ var _w_size = s.w_size;+ var p, n, m, more, str;- s.strm = strm; /* just in case */- old_flush = s.last_flush;- s.last_flush = flush;+ //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");- /* Write the header */- if (s.status === INIT_STATE) {+ do {+ more = s.window_size - s.lookahead - s.strstart;- if (s.wrap === 2) { // GZIP header- strm.adler = 0; //crc32(0L, Z_NULL, 0);- put_byte(s, 31);- put_byte(s, 139);- put_byte(s, 8);- if (!s.gzhead) { // s->gzhead == Z_NULL- put_byte(s, 0);- put_byte(s, 0);- put_byte(s, 0);- put_byte(s, 0);- put_byte(s, 0);- put_byte(s, s.level === 9 ? 2 :- (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?- 4 : 0));- put_byte(s, OS_CODE);- s.status = BUSY_STATE;- }- else {- put_byte(s, (s.gzhead.text ? 1 : 0) +- (s.gzhead.hcrc ? 2 : 0) +- (!s.gzhead.extra ? 0 : 4) +- (!s.gzhead.name ? 0 : 8) +- (!s.gzhead.comment ? 0 : 16)- );- put_byte(s, s.gzhead.time & 0xff);- put_byte(s, (s.gzhead.time >> 8) & 0xff);- put_byte(s, (s.gzhead.time >> 16) & 0xff);- put_byte(s, (s.gzhead.time >> 24) & 0xff);- put_byte(s, s.level === 9 ? 2 :- (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?- 4 : 0));- put_byte(s, s.gzhead.os & 0xff);- if (s.gzhead.extra && s.gzhead.extra.length) {- put_byte(s, s.gzhead.extra.length & 0xff);- put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);- }- if (s.gzhead.hcrc) {- strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);- }- s.gzindex = 0;- s.status = EXTRA_STATE;- }- }- else // DEFLATE header- {- var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;- var level_flags = -1;+ // JS ints have 32 bit, block below not needed+ /* Deal with !@#$% 64K limit: */+ //if (sizeof(int) <= 2) {+ // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {+ // more = wsize;+ //+ // } else if (more == (unsigned)(-1)) {+ // /* Very unlikely, but possible on 16 bit machine if+ // * strstart == 0 && lookahead == 1 (input done a byte at time)+ // */+ // more--;+ // }+ //}- if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {- level_flags = 0;- } else if (s.level < 6) {- level_flags = 1;- } else if (s.level === 6) {- level_flags = 2;- } else {- level_flags = 3;- }- header |= (level_flags << 6);- if (s.strstart !== 0) { header |= PRESET_DICT; }- header += 31 - (header % 31);- s.status = BUSY_STATE;- putShortMSB(s, header);+ /* If the window is almost full and there is insufficient lookahead,+ * move the upper half to the lower one to make room in the upper half.+ */+ if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {- /* Save the adler32 of the preset dictionary: */- if (s.strstart !== 0) {- putShortMSB(s, strm.adler >>> 16);- putShortMSB(s, strm.adler & 0xffff);- }- strm.adler = 1; // adler32(0L, Z_NULL, 0);- }- }+ utils.arraySet(s.window, s.window, _w_size, _w_size, 0);+ s.match_start -= _w_size;+ s.strstart -= _w_size;+ /* we now have strstart >= MAX_DIST */+ s.block_start -= _w_size;-//#ifdef GZIP- if (s.status === EXTRA_STATE) {- if (s.gzhead.extra/* != Z_NULL*/) {- beg = s.pending; /* start of bytes to update crc */+ /* Slide the hash table (could be avoided with 32 bit values+ at the expense of memory usage). We slide even when level == 0+ to keep the hash table consistent if we switch back to level > 0+ later. (Using level 0 permanently is not an optimal usage of+ zlib, so we don't care about this pathological case.)+ */- while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {- if (s.pending === s.pending_buf_size) {- if (s.gzhead.hcrc && s.pending > beg) {- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);- }- flush_pending(strm);- beg = s.pending;- if (s.pending === s.pending_buf_size) {- break;- }- }- put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);- s.gzindex++;- }- if (s.gzhead.hcrc && s.pending > beg) {- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);- }- if (s.gzindex === s.gzhead.extra.length) {- s.gzindex = 0;- s.status = NAME_STATE;- }- }- else {- s.status = NAME_STATE;- }- }- if (s.status === NAME_STATE) {- if (s.gzhead.name/* != Z_NULL*/) {- beg = s.pending; /* start of bytes to update crc */- //int val;+ n = s.hash_size;+ p = n;+ do {+ m = s.head[--p];+ s.head[p] = (m >= _w_size ? m - _w_size : 0);+ } while (--n);+ n = _w_size;+ p = n;do {- if (s.pending === s.pending_buf_size) {- if (s.gzhead.hcrc && s.pending > beg) {- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);- }- flush_pending(strm);- beg = s.pending;- if (s.pending === s.pending_buf_size) {- val = 1;- break;- }- }- // JS specific: little magic to add zero terminator to end of string- if (s.gzindex < s.gzhead.name.length) {- val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;- } else {- val = 0;- }- put_byte(s, val);- } while (val !== 0);+ m = s.prev[--p];+ s.prev[p] = (m >= _w_size ? m - _w_size : 0);+ /* If n is not on any hash chain, prev[n] is garbage but+ * its value will never be used.+ */+ } while (--n);- if (s.gzhead.hcrc && s.pending > beg){- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);- }- if (val === 0) {- s.gzindex = 0;- s.status = COMMENT_STATE;- }+ more += _w_size;}- else {- s.status = COMMENT_STATE;+ if (s.strm.avail_in === 0) {+ break;}- }- if (s.status === COMMENT_STATE) {- if (s.gzhead.comment/* != Z_NULL*/) {- beg = s.pending; /* start of bytes to update crc */- //int val;- do {- if (s.pending === s.pending_buf_size) {- if (s.gzhead.hcrc && s.pending > beg) {- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);- }- flush_pending(strm);- beg = s.pending;- if (s.pending === s.pending_buf_size) {- val = 1;- break;- }- }- // JS specific: little magic to add zero terminator to end of string- if (s.gzindex < s.gzhead.comment.length) {- val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;- } else {- val = 0;- }- put_byte(s, val);- } while (val !== 0);+ /* If there was no sliding:+ * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&+ * more == window_size - lookahead - strstart+ * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)+ * => more >= window_size - 2*WSIZE + 2+ * In the BIG_MEM or MMAP case (not yet supported),+ * window_size == input_size + MIN_LOOKAHEAD &&+ * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.+ * Otherwise, window_size == 2*WSIZE so more >= 2.+ * If there was sliding, more >= WSIZE. So in all cases, more >= 2.+ */+ //Assert(more >= 2, "more < 2");+ n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);+ s.lookahead += n;- if (s.gzhead.hcrc && s.pending > beg) {- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);- }- if (val === 0) {- s.status = HCRC_STATE;- }- }- else {- s.status = HCRC_STATE;- }- }- if (s.status === HCRC_STATE) {- if (s.gzhead.hcrc) {- if (s.pending + 2 > s.pending_buf_size) {- flush_pending(strm);- }- if (s.pending + 2 <= s.pending_buf_size) {- put_byte(s, strm.adler & 0xff);- put_byte(s, (strm.adler >> 8) & 0xff);- strm.adler = 0; //crc32(0L, Z_NULL, 0);- s.status = BUSY_STATE;- }- }- else {- s.status = BUSY_STATE;- }- }+ /* Initialize the hash value now that we have some input: */+ if (s.lookahead + s.insert >= MIN_MATCH) {+ str = s.strstart - s.insert;+ s.ins_h = s.window[str];++ /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */+ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;+//#if MIN_MATCH != 3+// Call update_hash() MIN_MATCH-3 more times//#endif+ while (s.insert) {+ /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */+ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;- /* Flush as much pending output as possible */- if (s.pending !== 0) {- flush_pending(strm);- if (strm.avail_out === 0) {- /* Since avail_out is 0, deflate will be called again with- * more output space, but possibly with both pending and- * avail_in equal to zero. There won't be anything to do,- * but this is not an error situation so make sure we- * return OK instead of BUF_ERROR at next call of deflate:- */- s.last_flush = -1;- return Z_OK;+ s.prev[str & s.w_mask] = s.head[s.ins_h];+ s.head[s.ins_h] = str;+ str++;+ s.insert--;+ if (s.lookahead + s.insert < MIN_MATCH) {+ break;+ }+ }}-- /* Make sure there is something to do and avoid duplicate consecutive- * flushes. For repeated and useless calls with Z_FINISH, we keep- * returning Z_STREAM_END instead of Z_BUF_ERROR.+ /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,+ * but this is not important since only literal bytes will be emitted.*/- } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&- flush !== Z_FINISH) {- return err(strm, Z_BUF_ERROR);- }- /* User must not provide more input after the first FINISH: */- if (s.status === FINISH_STATE && strm.avail_in !== 0) {- return err(strm, Z_BUF_ERROR);+ } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);++ /* If the WIN_INIT bytes after the end of the current data have never been+ * written, then zero those bytes in order to avoid memory check reports of+ * the use of uninitialized (or uninitialised as Julian writes) bytes by+ * the longest match routines. Update the high water mark for the next+ * time through here. WIN_INIT is set to MAX_MATCH since the longest match+ * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.+ */+// if (s.high_water < s.window_size) {+// var curr = s.strstart + s.lookahead;+// var init = 0;+//+// if (s.high_water < curr) {+// /* Previous high water mark below current data -- zero WIN_INIT+// * bytes or up to end of window, whichever is less.+// */+// init = s.window_size - curr;+// if (init > WIN_INIT)+// init = WIN_INIT;+// zmemzero(s->window + curr, (unsigned)init);+// s->high_water = curr + init;+// }+// else if (s->high_water < (ulg)curr + WIN_INIT) {+// /* High water mark at or above current data, but below current data+// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up+// * to end of window, whichever is less.+// */+// init = (ulg)curr + WIN_INIT - s->high_water;+// if (init > s->window_size - s->high_water)+// init = s->window_size - s->high_water;+// zmemzero(s->window + s->high_water, (unsigned)init);+// s->high_water += init;+// }+// }+//+// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,+// "not enough room for search");+}++/* ===========================================================================+ * Copy without compression as much as possible from the input stream, return+ * the current block state.+ * This function does not insert new strings in the dictionary since+ * uncompressible data is probably not useful. This function is used+ * only for the level=0 compression option.+ * NOTE: this function should be optimized to avoid extra copying from+ * window to pending_buf.+ */+function deflate_stored(s, flush) {+ /* Stored blocks are limited to 0xffff bytes, pending_buf is limited+ * to pending_buf_size, and each stored block has a 5 byte header:+ */+ var max_block_size = 0xffff;++ if (max_block_size > s.pending_buf_size - 5) {+ max_block_size = s.pending_buf_size - 5;}- /* Start a new block or continue the current one.- */- if (strm.avail_in !== 0 || s.lookahead !== 0 ||- (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {- var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :- (s.strategy === Z_RLE ? deflate_rle(s, flush) :- configuration_table[s.level].func(s, flush));-- if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {- s.status = FINISH_STATE;- }- if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {- if (strm.avail_out === 0) {- s.last_flush = -1;- /* avoid BUF_ERROR next call, see above */- }- return Z_OK;- /* If flush != Z_NO_FLUSH && avail_out == 0, the next call- * of deflate should use the same flush parameter to make sure- * that the flush is complete. So we don't have to output an- * empty block here, this will be done at next call. This also- * ensures that for a very small output buffer, we emit at most- * one empty block.- */- }- if (bstate === BS_BLOCK_DONE) {- if (flush === Z_PARTIAL_FLUSH) {- trees._tr_align(s);- }- else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */+ /* Copy as much as possible from input to output: */+ for (;;) {+ /* Fill the window as much as possible: */+ if (s.lookahead <= 1) {- trees._tr_stored_block(s, 0, 0, false);- /* For a full flush, this empty block will be recognized- * as a special marker by inflate_sync().- */- if (flush === Z_FULL_FLUSH) {- /*** CLEAR_HASH(s); ***/ /* forget history */- zero(s.head); // Fill with NIL (= 0);+ //Assert(s->strstart < s->w_size+MAX_DIST(s) ||+ // s->block_start >= (long)s->w_size, "slide too late");+// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||+// s.block_start >= s.w_size)) {+// throw new Error("slide too late");+// }- if (s.lookahead === 0) {- s.strstart = 0;- s.block_start = 0;- s.insert = 0;- }- }+ fill_window(s);+ if (s.lookahead === 0 && flush === Z_NO_FLUSH) {+ return BS_NEED_MORE;}- flush_pending(strm);- if (strm.avail_out === 0) {- s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */- return Z_OK;++ if (s.lookahead === 0) {+ break;}+ /* flush the current block */}- }- //Assert(strm->avail_out > 0, "bug2");- //if (strm.avail_out <= 0) { throw new Error("bug2");}+ //Assert(s->block_start >= 0L, "block gone");+// if (s.block_start < 0) throw new Error("block gone");- if (flush !== Z_FINISH) { return Z_OK; }- if (s.wrap <= 0) { return Z_STREAM_END; }+ s.strstart += s.lookahead;+ s.lookahead = 0;- /* Write the trailer */- if (s.wrap === 2) {- put_byte(s, strm.adler & 0xff);- put_byte(s, (strm.adler >> 8) & 0xff);- put_byte(s, (strm.adler >> 16) & 0xff);- put_byte(s, (strm.adler >> 24) & 0xff);- put_byte(s, strm.total_in & 0xff);- put_byte(s, (strm.total_in >> 8) & 0xff);- put_byte(s, (strm.total_in >> 16) & 0xff);- put_byte(s, (strm.total_in >> 24) & 0xff);- }- else- {- putShortMSB(s, strm.adler >>> 16);- putShortMSB(s, strm.adler & 0xffff);- }+ /* Emit a stored block if pending_buf will be full: */+ var max_start = s.block_start + max_block_size;- flush_pending(strm);- /* If avail_out is zero, the application will call deflate again- * to flush the rest.- */- if (s.wrap > 0) { s.wrap = -s.wrap; }- /* write the trailer only once! */- return s.pending !== 0 ? Z_OK : Z_STREAM_END;-}+ if (s.strstart === 0 || s.strstart >= max_start) {+ /* strstart == 0 is possible when wraparound on 16-bit machine */+ s.lookahead = s.strstart - max_start;+ s.strstart = max_start;+ /*** FLUSH_BLOCK(s, 0); ***/+ flush_block_only(s, false);+ if (s.strm.avail_out === 0) {+ return BS_NEED_MORE;+ }+ /***/-function deflateEnd(strm) {- var status;- if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {- return Z_STREAM_ERROR;+ }+ /* Flush if we may have to slide, otherwise block_start may become+ * negative and the data will be gone:+ */+ if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {+ /*** FLUSH_BLOCK(s, 0); ***/+ flush_block_only(s, false);+ if (s.strm.avail_out === 0) {+ return BS_NEED_MORE;+ }+ /***/+ }}- status = strm.state.status;- if (status !== INIT_STATE &&- status !== EXTRA_STATE &&- status !== NAME_STATE &&- status !== COMMENT_STATE &&- status !== HCRC_STATE &&- status !== BUSY_STATE &&- status !== FINISH_STATE- ) {- return err(strm, Z_STREAM_ERROR);+ s.insert = 0;++ if (flush === Z_FINISH) {+ /*** FLUSH_BLOCK(s, 1); ***/+ flush_block_only(s, true);+ if (s.strm.avail_out === 0) {+ return BS_FINISH_STARTED;+ }+ /***/+ return BS_FINISH_DONE;}- strm.state = null;+ if (s.strstart > s.block_start) {+ /*** FLUSH_BLOCK(s, 0); ***/+ flush_block_only(s, false);+ if (s.strm.avail_out === 0) {+ return BS_NEED_MORE;+ }+ /***/+ }- return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;+ return BS_NEED_MORE;}-/* =========================================================================- * Copy the source state to the destination state+/* ===========================================================================+ * Compress as much as possible from the input stream, return the current+ * block state.+ * This function does not perform lazy evaluation of matches and inserts+ * new strings in the dictionary only for unmatched strings or for short+ * matches. It is used only for the fast compression options.*/-//function deflateCopy(dest, source) {-//-//}+function deflate_fast(s, flush) {+ var hash_head; /* head of the hash chain */+ var bflush; /* set if current block must be flushed */-exports.deflateInit = deflateInit;-exports.deflateInit2 = deflateInit2;-exports.deflateReset = deflateReset;-exports.deflateResetKeep = deflateResetKeep;-exports.deflateSetHeader = deflateSetHeader;-exports.deflate = deflate;-exports.deflateEnd = deflateEnd;-exports.deflateInfo = 'pako deflate (from Nodeca project)';+ for (;;) {+ /* Make sure that we always have enough lookahead, except+ * at the end of the input file. We need MAX_MATCH bytes+ * for the next match, plus MIN_MATCH bytes to insert the+ * string following the next match.+ */+ if (s.lookahead < MIN_LOOKAHEAD) {+ fill_window(s);+ if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {+ return BS_NEED_MORE;+ }+ if (s.lookahead === 0) {+ break; /* flush the current block */+ }+ }-/* Not implemented-exports.deflateBound = deflateBound;-exports.deflateCopy = deflateCopy;-exports.deflateSetDictionary = deflateSetDictionary;-exports.deflateParams = deflateParams;-exports.deflatePending = deflatePending;-exports.deflatePrime = deflatePrime;-exports.deflateTune = deflateTune;-*/-},{"../utils/common":69,"./adler32":71,"./crc32":73,"./messages":79,"./trees":80}],75:[function(require,module,exports){-'use strict';+ /* Insert the string window[strstart .. strstart+2] in the+ * dictionary, and set hash_head to the head of the hash chain:+ */+ hash_head = 0/*NIL*/;+ if (s.lookahead >= MIN_MATCH) {+ /*** INSERT_STRING(s, s.strstart, hash_head); ***/+ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;+ hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];+ s.head[s.ins_h] = s.strstart;+ /***/+ }++ /* Find the longest match, discarding those <= prev_length.+ * At this point we have always match_length < MIN_MATCH+ */+ if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {+ /* To simplify the code, we prevent matches with the string+ * of window index 0 (in particular we have to avoid a match+ * of the string with itself at the start of the input file).+ */+ s.match_length = longest_match(s, hash_head);+ /* longest_match() sets match_start */+ }+ if (s.match_length >= MIN_MATCH) {+ // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only+ /*** _tr_tally_dist(s, s.strstart - s.match_start,+ s.match_length - MIN_MATCH, bflush); ***/+ bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);-function GZheader() {- /* true if compressed data believed to be text */- this.text = 0;- /* modification time */- this.time = 0;- /* extra flags (not used when writing a gzip file) */- this.xflags = 0;- /* operating system */- this.os = 0;- /* pointer to extra field or Z_NULL if none */- this.extra = null;- /* extra field length (valid if extra != Z_NULL) */- this.extra_len = 0; // Actually, we don't need it in JS,- // but leave for few code modifications+ s.lookahead -= s.match_length;++ /* Insert new strings in the hash table only if the match length+ * is not too large. This saves time but degrades compression.+ */+ if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {+ s.match_length--; /* string at strstart already in table */+ do {+ s.strstart++;+ /*** INSERT_STRING(s, s.strstart, hash_head); ***/+ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;+ hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];+ s.head[s.ins_h] = s.strstart;+ /***/+ /* strstart never exceeds WSIZE-MAX_MATCH, so there are+ * always MIN_MATCH bytes ahead.+ */+ } while (--s.match_length !== 0);+ s.strstart++;+ } else+ {+ s.strstart += s.match_length;+ s.match_length = 0;+ s.ins_h = s.window[s.strstart];+ /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */+ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;- //- // Setup limits is not necessary because in js we should not preallocate memory- // for inflate use constant limit in 65536 bytes- //+//#if MIN_MATCH != 3+// Call UPDATE_HASH() MIN_MATCH-3 more times+//#endif+ /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not+ * matter since it will be recomputed at next deflate call.+ */+ }+ } else {+ /* No match, output a literal byte */+ //Tracevv((stderr,"%c", s.window[s.strstart]));+ /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/+ bflush = trees._tr_tally(s, 0, s.window[s.strstart]);- /* space at extra (only when reading header) */- // this.extra_max = 0;- /* pointer to zero-terminated file name or Z_NULL */- this.name = '';- /* space at name (only when reading header) */- // this.name_max = 0;- /* pointer to zero-terminated comment or Z_NULL */- this.comment = '';- /* space at comment (only when reading header) */- // this.comm_max = 0;- /* true if there was or will be a header crc */- this.hcrc = 0;- /* true when done reading gzip header (not used when writing a gzip file) */- this.done = false;+ s.lookahead--;+ s.strstart++;+ }+ if (bflush) {+ /*** FLUSH_BLOCK(s, 0); ***/+ flush_block_only(s, false);+ if (s.strm.avail_out === 0) {+ return BS_NEED_MORE;+ }+ /***/+ }+ }+ s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);+ if (flush === Z_FINISH) {+ /*** FLUSH_BLOCK(s, 1); ***/+ flush_block_only(s, true);+ if (s.strm.avail_out === 0) {+ return BS_FINISH_STARTED;+ }+ /***/+ return BS_FINISH_DONE;+ }+ if (s.last_lit) {+ /*** FLUSH_BLOCK(s, 0); ***/+ flush_block_only(s, false);+ if (s.strm.avail_out === 0) {+ return BS_NEED_MORE;+ }+ /***/+ }+ return BS_BLOCK_DONE;}-module.exports = GZheader;-},{}],76:[function(require,module,exports){-'use strict';--// See state defs from inflate.js-var BAD = 30; /* got a data error -- remain here until reset */-var TYPE = 12; /* i: waiting for type bits, including last-flag bit */--/*- Decode literal, length, and distance codes and write out the resulting- literal and match bytes until either not enough input or output is- available, an end-of-block is encountered, or a data error is encountered.- When large enough input and output buffers are supplied to inflate(), for- example, a 16K input buffer and a 64K output buffer, more than 95% of the- inflate execution time is spent in this routine.+/* ===========================================================================+ * Same as above, but achieves better compression. We use a lazy+ * evaluation for matches: a match is finally adopted only if there is+ * no better match at the next window position.+ */+function deflate_slow(s, flush) {+ var hash_head; /* head of hash chain */+ var bflush; /* set if current block must be flushed */- Entry assumptions:+ var max_insert;- state.mode === LEN- strm.avail_in >= 6- strm.avail_out >= 258- start >= strm.avail_out- state.bits < 8+ /* Process the input block. */+ for (;;) {+ /* Make sure that we always have enough lookahead, except+ * at the end of the input file. We need MAX_MATCH bytes+ * for the next match, plus MIN_MATCH bytes to insert the+ * string following the next match.+ */+ if (s.lookahead < MIN_LOOKAHEAD) {+ fill_window(s);+ if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {+ return BS_NEED_MORE;+ }+ if (s.lookahead === 0) { break; } /* flush the current block */+ }- On return, state.mode is one of:+ /* Insert the string window[strstart .. strstart+2] in the+ * dictionary, and set hash_head to the head of the hash chain:+ */+ hash_head = 0/*NIL*/;+ if (s.lookahead >= MIN_MATCH) {+ /*** INSERT_STRING(s, s.strstart, hash_head); ***/+ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;+ hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];+ s.head[s.ins_h] = s.strstart;+ /***/+ }- LEN -- ran out of enough output space or enough available input- TYPE -- reached end of block code, inflate() to interpret next block- BAD -- error in block data+ /* Find the longest match, discarding those <= prev_length.+ */+ s.prev_length = s.match_length;+ s.prev_match = s.match_start;+ s.match_length = MIN_MATCH-1;- Notes:+ if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&+ s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {+ /* To simplify the code, we prevent matches with the string+ * of window index 0 (in particular we have to avoid a match+ * of the string with itself at the start of the input file).+ */+ s.match_length = longest_match(s, hash_head);+ /* longest_match() sets match_start */- - The maximum input bits used by a length/distance pair is 15 bits for the- length code, 5 bits for the length extra, 15 bits for the distance code,- and 13 bits for the distance extra. This totals 48 bits, or six bytes.- Therefore if strm.avail_in >= 6, then there is enough input to avoid- checking for available input while decoding.+ if (s.match_length <= 5 &&+ (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {- - The maximum bytes that a single length/distance pair can output is 258- bytes, which is the maximum length that can be coded. inflate_fast()- requires strm.avail_out >= 258 for each loop to avoid checking for- output space.- */-module.exports = function inflate_fast(strm, start) {- var state;- var _in; /* local strm.input */- var last; /* have enough input while in < last */- var _out; /* local strm.output */- var beg; /* inflate()'s initial strm.output */- var end; /* while out < end, enough space available */-//#ifdef INFLATE_STRICT- var dmax; /* maximum distance from zlib header */-//#endif- var wsize; /* window size or zero if not using window */- var whave; /* valid bytes in the window */- var wnext; /* window write index */- var window; /* allocated sliding window, if wsize != 0 */- var hold; /* local strm.hold */- var bits; /* local strm.bits */- var lcode; /* local strm.lencode */- var dcode; /* local strm.distcode */- var lmask; /* mask for first level of length codes */- var dmask; /* mask for first level of distance codes */- var here; /* retrieved table entry */- var op; /* code bits, operation, extra bits, or */- /* window position, window bytes to copy */- var len; /* match length, unused bytes */- var dist; /* match distance */- var from; /* where to copy match from */- var from_source;+ /* If prev_match is also MIN_MATCH, match_start is garbage+ * but we will ignore the current match anyway.+ */+ s.match_length = MIN_MATCH-1;+ }+ }+ /* If there was a match at the previous step and the current+ * match is not better, output the previous match:+ */+ if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {+ max_insert = s.strstart + s.lookahead - MIN_MATCH;+ /* Do not insert strings in hash table beyond this. */+ //check_match(s, s.strstart-1, s.prev_match, s.prev_length);- var input, output; // JS specific, because we have no pointers+ /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,+ s.prev_length - MIN_MATCH, bflush);***/+ bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);+ /* Insert in hash table all strings up to the end of the match.+ * strstart-1 and strstart are already inserted. If there is not+ * enough lookahead, the last two strings are not inserted in+ * the hash table.+ */+ s.lookahead -= s.prev_length-1;+ s.prev_length -= 2;+ do {+ if (++s.strstart <= max_insert) {+ /*** INSERT_STRING(s, s.strstart, hash_head); ***/+ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;+ hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];+ s.head[s.ins_h] = s.strstart;+ /***/+ }+ } while (--s.prev_length !== 0);+ s.match_available = 0;+ s.match_length = MIN_MATCH-1;+ s.strstart++;- /* copy state to local variables */- state = strm.state;- //here = state.here;- _in = strm.next_in;- input = strm.input;- last = _in + (strm.avail_in - 5);- _out = strm.next_out;- output = strm.output;- beg = _out - (start - strm.avail_out);- end = _out + (strm.avail_out - 257);-//#ifdef INFLATE_STRICT- dmax = state.dmax;-//#endif- wsize = state.wsize;- whave = state.whave;- wnext = state.wnext;- window = state.window;- hold = state.hold;- bits = state.bits;- lcode = state.lencode;- dcode = state.distcode;- lmask = (1 << state.lenbits) - 1;- dmask = (1 << state.distbits) - 1;+ if (bflush) {+ /*** FLUSH_BLOCK(s, 0); ***/+ flush_block_only(s, false);+ if (s.strm.avail_out === 0) {+ return BS_NEED_MORE;+ }+ /***/+ }+ } else if (s.match_available) {+ /* If there was no match at the previous position, output a+ * single literal. If there was a match but the current match+ * is longer, truncate the previous match to a single literal.+ */+ //Tracevv((stderr,"%c", s->window[s->strstart-1]));+ /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/+ bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);- /* decode literals and length/distances until end-of-block or not enough- input data or output space */+ if (bflush) {+ /*** FLUSH_BLOCK_ONLY(s, 0) ***/+ flush_block_only(s, false);+ /***/+ }+ s.strstart++;+ s.lookahead--;+ if (s.strm.avail_out === 0) {+ return BS_NEED_MORE;+ }+ } else {+ /* There is no previous match to compare with, wait for+ * the next step to decide.+ */+ s.match_available = 1;+ s.strstart++;+ s.lookahead--;+ }+ }+ //Assert (flush != Z_NO_FLUSH, "no flush?");+ if (s.match_available) {+ //Tracevv((stderr,"%c", s->window[s->strstart-1]));+ /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/+ bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);- top:- do {- if (bits < 15) {- hold += input[_in++] << bits;- bits += 8;- hold += input[_in++] << bits;- bits += 8;+ s.match_available = 0;+ }+ s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;+ if (flush === Z_FINISH) {+ /*** FLUSH_BLOCK(s, 1); ***/+ flush_block_only(s, true);+ if (s.strm.avail_out === 0) {+ return BS_FINISH_STARTED;}+ /***/+ return BS_FINISH_DONE;+ }+ if (s.last_lit) {+ /*** FLUSH_BLOCK(s, 0); ***/+ flush_block_only(s, false);+ if (s.strm.avail_out === 0) {+ return BS_NEED_MORE;+ }+ /***/+ }- here = lcode[hold & lmask];+ return BS_BLOCK_DONE;+}- dolen:- for (;;) { // Goto emulation- op = here >>> 24/*here.bits*/;- hold >>>= op;- bits -= op;- op = (here >>> 16) & 0xff/*here.op*/;- if (op === 0) { /* literal */- //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?- // "inflate: literal '%c'\n" :- // "inflate: literal 0x%02x\n", here.val));- output[_out++] = here & 0xffff/*here.val*/;- }- else if (op & 16) { /* length base */- len = here & 0xffff/*here.val*/;- op &= 15; /* number of extra bits */- if (op) {- if (bits < op) {- hold += input[_in++] << bits;- bits += 8;- }- len += hold & ((1 << op) - 1);- hold >>>= op;- bits -= op;- }- //Tracevv((stderr, "inflate: length %u\n", len));- if (bits < 15) {- hold += input[_in++] << bits;- bits += 8;- hold += input[_in++] << bits;- bits += 8;- }- here = dcode[hold & dmask];- dodist:- for (;;) { // goto emulation- op = here >>> 24/*here.bits*/;- hold >>>= op;- bits -= op;- op = (here >>> 16) & 0xff/*here.op*/;+/* ===========================================================================+ * For Z_RLE, simply look for runs of bytes, generate matches only of distance+ * one. Do not maintain a hash table. (It will be regenerated if this run of+ * deflate switches away from Z_RLE.)+ */+function deflate_rle(s, flush) {+ var bflush; /* set if current block must be flushed */+ var prev; /* byte at distance one to match */+ var scan, strend; /* scan goes up to strend for length of run */- if (op & 16) { /* distance base */- dist = here & 0xffff/*here.val*/;- op &= 15; /* number of extra bits */- if (bits < op) {- hold += input[_in++] << bits;- bits += 8;- if (bits < op) {- hold += input[_in++] << bits;- bits += 8;- }- }- dist += hold & ((1 << op) - 1);-//#ifdef INFLATE_STRICT- if (dist > dmax) {- strm.msg = 'invalid distance too far back';- state.mode = BAD;- break top;- }-//#endif- hold >>>= op;- bits -= op;- //Tracevv((stderr, "inflate: distance %u\n", dist));- op = _out - beg; /* max distance in output */- if (dist > op) { /* see if copy from window */- op = dist - op; /* distance back in window */- if (op > whave) {- if (state.sane) {- strm.msg = 'invalid distance too far back';- state.mode = BAD;- break top;- }+ var _win = s.window;-// (!) This block is disabled in zlib defailts,-// don't enable it for binary compatibility-//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR-// if (len <= op - whave) {-// do {-// output[_out++] = 0;-// } while (--len);-// continue top;-// }-// len -= op - whave;-// do {-// output[_out++] = 0;-// } while (--op > whave);-// if (op === 0) {-// from = _out - dist;-// do {-// output[_out++] = output[from++];-// } while (--len);-// continue top;-// }-//#endif- }- from = 0; // window index- from_source = window;- if (wnext === 0) { /* very common case */- from += wsize - op;- if (op < len) { /* some from window */- len -= op;- do {- output[_out++] = window[from++];- } while (--op);- from = _out - dist; /* rest from output */- from_source = output;- }- }- else if (wnext < op) { /* wrap around window */- from += wsize + wnext - op;- op -= wnext;- if (op < len) { /* some from end of window */- len -= op;- do {- output[_out++] = window[from++];- } while (--op);- from = 0;- if (wnext < len) { /* some from start of window */- op = wnext;- len -= op;- do {- output[_out++] = window[from++];- } while (--op);- from = _out - dist; /* rest from output */- from_source = output;- }- }- }- else { /* contiguous in window */- from += wnext - op;- if (op < len) { /* some from window */- len -= op;- do {- output[_out++] = window[from++];- } while (--op);- from = _out - dist; /* rest from output */- from_source = output;- }- }- while (len > 2) {- output[_out++] = from_source[from++];- output[_out++] = from_source[from++];- output[_out++] = from_source[from++];- len -= 3;- }- if (len) {- output[_out++] = from_source[from++];- if (len > 1) {- output[_out++] = from_source[from++];- }- }- }- else {- from = _out - dist; /* copy direct from output */- do { /* minimum length is three */- output[_out++] = output[from++];- output[_out++] = output[from++];- output[_out++] = output[from++];- len -= 3;- } while (len > 2);- if (len) {- output[_out++] = output[from++];- if (len > 1) {- output[_out++] = output[from++];- }- }- }- }- else if ((op & 64) === 0) { /* 2nd level distance code */- here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];- continue dodist;- }- else {- strm.msg = 'invalid distance code';- state.mode = BAD;- break top;- }+ for (;;) {+ /* Make sure that we always have enough lookahead, except+ * at the end of the input file. We need MAX_MATCH bytes+ * for the longest run, plus one for the unrolled loop.+ */+ if (s.lookahead <= MAX_MATCH) {+ fill_window(s);+ if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {+ return BS_NEED_MORE;+ }+ if (s.lookahead === 0) { break; } /* flush the current block */+ }- break; // need to emulate goto via "continue"+ /* See how many times the previous byte repeats */+ s.match_length = 0;+ if (s.lookahead >= MIN_MATCH && s.strstart > 0) {+ scan = s.strstart - 1;+ prev = _win[scan];+ if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {+ strend = s.strstart + MAX_MATCH;+ do {+ /*jshint noempty:false*/+ } while (prev === _win[++scan] && prev === _win[++scan] &&+ prev === _win[++scan] && prev === _win[++scan] &&+ prev === _win[++scan] && prev === _win[++scan] &&+ prev === _win[++scan] && prev === _win[++scan] &&+ scan < strend);+ s.match_length = MAX_MATCH - (strend - scan);+ if (s.match_length > s.lookahead) {+ s.match_length = s.lookahead;}}- else if ((op & 64) === 0) { /* 2nd level length code */- here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];- continue dolen;- }- else if (op & 32) { /* end-of-block */- //Tracevv((stderr, "inflate: end of block\n"));- state.mode = TYPE;- break top;- }- else {- strm.msg = 'invalid literal/length code';- state.mode = BAD;- break top;- }-- break; // need to emulate goto via "continue"+ //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");}- } while (_in < last && _out < end);- /* return unused bytes (on entry, bits < 8, so in won't go too far back) */- len = bits >> 3;- _in -= len;- bits -= len << 3;- hold &= (1 << bits) - 1;+ /* Emit match if have run of MIN_MATCH or longer, else emit literal */+ if (s.match_length >= MIN_MATCH) {+ //check_match(s, s.strstart, s.strstart - 1, s.match_length);- /* update state and return */- strm.next_in = _in;- strm.next_out = _out;- strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));- strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));- state.hold = hold;- state.bits = bits;- return;-};+ /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/+ bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);-},{}],77:[function(require,module,exports){-'use strict';+ s.lookahead -= s.match_length;+ s.strstart += s.match_length;+ s.match_length = 0;+ } else {+ /* No match, output a literal byte */+ //Tracevv((stderr,"%c", s->window[s->strstart]));+ /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/+ bflush = trees._tr_tally(s, 0, s.window[s.strstart]);+ s.lookahead--;+ s.strstart++;+ }+ if (bflush) {+ /*** FLUSH_BLOCK(s, 0); ***/+ flush_block_only(s, false);+ if (s.strm.avail_out === 0) {+ return BS_NEED_MORE;+ }+ /***/+ }+ }+ s.insert = 0;+ if (flush === Z_FINISH) {+ /*** FLUSH_BLOCK(s, 1); ***/+ flush_block_only(s, true);+ if (s.strm.avail_out === 0) {+ return BS_FINISH_STARTED;+ }+ /***/+ return BS_FINISH_DONE;+ }+ if (s.last_lit) {+ /*** FLUSH_BLOCK(s, 0); ***/+ flush_block_only(s, false);+ if (s.strm.avail_out === 0) {+ return BS_NEED_MORE;+ }+ /***/+ }+ return BS_BLOCK_DONE;+}-var utils = require('../utils/common');-var adler32 = require('./adler32');-var crc32 = require('./crc32');-var inflate_fast = require('./inffast');-var inflate_table = require('./inftrees');+/* ===========================================================================+ * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.+ * (It will be regenerated if this run of deflate switches away from Huffman.)+ */+function deflate_huff(s, flush) {+ var bflush; /* set if current block must be flushed */-var CODES = 0;-var LENS = 1;-var DISTS = 2;+ for (;;) {+ /* Make sure that we have a literal to write. */+ if (s.lookahead === 0) {+ fill_window(s);+ if (s.lookahead === 0) {+ if (flush === Z_NO_FLUSH) {+ return BS_NEED_MORE;+ }+ break; /* flush the current block */+ }+ }-/* Public constants ==========================================================*/-/* ===========================================================================*/+ /* Output a literal byte */+ s.match_length = 0;+ //Tracevv((stderr,"%c", s->window[s->strstart]));+ /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/+ bflush = trees._tr_tally(s, 0, s.window[s.strstart]);+ s.lookahead--;+ s.strstart++;+ if (bflush) {+ /*** FLUSH_BLOCK(s, 0); ***/+ flush_block_only(s, false);+ if (s.strm.avail_out === 0) {+ return BS_NEED_MORE;+ }+ /***/+ }+ }+ s.insert = 0;+ if (flush === Z_FINISH) {+ /*** FLUSH_BLOCK(s, 1); ***/+ flush_block_only(s, true);+ if (s.strm.avail_out === 0) {+ return BS_FINISH_STARTED;+ }+ /***/+ return BS_FINISH_DONE;+ }+ if (s.last_lit) {+ /*** FLUSH_BLOCK(s, 0); ***/+ flush_block_only(s, false);+ if (s.strm.avail_out === 0) {+ return BS_NEED_MORE;+ }+ /***/+ }+ return BS_BLOCK_DONE;+}+/* Values for max_lazy_match, good_match and max_chain_length, depending on+ * the desired pack level (0..9). The values given below have been tuned to+ * exclude worst case performance for pathological files. Better values may be+ * found for specific files.+ */+var Config = function (good_length, max_lazy, nice_length, max_chain, func) {+ this.good_length = good_length;+ this.max_lazy = max_lazy;+ this.nice_length = nice_length;+ this.max_chain = max_chain;+ this.func = func;+};-/* Allowed flush values; see deflate() and inflate() below for details */-//var Z_NO_FLUSH = 0;-//var Z_PARTIAL_FLUSH = 1;-//var Z_SYNC_FLUSH = 2;-//var Z_FULL_FLUSH = 3;-var Z_FINISH = 4;-var Z_BLOCK = 5;-var Z_TREES = 6;+var configuration_table;+configuration_table = [+ /* good lazy nice chain */+ new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */+ new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */+ new Config(4, 5, 16, 8, deflate_fast), /* 2 */+ new Config(4, 6, 32, 32, deflate_fast), /* 3 */-/* Return codes for the compression/decompression functions. Negative values- * are errors, positive values are used for special but normal events.- */-var Z_OK = 0;-var Z_STREAM_END = 1;-var Z_NEED_DICT = 2;-//var Z_ERRNO = -1;-var Z_STREAM_ERROR = -2;-var Z_DATA_ERROR = -3;-var Z_MEM_ERROR = -4;-var Z_BUF_ERROR = -5;-//var Z_VERSION_ERROR = -6;+ new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */+ new Config(8, 16, 32, 32, deflate_slow), /* 5 */+ new Config(8, 16, 128, 128, deflate_slow), /* 6 */+ new Config(8, 32, 128, 256, deflate_slow), /* 7 */+ new Config(32, 128, 258, 1024, deflate_slow), /* 8 */+ new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */+];-/* The deflate compression method */-var Z_DEFLATED = 8;+/* ===========================================================================+ * Initialize the "longest match" routines for a new zlib stream+ */+function lm_init(s) {+ s.window_size = 2 * s.w_size;-/* STATES ====================================================================*/-/* ===========================================================================*/+ /*** CLEAR_HASH(s); ***/+ zero(s.head); // Fill with NIL (= 0);+ /* Set the default configuration parameters:+ */+ s.max_lazy_match = configuration_table[s.level].max_lazy;+ s.good_match = configuration_table[s.level].good_length;+ s.nice_match = configuration_table[s.level].nice_length;+ s.max_chain_length = configuration_table[s.level].max_chain;-var HEAD = 1; /* i: waiting for magic header */-var FLAGS = 2; /* i: waiting for method and flags (gzip) */-var TIME = 3; /* i: waiting for modification time (gzip) */-var OS = 4; /* i: waiting for extra flags and operating system (gzip) */-var EXLEN = 5; /* i: waiting for extra length (gzip) */-var EXTRA = 6; /* i: waiting for extra bytes (gzip) */-var NAME = 7; /* i: waiting for end of file name (gzip) */-var COMMENT = 8; /* i: waiting for end of comment (gzip) */-var HCRC = 9; /* i: waiting for header crc (gzip) */-var DICTID = 10; /* i: waiting for dictionary check value */-var DICT = 11; /* waiting for inflateSetDictionary() call */-var TYPE = 12; /* i: waiting for type bits, including last-flag bit */-var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */-var STORED = 14; /* i: waiting for stored size (length and complement) */-var COPY_ = 15; /* i/o: same as COPY below, but only first time in */-var COPY = 16; /* i/o: waiting for input or output to copy stored block */-var TABLE = 17; /* i: waiting for dynamic block table lengths */-var LENLENS = 18; /* i: waiting for code length code lengths */-var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */-var LEN_ = 20; /* i: same as LEN below, but only first time in */-var LEN = 21; /* i: waiting for length/lit/eob code */-var LENEXT = 22; /* i: waiting for length extra bits */-var DIST = 23; /* i: waiting for distance code */-var DISTEXT = 24; /* i: waiting for distance extra bits */-var MATCH = 25; /* o: waiting for output space to copy string */-var LIT = 26; /* o: waiting for output space to write literal */-var CHECK = 27; /* i: waiting for 32-bit check value */-var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */-var DONE = 29; /* finished check, done -- remain here until reset */-var BAD = 30; /* got a data error -- remain here until reset */-var MEM = 31; /* got an inflate() memory error -- remain here until reset */-var SYNC = 32; /* looking for synchronization bytes to restart inflate() */+ s.strstart = 0;+ s.block_start = 0;+ s.lookahead = 0;+ s.insert = 0;+ s.match_length = s.prev_length = MIN_MATCH - 1;+ s.match_available = 0;+ s.ins_h = 0;+}-/* ===========================================================================*/+function DeflateState() {+ this.strm = null; /* pointer back to this zlib stream */+ this.status = 0; /* as the name implies */+ this.pending_buf = null; /* output still pending */+ this.pending_buf_size = 0; /* size of pending_buf */+ this.pending_out = 0; /* next pending byte to output to the stream */+ this.pending = 0; /* nb of bytes in the pending buffer */+ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */+ this.gzhead = null; /* gzip header information to write */+ this.gzindex = 0; /* where in extra, name, or comment */+ this.method = Z_DEFLATED; /* can only be DEFLATED */+ this.last_flush = -1; /* value of flush param for previous deflate call */+ this.w_size = 0; /* LZ77 window size (32K by default) */+ this.w_bits = 0; /* log2(w_size) (8..16) */+ this.w_mask = 0; /* w_size - 1 */-var ENOUGH_LENS = 852;-var ENOUGH_DISTS = 592;-//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);+ this.window = null;+ /* Sliding window. Input bytes are read into the second half of the window,+ * and move to the first half later to keep a dictionary of at least wSize+ * bytes. With this organization, matches are limited to a distance of+ * wSize-MAX_MATCH bytes, but this ensures that IO is always+ * performed with a length multiple of the block size.+ */-var MAX_WBITS = 15;-/* 32K LZ77 window */-var DEF_WBITS = MAX_WBITS;+ this.window_size = 0;+ /* Actual size of window: 2*wSize, except when the user input buffer+ * is directly used as sliding window.+ */+ this.prev = null;+ /* Link to older string with same hash index. To limit the size of this+ * array to 64K, this link is maintained only for the last 32K strings.+ * An index in this array is thus a window index modulo 32K.+ */-function ZSWAP32(q) {- return (((q >>> 24) & 0xff) +- ((q >>> 8) & 0xff00) +- ((q & 0xff00) << 8) +- ((q & 0xff) << 24));-}+ this.head = null; /* Heads of the hash chains or NIL. */+ this.ins_h = 0; /* hash index of string to be inserted */+ this.hash_size = 0; /* number of elements in hash table */+ this.hash_bits = 0; /* log2(hash_size) */+ this.hash_mask = 0; /* hash_size-1 */-function InflateState() {- this.mode = 0; /* current inflate mode */- this.last = false; /* true if processing last block */- this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */- this.havedict = false; /* true if dictionary provided */- this.flags = 0; /* gzip header method and flags (0 if zlib) */- this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */- this.check = 0; /* protected copy of check value */- this.total = 0; /* protected copy of output count */- // TODO: may be {}- this.head = null; /* where to save gzip header information */+ this.hash_shift = 0;+ /* Number of bits by which ins_h must be shifted at each input+ * step. It must be such that after MIN_MATCH steps, the oldest+ * byte no longer takes part in the hash key, that is:+ * hash_shift * MIN_MATCH >= hash_bits+ */- /* sliding window */- this.wbits = 0; /* log base 2 of requested window size */- this.wsize = 0; /* window size or zero if not using window */- this.whave = 0; /* valid bytes in the window */- this.wnext = 0; /* window write index */- this.window = null; /* allocated sliding window, if needed */+ this.block_start = 0;+ /* Window position at the beginning of the current output block. Gets+ * negative when the window is moved backwards.+ */- /* bit accumulator */- this.hold = 0; /* input bit accumulator */- this.bits = 0; /* number of bits in "in" */+ this.match_length = 0; /* length of best match */+ this.prev_match = 0; /* previous match */+ this.match_available = 0; /* set if previous match exists */+ this.strstart = 0; /* start of string to insert */+ this.match_start = 0; /* start of matching string */+ this.lookahead = 0; /* number of valid bytes ahead in window */- /* for string and stored block copying */- this.length = 0; /* literal or length of data to copy */- this.offset = 0; /* distance back to copy string from */+ this.prev_length = 0;+ /* Length of the best match at previous step. Matches not greater than this+ * are discarded. This is used in the lazy match evaluation.+ */- /* for table and code decoding */- this.extra = 0; /* extra bits needed */+ this.max_chain_length = 0;+ /* To speed up deflation, hash chains are never searched beyond this+ * length. A higher limit improves compression ratio but degrades the+ * speed.+ */- /* fixed and dynamic code tables */- this.lencode = null; /* starting table for length/literal codes */- this.distcode = null; /* starting table for distance codes */- this.lenbits = 0; /* index bits for lencode */- this.distbits = 0; /* index bits for distcode */+ this.max_lazy_match = 0;+ /* Attempt to find a better match only when the current match is strictly+ * smaller than this value. This mechanism is used only for compression+ * levels >= 4.+ */+ // That's alias to max_lazy_match, don't use directly+ //this.max_insert_length = 0;+ /* Insert new strings in the hash table only if the match length is not+ * greater than this length. This saves time but degrades compression.+ * max_insert_length is used only for compression levels <= 3.+ */- /* dynamic table building */- this.ncode = 0; /* number of code length code lengths */- this.nlen = 0; /* number of length code lengths */- this.ndist = 0; /* number of distance code lengths */- this.have = 0; /* number of code lengths in lens[] */- this.next = null; /* next available space in codes[] */+ this.level = 0; /* compression level (1..9) */+ this.strategy = 0; /* favor or force Huffman coding*/- this.lens = new utils.Buf16(320); /* temporary storage for code lengths */- this.work = new utils.Buf16(288); /* work area for code table building */+ this.good_match = 0;+ /* Use a faster search when the previous match is longer than this */- /*- because we don't have pointers in js, we use lencode and distcode directly- as buffers so we don't need codes- */- //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */- this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */- this.distdyn = null; /* dynamic table for distance codes (JS specific) */- this.sane = 0; /* if false, allow invalid distance too far */- this.back = 0; /* bits back of last unprocessed length/lit */- this.was = 0; /* initial length of match */-}+ this.nice_match = 0; /* Stop searching when current match exceeds this */-function inflateResetKeep(strm) {- var state;+ /* used by trees.c: */- if (!strm || !strm.state) { return Z_STREAM_ERROR; }- state = strm.state;- strm.total_in = strm.total_out = state.total = 0;- strm.msg = ''; /*Z_NULL*/- if (state.wrap) { /* to support ill-conceived Java test suite */- strm.adler = state.wrap & 1;- }- state.mode = HEAD;- state.last = 0;- state.havedict = 0;- state.dmax = 32768;- state.head = null/*Z_NULL*/;- state.hold = 0;- state.bits = 0;- //state.lencode = state.distcode = state.next = state.codes;- state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);- state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);+ /* Didn't use ct_data typedef below to suppress compiler warning */- state.sane = 1;- state.back = -1;- //Tracev((stderr, "inflate: reset\n"));- return Z_OK;-}+ // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */+ // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */+ // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */-function inflateReset(strm) {- var state;+ // Use flat array of DOUBLE size, with interleaved fata,+ // because JS does not support effective+ this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);+ this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);+ this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);+ zero(this.dyn_ltree);+ zero(this.dyn_dtree);+ zero(this.bl_tree);- if (!strm || !strm.state) { return Z_STREAM_ERROR; }- state = strm.state;- state.wsize = 0;- state.whave = 0;- state.wnext = 0;- return inflateResetKeep(strm);+ this.l_desc = null; /* desc. for literal tree */+ this.d_desc = null; /* desc. for distance tree */+ this.bl_desc = null; /* desc. for bit length tree */-}+ //ush bl_count[MAX_BITS+1];+ this.bl_count = new utils.Buf16(MAX_BITS+1);+ /* number of codes at each bit length for an optimal tree */-function inflateReset2(strm, windowBits) {- var wrap;- var state;+ //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */+ this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */+ zero(this.heap);- /* get the state */- if (!strm || !strm.state) { return Z_STREAM_ERROR; }- state = strm.state;+ this.heap_len = 0; /* number of elements in the heap */+ this.heap_max = 0; /* element of largest frequency */+ /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.+ * The same heap array is used to build all trees.+ */- /* extract wrap request from windowBits parameter */- if (windowBits < 0) {- wrap = 0;- windowBits = -windowBits;- }- else {- wrap = (windowBits >> 4) + 1;- if (windowBits < 48) {- windowBits &= 15;- }- }+ this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];+ zero(this.depth);+ /* Depth of each subtree used as tie breaker for trees of equal frequency+ */- /* set number of window bits, free window if different */- if (windowBits && (windowBits < 8 || windowBits > 15)) {- return Z_STREAM_ERROR;- }- if (state.window !== null && state.wbits !== windowBits) {- state.window = null;- }+ this.l_buf = 0; /* buffer index for literals or lengths */++ this.lit_bufsize = 0;+ /* Size of match buffer for literals/lengths. There are 4 reasons for+ * limiting lit_bufsize to 64K:+ * - frequencies can be kept in 16 bit counters+ * - if compression is not successful for the first block, all input+ * data is still in the window so we can still emit a stored block even+ * when input comes from standard input. (This can also be done for+ * all blocks if lit_bufsize is not greater than 32K.)+ * - if compression is not successful for a file smaller than 64K, we can+ * even emit a stored file instead of a stored block (saving 5 bytes).+ * This is applicable only for zip (not gzip or zlib).+ * - creating new Huffman trees less frequently may not provide fast+ * adaptation to changes in the input data statistics. (Take for+ * example a binary file with poorly compressible code followed by+ * a highly compressible string table.) Smaller buffer sizes give+ * fast adaptation but have of course the overhead of transmitting+ * trees more frequently.+ * - I can't count above 4+ */- /* update state and reset the rest of it */- state.wrap = wrap;- state.wbits = windowBits;- return inflateReset(strm);-}+ this.last_lit = 0; /* running index in l_buf */-function inflateInit2(strm, windowBits) {- var ret;- var state;+ this.d_buf = 0;+ /* Buffer index for distances. To simplify the code, d_buf and l_buf have+ * the same number of elements. To use different lengths, an extra flag+ * array would be necessary.+ */- if (!strm) { return Z_STREAM_ERROR; }- //strm.msg = Z_NULL; /* in case we return an error */+ this.opt_len = 0; /* bit length of current block with optimal trees */+ this.static_len = 0; /* bit length of current block with static trees */+ this.matches = 0; /* number of string matches in current block */+ this.insert = 0; /* bytes at end of window left to insert */- state = new InflateState();- //if (state === Z_NULL) return Z_MEM_ERROR;- //Tracev((stderr, "inflate: allocated\n"));- strm.state = state;- state.window = null/*Z_NULL*/;- ret = inflateReset2(strm, windowBits);- if (ret !== Z_OK) {- strm.state = null/*Z_NULL*/;- }- return ret;-}+ this.bi_buf = 0;+ /* Output buffer. bits are inserted starting at the bottom (least+ * significant bits).+ */+ this.bi_valid = 0;+ /* Number of valid bits in bi_buf. All bits above the last valid bit+ * are always zero.+ */-function inflateInit(strm) {- return inflateInit2(strm, DEF_WBITS);+ // Used for window memory init. We safely ignore it for JS. That makes+ // sense only for pointers and memory check tools.+ //this.high_water = 0;+ /* High water mark offset in window for initialized bytes -- bytes above+ * this are set to zero in order to avoid memory check warnings when+ * longest match routines access bytes past the input. This is then+ * updated to the new high water mark.+ */}-/*- Return state with length and distance decoding tables and index sizes set to- fixed code decoding. Normally this returns fixed tables from inffixed.h.- If BUILDFIXED is defined, then instead this routine builds the tables the- first time it's called, and returns those tables the first time and- thereafter. This reduces the size of the code by about 2K bytes, in- exchange for a little execution time. However, BUILDFIXED should not be- used for threaded applications, since the rewriting of the tables and virgin- may not be thread-safe.- */-var virgin = true;--var lenfix, distfix; // We have no pointers in JS, so keep tables separate--function fixedtables(state) {- /* build fixed huffman tables if first call (may not be thread safe) */- if (virgin) {- var sym;+function deflateResetKeep(strm) {+ var s;- lenfix = new utils.Buf32(512);- distfix = new utils.Buf32(32);+ if (!strm || !strm.state) {+ return err(strm, Z_STREAM_ERROR);+ }- /* literal/length table */- sym = 0;- while (sym < 144) { state.lens[sym++] = 8; }- while (sym < 256) { state.lens[sym++] = 9; }- while (sym < 280) { state.lens[sym++] = 7; }- while (sym < 288) { state.lens[sym++] = 8; }+ strm.total_in = strm.total_out = 0;+ strm.data_type = Z_UNKNOWN;- inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});+ s = strm.state;+ s.pending = 0;+ s.pending_out = 0;- /* distance table */- sym = 0;- while (sym < 32) { state.lens[sym++] = 5; }+ if (s.wrap < 0) {+ s.wrap = -s.wrap;+ /* was made negative by deflate(..., Z_FINISH); */+ }+ s.status = (s.wrap ? INIT_STATE : BUSY_STATE);+ strm.adler = (s.wrap === 2) ?+ 0 // crc32(0, Z_NULL, 0)+ :+ 1; // adler32(0, Z_NULL, 0)+ s.last_flush = Z_NO_FLUSH;+ trees._tr_init(s);+ return Z_OK;+}- inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});- /* do this just once */- virgin = false;+function deflateReset(strm) {+ var ret = deflateResetKeep(strm);+ if (ret === Z_OK) {+ lm_init(strm.state);}+ return ret;+}- state.lencode = lenfix;- state.lenbits = 9;- state.distcode = distfix;- state.distbits = 5;++function deflateSetHeader(strm, head) {+ if (!strm || !strm.state) { return Z_STREAM_ERROR; }+ if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }+ strm.state.gzhead = head;+ return Z_OK;}-/*- Update the window with the last wsize (normally 32K) bytes written before- returning. If window does not exist yet, create it. This is only called- when a window is already in use, or when output has been written during this- inflate call, but the end of the deflate stream has not been reached yet.- It is also called to create a window for dictionary data when a dictionary- is loaded.+function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {+ if (!strm) { // === Z_NULL+ return Z_STREAM_ERROR;+ }+ var wrap = 1;- Providing output buffers larger than 32K to inflate() should provide a speed- advantage, since only the last 32K of output is copied to the sliding window- upon return from inflate(), and since all distances after the first 32K of- output will fall in the output data, making match copies simpler and faster.- The advantage may be dependent on the size of the processor's data caches.- */-function updatewindow(strm, src, end, copy) {- var dist;- var state = strm.state;+ if (level === Z_DEFAULT_COMPRESSION) {+ level = 6;+ }- /* if it hasn't been done already, allocate space for the window */- if (state.window === null) {- state.wsize = 1 << state.wbits;- state.wnext = 0;- state.whave = 0;+ if (windowBits < 0) { /* suppress zlib wrapper */+ wrap = 0;+ windowBits = -windowBits;+ }- state.window = new utils.Buf8(state.wsize);+ else if (windowBits > 15) {+ wrap = 2; /* write gzip wrapper instead */+ windowBits -= 16;}- /* copy state->wsize or less output bytes into the circular window */- if (copy >= state.wsize) {- utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);- state.wnext = 0;- state.whave = state.wsize;++ if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||+ windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||+ strategy < 0 || strategy > Z_FIXED) {+ return err(strm, Z_STREAM_ERROR);}- else {- dist = state.wsize - state.wnext;- if (dist > copy) {- dist = copy;- }- //zmemcpy(state->window + state->wnext, end - copy, dist);- utils.arraySet(state.window,src, end - copy, dist, state.wnext);- copy -= dist;- if (copy) {- //zmemcpy(state->window, end - copy, copy);- utils.arraySet(state.window,src, end - copy, copy, 0);- state.wnext = copy;- state.whave = state.wsize;- }- else {- state.wnext += dist;- if (state.wnext === state.wsize) { state.wnext = 0; }- if (state.whave < state.wsize) { state.whave += dist; }- }+++ if (windowBits === 8) {+ windowBits = 9;}- return 0;-}+ /* until 256-byte window bug fixed */-function inflate(strm, flush) {- var state;- var input, output; // input/output buffers- var next; /* next input INDEX */- var put; /* next output INDEX */- var have, left; /* available input and output */- var hold; /* bit buffer */- var bits; /* bits in bit buffer */- var _in, _out; /* save starting available input and output */- var copy; /* number of stored or match bytes to copy */- var from; /* where to copy match bytes from */- var from_source;- var here = 0; /* current decoding table entry */- var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)- //var last; /* parent table entry */- var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)- var len; /* length to copy for repeats, bits to drop */- var ret; /* return code */- var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */- var opts;+ var s = new DeflateState();- var n; // temporary var for NEED_BITS+ strm.state = s;+ s.strm = strm;- var order = /* permutation of code lengths */- [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];+ s.wrap = wrap;+ s.gzhead = null;+ s.w_bits = windowBits;+ s.w_size = 1 << s.w_bits;+ s.w_mask = s.w_size - 1;+ s.hash_bits = memLevel + 7;+ s.hash_size = 1 << s.hash_bits;+ s.hash_mask = s.hash_size - 1;+ s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);- if (!strm || !strm.state || !strm.output ||- (!strm.input && strm.avail_in !== 0)) {- return Z_STREAM_ERROR;- }+ s.window = new utils.Buf8(s.w_size * 2);+ s.head = new utils.Buf16(s.hash_size);+ s.prev = new utils.Buf16(s.w_size);- state = strm.state;- if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */+ // Don't need mem init magic for JS.+ //s.high_water = 0; /* nothing written to s->window yet */+ s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */- //--- LOAD() ---- put = strm.next_out;- output = strm.output;- left = strm.avail_out;- next = strm.next_in;- input = strm.input;- have = strm.avail_in;- hold = state.hold;- bits = state.bits;- //---+ s.pending_buf_size = s.lit_bufsize * 4;+ s.pending_buf = new utils.Buf8(s.pending_buf_size);++ s.d_buf = s.lit_bufsize >> 1;+ s.l_buf = (1 + 2) * s.lit_bufsize;- _in = have;- _out = left;- ret = Z_OK;+ s.level = level;+ s.strategy = strategy;+ s.method = method;- inf_leave: // goto emulation- for (;;) {- switch (state.mode) {- case HEAD:- if (state.wrap === 0) {- state.mode = TYPEDO;- break;- }- //=== NEEDBITS(16);- while (bits < 16) {- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;- }- //===//- if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */- state.check = 0/*crc32(0L, Z_NULL, 0)*/;- //=== CRC2(state.check, hold);- hbuf[0] = hold & 0xff;- hbuf[1] = (hold >>> 8) & 0xff;- state.check = crc32(state.check, hbuf, 2, 0);- //===//+ return deflateReset(strm);+}- //=== INITBITS();- hold = 0;- bits = 0;- //===//- state.mode = FLAGS;- break;- }- state.flags = 0; /* expect zlib header */- if (state.head) {- state.head.done = false;- }- if (!(state.wrap & 1) || /* check if zlib header allowed */- (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {- strm.msg = 'incorrect header check';- state.mode = BAD;- break;- }- if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {- strm.msg = 'unknown compression method';- state.mode = BAD;- break;- }- //--- DROPBITS(4) ---//- hold >>>= 4;- bits -= 4;- //---//- len = (hold & 0x0f)/*BITS(4)*/ + 8;- if (state.wbits === 0) {- state.wbits = len;- }- else if (len > state.wbits) {- strm.msg = 'invalid window size';- state.mode = BAD;- break;- }- state.dmax = 1 << len;- //Tracev((stderr, "inflate: zlib header ok\n"));- strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;- state.mode = hold & 0x200 ? DICTID : TYPE;- //=== INITBITS();- hold = 0;- bits = 0;- //===//- break;- case FLAGS:- //=== NEEDBITS(16); */- while (bits < 16) {- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;- }- //===//- state.flags = hold;- if ((state.flags & 0xff) !== Z_DEFLATED) {- strm.msg = 'unknown compression method';- state.mode = BAD;- break;- }- if (state.flags & 0xe000) {- strm.msg = 'unknown header flags set';- state.mode = BAD;- break;- }- if (state.head) {- state.head.text = ((hold >> 8) & 1);- }- if (state.flags & 0x0200) {- //=== CRC2(state.check, hold);- hbuf[0] = hold & 0xff;- hbuf[1] = (hold >>> 8) & 0xff;- state.check = crc32(state.check, hbuf, 2, 0);- //===//- }- //=== INITBITS();- hold = 0;- bits = 0;- //===//- state.mode = TIME;- /* falls through */- case TIME:- //=== NEEDBITS(32); */- while (bits < 32) {- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;- }- //===//- if (state.head) {- state.head.time = hold;- }- if (state.flags & 0x0200) {- //=== CRC4(state.check, hold)- hbuf[0] = hold & 0xff;- hbuf[1] = (hold >>> 8) & 0xff;- hbuf[2] = (hold >>> 16) & 0xff;- hbuf[3] = (hold >>> 24) & 0xff;- state.check = crc32(state.check, hbuf, 4, 0);- //===- }- //=== INITBITS();- hold = 0;- bits = 0;- //===//- state.mode = OS;- /* falls through */- case OS:- //=== NEEDBITS(16); */- while (bits < 16) {- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;- }- //===//- if (state.head) {- state.head.xflags = (hold & 0xff);- state.head.os = (hold >> 8);- }- if (state.flags & 0x0200) {- //=== CRC2(state.check, hold);- hbuf[0] = hold & 0xff;- hbuf[1] = (hold >>> 8) & 0xff;- state.check = crc32(state.check, hbuf, 2, 0);- //===//- }- //=== INITBITS();- hold = 0;- bits = 0;- //===//- state.mode = EXLEN;- /* falls through */- case EXLEN:- if (state.flags & 0x0400) {- //=== NEEDBITS(16); */- while (bits < 16) {- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;- }- //===//- state.length = hold;- if (state.head) {- state.head.extra_len = hold;- }- if (state.flags & 0x0200) {- //=== CRC2(state.check, hold);- hbuf[0] = hold & 0xff;- hbuf[1] = (hold >>> 8) & 0xff;- state.check = crc32(state.check, hbuf, 2, 0);- //===//- }- //=== INITBITS();- hold = 0;- bits = 0;- //===//- }- else if (state.head) {- state.head.extra = null/*Z_NULL*/;- }- state.mode = EXTRA;- /* falls through */- case EXTRA:- if (state.flags & 0x0400) {- copy = state.length;- if (copy > have) { copy = have; }- if (copy) {- if (state.head) {- len = state.head.extra_len - state.length;- if (!state.head.extra) {- // Use untyped array for more conveniend processing later- state.head.extra = new Array(state.head.extra_len);- }- utils.arraySet(- state.head.extra,- input,- next,- // extra field is limited to 65536 bytes- // - no need for additional size check- copy,- /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/- len- );- //zmemcpy(state.head.extra + len, next,- // len + copy > state.head.extra_max ?- // state.head.extra_max - len : copy);- }- if (state.flags & 0x0200) {- state.check = crc32(state.check, input, copy, next);- }- have -= copy;- next += copy;- state.length -= copy;- }- if (state.length) { break inf_leave; }- }- state.length = 0;- state.mode = NAME;- /* falls through */- case NAME:- if (state.flags & 0x0800) {- if (have === 0) { break inf_leave; }- copy = 0;- do {- // TODO: 2 or 1 bytes?- len = input[next + copy++];- /* use constant limit because in js we should not preallocate memory */- if (state.head && len &&- (state.length < 65536 /*state.head.name_max*/)) {- state.head.name += String.fromCharCode(len);- }- } while (len && copy < have);+function deflateInit(strm, level) {+ return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);+}+++function deflate(strm, flush) {+ var old_flush, s;+ var beg, val; // for gzip header write only++ if (!strm || !strm.state ||+ flush > Z_BLOCK || flush < 0) {+ return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;+ }- if (state.flags & 0x0200) {- state.check = crc32(state.check, input, copy, next);- }- have -= copy;- next += copy;- if (len) { break inf_leave; }- }- else if (state.head) {- state.head.name = null;- }- state.length = 0;- state.mode = COMMENT;- /* falls through */- case COMMENT:- if (state.flags & 0x1000) {- if (have === 0) { break inf_leave; }- copy = 0;- do {- len = input[next + copy++];- /* use constant limit because in js we should not preallocate memory */- if (state.head && len &&- (state.length < 65536 /*state.head.comm_max*/)) {- state.head.comment += String.fromCharCode(len);- }- } while (len && copy < have);- if (state.flags & 0x0200) {- state.check = crc32(state.check, input, copy, next);- }- have -= copy;- next += copy;- if (len) { break inf_leave; }- }- else if (state.head) {- state.head.comment = null;+ s = strm.state;++ if (!strm.output ||+ (!strm.input && strm.avail_in !== 0) ||+ (s.status === FINISH_STATE && flush !== Z_FINISH)) {+ return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);+ }++ s.strm = strm; /* just in case */+ old_flush = s.last_flush;+ s.last_flush = flush;++ /* Write the header */+ if (s.status === INIT_STATE) {++ if (s.wrap === 2) { // GZIP header+ strm.adler = 0; //crc32(0L, Z_NULL, 0);+ put_byte(s, 31);+ put_byte(s, 139);+ put_byte(s, 8);+ if (!s.gzhead) { // s->gzhead == Z_NULL+ put_byte(s, 0);+ put_byte(s, 0);+ put_byte(s, 0);+ put_byte(s, 0);+ put_byte(s, 0);+ put_byte(s, s.level === 9 ? 2 :+ (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?+ 4 : 0));+ put_byte(s, OS_CODE);+ s.status = BUSY_STATE;}- state.mode = HCRC;- /* falls through */- case HCRC:- if (state.flags & 0x0200) {- //=== NEEDBITS(16); */- while (bits < 16) {- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;+ else {+ put_byte(s, (s.gzhead.text ? 1 : 0) ++ (s.gzhead.hcrc ? 2 : 0) ++ (!s.gzhead.extra ? 0 : 4) ++ (!s.gzhead.name ? 0 : 8) ++ (!s.gzhead.comment ? 0 : 16)+ );+ put_byte(s, s.gzhead.time & 0xff);+ put_byte(s, (s.gzhead.time >> 8) & 0xff);+ put_byte(s, (s.gzhead.time >> 16) & 0xff);+ put_byte(s, (s.gzhead.time >> 24) & 0xff);+ put_byte(s, s.level === 9 ? 2 :+ (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?+ 4 : 0));+ put_byte(s, s.gzhead.os & 0xff);+ if (s.gzhead.extra && s.gzhead.extra.length) {+ put_byte(s, s.gzhead.extra.length & 0xff);+ put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);}- //===//- if (hold !== (state.check & 0xffff)) {- strm.msg = 'header crc mismatch';- state.mode = BAD;- break;+ if (s.gzhead.hcrc) {+ strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);}- //=== INITBITS();- hold = 0;- bits = 0;- //===//- }- if (state.head) {- state.head.hcrc = ((state.flags >> 9) & 1);- state.head.done = true;- }- strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;- state.mode = TYPE;- break;- case DICTID:- //=== NEEDBITS(32); */- while (bits < 32) {- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;- }- //===//- strm.adler = state.check = ZSWAP32(hold);- //=== INITBITS();- hold = 0;- bits = 0;- //===//- state.mode = DICT;- /* falls through */- case DICT:- if (state.havedict === 0) {- //--- RESTORE() ---- strm.next_out = put;- strm.avail_out = left;- strm.next_in = next;- strm.avail_in = have;- state.hold = hold;- state.bits = bits;- //---- return Z_NEED_DICT;+ s.gzindex = 0;+ s.status = EXTRA_STATE;}- strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;- state.mode = TYPE;- /* falls through */- case TYPE:- if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }- /* falls through */- case TYPEDO:- if (state.last) {- //--- BYTEBITS() ---//- hold >>>= bits & 7;- bits -= bits & 7;- //---//- state.mode = CHECK;- break;+ }+ else // DEFLATE header+ {+ var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;+ var level_flags = -1;++ if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {+ level_flags = 0;+ } else if (s.level < 6) {+ level_flags = 1;+ } else if (s.level === 6) {+ level_flags = 2;+ } else {+ level_flags = 3;}- //=== NEEDBITS(3); */- while (bits < 3) {- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;+ header |= (level_flags << 6);+ if (s.strstart !== 0) { header |= PRESET_DICT; }+ header += 31 - (header % 31);++ s.status = BUSY_STATE;+ putShortMSB(s, header);++ /* Save the adler32 of the preset dictionary: */+ if (s.strstart !== 0) {+ putShortMSB(s, strm.adler >>> 16);+ putShortMSB(s, strm.adler & 0xffff);}- //===//- state.last = (hold & 0x01)/*BITS(1)*/;- //--- DROPBITS(1) ---//- hold >>>= 1;- bits -= 1;- //---//+ strm.adler = 1; // adler32(0L, Z_NULL, 0);+ }+ }- switch ((hold & 0x03)/*BITS(2)*/) {- case 0: /* stored block */- //Tracev((stderr, "inflate: stored block%s\n",- // state.last ? " (last)" : ""));- state.mode = STORED;- break;- case 1: /* fixed block */- fixedtables(state);- //Tracev((stderr, "inflate: fixed codes block%s\n",- // state.last ? " (last)" : ""));- state.mode = LEN_; /* decode codes */- if (flush === Z_TREES) {- //--- DROPBITS(2) ---//- hold >>>= 2;- bits -= 2;- //---//- break inf_leave;+//#ifdef GZIP+ if (s.status === EXTRA_STATE) {+ if (s.gzhead.extra/* != Z_NULL*/) {+ beg = s.pending; /* start of bytes to update crc */++ while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {+ if (s.pending === s.pending_buf_size) {+ if (s.gzhead.hcrc && s.pending > beg) {+ strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);+ }+ flush_pending(strm);+ beg = s.pending;+ if (s.pending === s.pending_buf_size) {+ break;+ }}- break;- case 2: /* dynamic block */- //Tracev((stderr, "inflate: dynamic codes block%s\n",- // state.last ? " (last)" : ""));- state.mode = TABLE;- break;- case 3:- strm.msg = 'invalid block type';- state.mode = BAD;- }- //--- DROPBITS(2) ---//- hold >>>= 2;- bits -= 2;- //---//- break;- case STORED:- //--- BYTEBITS() ---// /* go to byte boundary */- hold >>>= bits & 7;- bits -= bits & 7;- //---//- //=== NEEDBITS(32); */- while (bits < 32) {- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;+ put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);+ s.gzindex++;}- //===//- if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {- strm.msg = 'invalid stored block lengths';- state.mode = BAD;- break;+ if (s.gzhead.hcrc && s.pending > beg) {+ strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);}- state.length = hold & 0xffff;- //Tracev((stderr, "inflate: stored length %u\n",- // state.length));- //=== INITBITS();- hold = 0;- bits = 0;- //===//- state.mode = COPY_;- if (flush === Z_TREES) { break inf_leave; }- /* falls through */- case COPY_:- state.mode = COPY;- /* falls through */- case COPY:- copy = state.length;- if (copy) {- if (copy > have) { copy = have; }- if (copy > left) { copy = left; }- if (copy === 0) { break inf_leave; }- //--- zmemcpy(put, next, copy); ---- utils.arraySet(output, input, next, copy, put);- //---//- have -= copy;- next += copy;- left -= copy;- put += copy;- state.length -= copy;- break;+ if (s.gzindex === s.gzhead.extra.length) {+ s.gzindex = 0;+ s.status = NAME_STATE;}- //Tracev((stderr, "inflate: stored end\n"));- state.mode = TYPE;- break;- case TABLE:- //=== NEEDBITS(14); */- while (bits < 14) {- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;+ }+ else {+ s.status = NAME_STATE;+ }+ }+ if (s.status === NAME_STATE) {+ if (s.gzhead.name/* != Z_NULL*/) {+ beg = s.pending; /* start of bytes to update crc */+ //int val;++ do {+ if (s.pending === s.pending_buf_size) {+ if (s.gzhead.hcrc && s.pending > beg) {+ strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);+ }+ flush_pending(strm);+ beg = s.pending;+ if (s.pending === s.pending_buf_size) {+ val = 1;+ break;+ }+ }+ // JS specific: little magic to add zero terminator to end of string+ if (s.gzindex < s.gzhead.name.length) {+ val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;+ } else {+ val = 0;+ }+ put_byte(s, val);+ } while (val !== 0);++ if (s.gzhead.hcrc && s.pending > beg){+ strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);}- //===//- state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;- //--- DROPBITS(5) ---//- hold >>>= 5;- bits -= 5;- //---//- state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;- //--- DROPBITS(5) ---//- hold >>>= 5;- bits -= 5;- //---//- state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;- //--- DROPBITS(4) ---//- hold >>>= 4;- bits -= 4;- //---//-//#ifndef PKZIP_BUG_WORKAROUND- if (state.nlen > 286 || state.ndist > 30) {- strm.msg = 'too many length or distance symbols';- state.mode = BAD;- break;+ if (val === 0) {+ s.gzindex = 0;+ s.status = COMMENT_STATE;}-//#endif- //Tracev((stderr, "inflate: table sizes ok\n"));- state.have = 0;- state.mode = LENLENS;- /* falls through */- case LENLENS:- while (state.have < state.ncode) {- //=== NEEDBITS(3);- while (bits < 3) {- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;+ }+ else {+ s.status = COMMENT_STATE;+ }+ }+ if (s.status === COMMENT_STATE) {+ if (s.gzhead.comment/* != Z_NULL*/) {+ beg = s.pending; /* start of bytes to update crc */+ //int val;++ do {+ if (s.pending === s.pending_buf_size) {+ if (s.gzhead.hcrc && s.pending > beg) {+ strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);+ }+ flush_pending(strm);+ beg = s.pending;+ if (s.pending === s.pending_buf_size) {+ val = 1;+ break;+ }}- //===//- state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);- //--- DROPBITS(3) ---//- hold >>>= 3;- bits -= 3;- //---//+ // JS specific: little magic to add zero terminator to end of string+ if (s.gzindex < s.gzhead.comment.length) {+ val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;+ } else {+ val = 0;+ }+ put_byte(s, val);+ } while (val !== 0);++ if (s.gzhead.hcrc && s.pending > beg) {+ strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);}- while (state.have < 19) {- state.lens[order[state.have++]] = 0;+ if (val === 0) {+ s.status = HCRC_STATE;}- // We have separate tables & no pointers. 2 commented lines below not needed.- //state.next = state.codes;- //state.lencode = state.next;- // Switch to use dynamic table- state.lencode = state.lendyn;- state.lenbits = 7;+ }+ else {+ s.status = HCRC_STATE;+ }+ }+ if (s.status === HCRC_STATE) {+ if (s.gzhead.hcrc) {+ if (s.pending + 2 > s.pending_buf_size) {+ flush_pending(strm);+ }+ if (s.pending + 2 <= s.pending_buf_size) {+ put_byte(s, strm.adler & 0xff);+ put_byte(s, (strm.adler >> 8) & 0xff);+ strm.adler = 0; //crc32(0L, Z_NULL, 0);+ s.status = BUSY_STATE;+ }+ }+ else {+ s.status = BUSY_STATE;+ }+ }+//#endif- opts = {bits: state.lenbits};- ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);- state.lenbits = opts.bits;+ /* Flush as much pending output as possible */+ if (s.pending !== 0) {+ flush_pending(strm);+ if (strm.avail_out === 0) {+ /* Since avail_out is 0, deflate will be called again with+ * more output space, but possibly with both pending and+ * avail_in equal to zero. There won't be anything to do,+ * but this is not an error situation so make sure we+ * return OK instead of BUF_ERROR at next call of deflate:+ */+ s.last_flush = -1;+ return Z_OK;+ }- if (ret) {- strm.msg = 'invalid code lengths set';- state.mode = BAD;- break;+ /* Make sure there is something to do and avoid duplicate consecutive+ * flushes. For repeated and useless calls with Z_FINISH, we keep+ * returning Z_STREAM_END instead of Z_BUF_ERROR.+ */+ } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&+ flush !== Z_FINISH) {+ return err(strm, Z_BUF_ERROR);+ }++ /* User must not provide more input after the first FINISH: */+ if (s.status === FINISH_STATE && strm.avail_in !== 0) {+ return err(strm, Z_BUF_ERROR);+ }++ /* Start a new block or continue the current one.+ */+ if (strm.avail_in !== 0 || s.lookahead !== 0 ||+ (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {+ var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :+ (s.strategy === Z_RLE ? deflate_rle(s, flush) :+ configuration_table[s.level].func(s, flush));++ if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {+ s.status = FINISH_STATE;+ }+ if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {+ if (strm.avail_out === 0) {+ s.last_flush = -1;+ /* avoid BUF_ERROR next call, see above */}- //Tracev((stderr, "inflate: code lengths ok\n"));- state.have = 0;- state.mode = CODELENS;- /* falls through */- case CODELENS:- while (state.have < state.nlen + state.ndist) {- for (;;) {- here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/- here_bits = here >>> 24;- here_op = (here >>> 16) & 0xff;- here_val = here & 0xffff;+ return Z_OK;+ /* If flush != Z_NO_FLUSH && avail_out == 0, the next call+ * of deflate should use the same flush parameter to make sure+ * that the flush is complete. So we don't have to output an+ * empty block here, this will be done at next call. This also+ * ensures that for a very small output buffer, we emit at most+ * one empty block.+ */+ }+ if (bstate === BS_BLOCK_DONE) {+ if (flush === Z_PARTIAL_FLUSH) {+ trees._tr_align(s);+ }+ else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */- if ((here_bits) <= bits) { break; }- //--- PULLBYTE() ---//- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;- //---//- }- if (here_val < 16) {- //--- DROPBITS(here.bits) ---//- hold >>>= here_bits;- bits -= here_bits;- //---//- state.lens[state.have++] = here_val;- }- else {- if (here_val === 16) {- //=== NEEDBITS(here.bits + 2);- n = here_bits + 2;- while (bits < n) {- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;- }- //===//- //--- DROPBITS(here.bits) ---//- hold >>>= here_bits;- bits -= here_bits;- //---//- if (state.have === 0) {- strm.msg = 'invalid bit length repeat';- state.mode = BAD;- break;- }- len = state.lens[state.have - 1];- copy = 3 + (hold & 0x03);//BITS(2);- //--- DROPBITS(2) ---//- hold >>>= 2;- bits -= 2;- //---//- }- else if (here_val === 17) {- //=== NEEDBITS(here.bits + 3);- n = here_bits + 3;- while (bits < n) {- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;- }- //===//- //--- DROPBITS(here.bits) ---//- hold >>>= here_bits;- bits -= here_bits;- //---//- len = 0;- copy = 3 + (hold & 0x07);//BITS(3);- //--- DROPBITS(3) ---//- hold >>>= 3;- bits -= 3;- //---//- }- else {- //=== NEEDBITS(here.bits + 7);- n = here_bits + 7;- while (bits < n) {- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;- }- //===//- //--- DROPBITS(here.bits) ---//- hold >>>= here_bits;- bits -= here_bits;- //---//- len = 0;- copy = 11 + (hold & 0x7f);//BITS(7);- //--- DROPBITS(7) ---//- hold >>>= 7;- bits -= 7;- //---//- }- if (state.have + copy > state.nlen + state.ndist) {- strm.msg = 'invalid bit length repeat';- state.mode = BAD;- break;- }- while (copy--) {- state.lens[state.have++] = len;+ trees._tr_stored_block(s, 0, 0, false);+ /* For a full flush, this empty block will be recognized+ * as a special marker by inflate_sync().+ */+ if (flush === Z_FULL_FLUSH) {+ /*** CLEAR_HASH(s); ***/ /* forget history */+ zero(s.head); // Fill with NIL (= 0);++ if (s.lookahead === 0) {+ s.strstart = 0;+ s.block_start = 0;+ s.insert = 0;}}}+ flush_pending(strm);+ if (strm.avail_out === 0) {+ s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */+ return Z_OK;+ }+ }+ }+ //Assert(strm->avail_out > 0, "bug2");+ //if (strm.avail_out <= 0) { throw new Error("bug2");}++ if (flush !== Z_FINISH) { return Z_OK; }+ if (s.wrap <= 0) { return Z_STREAM_END; }++ /* Write the trailer */+ if (s.wrap === 2) {+ put_byte(s, strm.adler & 0xff);+ put_byte(s, (strm.adler >> 8) & 0xff);+ put_byte(s, (strm.adler >> 16) & 0xff);+ put_byte(s, (strm.adler >> 24) & 0xff);+ put_byte(s, strm.total_in & 0xff);+ put_byte(s, (strm.total_in >> 8) & 0xff);+ put_byte(s, (strm.total_in >> 16) & 0xff);+ put_byte(s, (strm.total_in >> 24) & 0xff);+ }+ else+ {+ putShortMSB(s, strm.adler >>> 16);+ putShortMSB(s, strm.adler & 0xffff);+ }++ flush_pending(strm);+ /* If avail_out is zero, the application will call deflate again+ * to flush the rest.+ */+ if (s.wrap > 0) { s.wrap = -s.wrap; }+ /* write the trailer only once! */+ return s.pending !== 0 ? Z_OK : Z_STREAM_END;+}++function deflateEnd(strm) {+ var status;++ if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {+ return Z_STREAM_ERROR;+ }++ status = strm.state.status;+ if (status !== INIT_STATE &&+ status !== EXTRA_STATE &&+ status !== NAME_STATE &&+ status !== COMMENT_STATE &&+ status !== HCRC_STATE &&+ status !== BUSY_STATE &&+ status !== FINISH_STATE+ ) {+ return err(strm, Z_STREAM_ERROR);+ }++ strm.state = null;++ return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;+}++/* =========================================================================+ * Copy the source state to the destination state+ */+//function deflateCopy(dest, source) {+//+//}++exports.deflateInit = deflateInit;+exports.deflateInit2 = deflateInit2;+exports.deflateReset = deflateReset;+exports.deflateResetKeep = deflateResetKeep;+exports.deflateSetHeader = deflateSetHeader;+exports.deflate = deflate;+exports.deflateEnd = deflateEnd;+exports.deflateInfo = 'pako deflate (from Nodeca project)';++/* Not implemented+exports.deflateBound = deflateBound;+exports.deflateCopy = deflateCopy;+exports.deflateSetDictionary = deflateSetDictionary;+exports.deflateParams = deflateParams;+exports.deflatePending = deflatePending;+exports.deflatePrime = deflatePrime;+exports.deflateTune = deflateTune;+*/+},{"../utils/common":70,"./adler32":72,"./crc32":74,"./messages":80,"./trees":81}],76:[function(require,module,exports){+'use strict';+++function GZheader() {+ /* true if compressed data believed to be text */+ this.text = 0;+ /* modification time */+ this.time = 0;+ /* extra flags (not used when writing a gzip file) */+ this.xflags = 0;+ /* operating system */+ this.os = 0;+ /* pointer to extra field or Z_NULL if none */+ this.extra = null;+ /* extra field length (valid if extra != Z_NULL) */+ this.extra_len = 0; // Actually, we don't need it in JS,+ // but leave for few code modifications++ //+ // Setup limits is not necessary because in js we should not preallocate memory+ // for inflate use constant limit in 65536 bytes+ //++ /* space at extra (only when reading header) */+ // this.extra_max = 0;+ /* pointer to zero-terminated file name or Z_NULL */+ this.name = '';+ /* space at name (only when reading header) */+ // this.name_max = 0;+ /* pointer to zero-terminated comment or Z_NULL */+ this.comment = '';+ /* space at comment (only when reading header) */+ // this.comm_max = 0;+ /* true if there was or will be a header crc */+ this.hcrc = 0;+ /* true when done reading gzip header (not used when writing a gzip file) */+ this.done = false;+}++module.exports = GZheader;+},{}],77:[function(require,module,exports){+'use strict';++// See state defs from inflate.js+var BAD = 30; /* got a data error -- remain here until reset */+var TYPE = 12; /* i: waiting for type bits, including last-flag bit */++/*+ Decode literal, length, and distance codes and write out the resulting+ literal and match bytes until either not enough input or output is+ available, an end-of-block is encountered, or a data error is encountered.+ When large enough input and output buffers are supplied to inflate(), for+ example, a 16K input buffer and a 64K output buffer, more than 95% of the+ inflate execution time is spent in this routine.++ Entry assumptions:++ state.mode === LEN+ strm.avail_in >= 6+ strm.avail_out >= 258+ start >= strm.avail_out+ state.bits < 8- /* handle error breaks in while */- if (state.mode === BAD) { break; }+ On return, state.mode is one of:- /* check for end-of-block code (better have one) */- if (state.lens[256] === 0) {- strm.msg = 'invalid code -- missing end-of-block';- state.mode = BAD;- break;- }+ LEN -- ran out of enough output space or enough available input+ TYPE -- reached end of block code, inflate() to interpret next block+ BAD -- error in block data- /* build code tables -- note: do not change the lenbits or distbits- values here (9 and 6) without reading the comments in inftrees.h- concerning the ENOUGH constants, which depend on those values */- state.lenbits = 9;+ Notes:- opts = {bits: state.lenbits};- ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);- // We have separate tables & no pointers. 2 commented lines below not needed.- // state.next_index = opts.table_index;- state.lenbits = opts.bits;- // state.lencode = state.next;+ - The maximum input bits used by a length/distance pair is 15 bits for the+ length code, 5 bits for the length extra, 15 bits for the distance code,+ and 13 bits for the distance extra. This totals 48 bits, or six bytes.+ Therefore if strm.avail_in >= 6, then there is enough input to avoid+ checking for available input while decoding.- if (ret) {- strm.msg = 'invalid literal/lengths set';- state.mode = BAD;- break;- }+ - The maximum bytes that a single length/distance pair can output is 258+ bytes, which is the maximum length that can be coded. inflate_fast()+ requires strm.avail_out >= 258 for each loop to avoid checking for+ output space.+ */+module.exports = function inflate_fast(strm, start) {+ var state;+ var _in; /* local strm.input */+ var last; /* have enough input while in < last */+ var _out; /* local strm.output */+ var beg; /* inflate()'s initial strm.output */+ var end; /* while out < end, enough space available */+//#ifdef INFLATE_STRICT+ var dmax; /* maximum distance from zlib header */+//#endif+ var wsize; /* window size or zero if not using window */+ var whave; /* valid bytes in the window */+ var wnext; /* window write index */+ var window; /* allocated sliding window, if wsize != 0 */+ var hold; /* local strm.hold */+ var bits; /* local strm.bits */+ var lcode; /* local strm.lencode */+ var dcode; /* local strm.distcode */+ var lmask; /* mask for first level of length codes */+ var dmask; /* mask for first level of distance codes */+ var here; /* retrieved table entry */+ var op; /* code bits, operation, extra bits, or */+ /* window position, window bytes to copy */+ var len; /* match length, unused bytes */+ var dist; /* match distance */+ var from; /* where to copy match from */+ var from_source;- state.distbits = 6;- //state.distcode.copy(state.codes);- // Switch to use dynamic table- state.distcode = state.distdyn;- opts = {bits: state.distbits};- ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);- // We have separate tables & no pointers. 2 commented lines below not needed.- // state.next_index = opts.table_index;- state.distbits = opts.bits;- // state.distcode = state.next;- if (ret) {- strm.msg = 'invalid distances set';- state.mode = BAD;- break;- }- //Tracev((stderr, 'inflate: codes ok\n'));- state.mode = LEN_;- if (flush === Z_TREES) { break inf_leave; }- /* falls through */- case LEN_:- state.mode = LEN;- /* falls through */- case LEN:- if (have >= 6 && left >= 258) {- //--- RESTORE() ---- strm.next_out = put;- strm.avail_out = left;- strm.next_in = next;- strm.avail_in = have;- state.hold = hold;- state.bits = bits;- //---- inflate_fast(strm, _out);- //--- LOAD() ---- put = strm.next_out;- output = strm.output;- left = strm.avail_out;- next = strm.next_in;- input = strm.input;- have = strm.avail_in;- hold = state.hold;- bits = state.bits;- //---+ var input, output; // JS specific, because we have no pointers- if (state.mode === TYPE) {- state.back = -1;- }- break;- }- state.back = 0;- for (;;) {- here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/- here_bits = here >>> 24;- here_op = (here >>> 16) & 0xff;- here_val = here & 0xffff;+ /* copy state to local variables */+ state = strm.state;+ //here = state.here;+ _in = strm.next_in;+ input = strm.input;+ last = _in + (strm.avail_in - 5);+ _out = strm.next_out;+ output = strm.output;+ beg = _out - (start - strm.avail_out);+ end = _out + (strm.avail_out - 257);+//#ifdef INFLATE_STRICT+ dmax = state.dmax;+//#endif+ wsize = state.wsize;+ whave = state.whave;+ wnext = state.wnext;+ window = state.window;+ hold = state.hold;+ bits = state.bits;+ lcode = state.lencode;+ dcode = state.distcode;+ lmask = (1 << state.lenbits) - 1;+ dmask = (1 << state.distbits) - 1;- if (here_bits <= bits) { break; }- //--- PULLBYTE() ---//- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;- //---//- }- if (here_op && (here_op & 0xf0) === 0) {- last_bits = here_bits;- last_op = here_op;- last_val = here_val;- for (;;) {- here = state.lencode[last_val +- ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];- here_bits = here >>> 24;- here_op = (here >>> 16) & 0xff;- here_val = here & 0xffff;- if ((last_bits + here_bits) <= bits) { break; }- //--- PULLBYTE() ---//- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;- //---//- }- //--- DROPBITS(last.bits) ---//- hold >>>= last_bits;- bits -= last_bits;- //---//- state.back += last_bits;- }- //--- DROPBITS(here.bits) ---//- hold >>>= here_bits;- bits -= here_bits;- //---//- state.back += here_bits;- state.length = here_val;- if (here_op === 0) {- //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?- // "inflate: literal '%c'\n" :- // "inflate: literal 0x%02x\n", here.val));- state.mode = LIT;- break;- }- if (here_op & 32) {- //Tracevv((stderr, "inflate: end of block\n"));- state.back = -1;- state.mode = TYPE;- break;- }- if (here_op & 64) {- strm.msg = 'invalid literal/length code';- state.mode = BAD;- break;- }- state.extra = here_op & 15;- state.mode = LENEXT;- /* falls through */- case LENEXT:- if (state.extra) {- //=== NEEDBITS(state.extra);- n = state.extra;- while (bits < n) {- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;- }- //===//- state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;- //--- DROPBITS(state.extra) ---//- hold >>>= state.extra;- bits -= state.extra;- //---//- state.back += state.extra;- }- //Tracevv((stderr, "inflate: length %u\n", state.length));- state.was = state.length;- state.mode = DIST;- /* falls through */- case DIST:- for (;;) {- here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/- here_bits = here >>> 24;- here_op = (here >>> 16) & 0xff;- here_val = here & 0xffff;+ /* decode literals and length/distances until end-of-block or not enough+ input data or output space */- if ((here_bits) <= bits) { break; }- //--- PULLBYTE() ---//- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;- //---//- }- if ((here_op & 0xf0) === 0) {- last_bits = here_bits;- last_op = here_op;- last_val = here_val;- for (;;) {- here = state.distcode[last_val +- ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];- here_bits = here >>> 24;- here_op = (here >>> 16) & 0xff;- here_val = here & 0xffff;+ top:+ do {+ if (bits < 15) {+ hold += input[_in++] << bits;+ bits += 8;+ hold += input[_in++] << bits;+ bits += 8;+ }- if ((last_bits + here_bits) <= bits) { break; }- //--- PULLBYTE() ---//- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;- //---//- }- //--- DROPBITS(last.bits) ---//- hold >>>= last_bits;- bits -= last_bits;- //---//- state.back += last_bits;- }- //--- DROPBITS(here.bits) ---//- hold >>>= here_bits;- bits -= here_bits;- //---//- state.back += here_bits;- if (here_op & 64) {- strm.msg = 'invalid distance code';- state.mode = BAD;- break;+ here = lcode[hold & lmask];++ dolen:+ for (;;) { // Goto emulation+ op = here >>> 24/*here.bits*/;+ hold >>>= op;+ bits -= op;+ op = (here >>> 16) & 0xff/*here.op*/;+ if (op === 0) { /* literal */+ //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?+ // "inflate: literal '%c'\n" :+ // "inflate: literal 0x%02x\n", here.val));+ output[_out++] = here & 0xffff/*here.val*/;}- state.offset = here_val;- state.extra = (here_op) & 15;- state.mode = DISTEXT;- /* falls through */- case DISTEXT:- if (state.extra) {- //=== NEEDBITS(state.extra);- n = state.extra;- while (bits < n) {- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;+ else if (op & 16) { /* length base */+ len = here & 0xffff/*here.val*/;+ op &= 15; /* number of extra bits */+ if (op) {+ if (bits < op) {+ hold += input[_in++] << bits;+ bits += 8;+ }+ len += hold & ((1 << op) - 1);+ hold >>>= op;+ bits -= op;+ }+ //Tracevv((stderr, "inflate: length %u\n", len));+ if (bits < 15) {+ hold += input[_in++] << bits;+ bits += 8;+ hold += input[_in++] << bits;bits += 8;}- //===//- state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;- //--- DROPBITS(state.extra) ---//- hold >>>= state.extra;- bits -= state.extra;- //---//- state.back += state.extra;- }+ here = dcode[hold & dmask];++ dodist:+ for (;;) { // goto emulation+ op = here >>> 24/*here.bits*/;+ hold >>>= op;+ bits -= op;+ op = (here >>> 16) & 0xff/*here.op*/;++ if (op & 16) { /* distance base */+ dist = here & 0xffff/*here.val*/;+ op &= 15; /* number of extra bits */+ if (bits < op) {+ hold += input[_in++] << bits;+ bits += 8;+ if (bits < op) {+ hold += input[_in++] << bits;+ bits += 8;+ }+ }+ dist += hold & ((1 << op) - 1);//#ifdef INFLATE_STRICT- if (state.offset > state.dmax) {- strm.msg = 'invalid distance too far back';- state.mode = BAD;- break;- }+ if (dist > dmax) {+ strm.msg = 'invalid distance too far back';+ state.mode = BAD;+ break top;+ }//#endif- //Tracevv((stderr, "inflate: distance %u\n", state.offset));- state.mode = MATCH;- /* falls through */- case MATCH:- if (left === 0) { break inf_leave; }- copy = _out - left;- if (state.offset > copy) { /* copy from window */- copy = state.offset - copy;- if (copy > state.whave) {- if (state.sane) {- strm.msg = 'invalid distance too far back';- state.mode = BAD;- break;- }+ hold >>>= op;+ bits -= op;+ //Tracevv((stderr, "inflate: distance %u\n", dist));+ op = _out - beg; /* max distance in output */+ if (dist > op) { /* see if copy from window */+ op = dist - op; /* distance back in window */+ if (op > whave) {+ if (state.sane) {+ strm.msg = 'invalid distance too far back';+ state.mode = BAD;+ break top;+ }+// (!) This block is disabled in zlib defailts,// don't enable it for binary compatibility//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR-// Trace((stderr, "inflate.c too far\n"));-// copy -= state.whave;-// if (copy > state.length) { copy = state.length; }-// if (copy > left) { copy = left; }-// left -= copy;-// state.length -= copy;-// do {-// output[put++] = 0;-// } while (--copy);-// if (state.length === 0) { state.mode = LEN; }-// break;+// if (len <= op - whave) {+// do {+// output[_out++] = 0;+// } while (--len);+// continue top;+// }+// len -= op - whave;+// do {+// output[_out++] = 0;+// } while (--op > whave);+// if (op === 0) {+// from = _out - dist;+// do {+// output[_out++] = output[from++];+// } while (--len);+// continue top;+// }//#endif+ }+ from = 0; // window index+ from_source = window;+ if (wnext === 0) { /* very common case */+ from += wsize - op;+ if (op < len) { /* some from window */+ len -= op;+ do {+ output[_out++] = window[from++];+ } while (--op);+ from = _out - dist; /* rest from output */+ from_source = output;+ }+ }+ else if (wnext < op) { /* wrap around window */+ from += wsize + wnext - op;+ op -= wnext;+ if (op < len) { /* some from end of window */+ len -= op;+ do {+ output[_out++] = window[from++];+ } while (--op);+ from = 0;+ if (wnext < len) { /* some from start of window */+ op = wnext;+ len -= op;+ do {+ output[_out++] = window[from++];+ } while (--op);+ from = _out - dist; /* rest from output */+ from_source = output;+ }+ }+ }+ else { /* contiguous in window */+ from += wnext - op;+ if (op < len) { /* some from window */+ len -= op;+ do {+ output[_out++] = window[from++];+ } while (--op);+ from = _out - dist; /* rest from output */+ from_source = output;+ }+ }+ while (len > 2) {+ output[_out++] = from_source[from++];+ output[_out++] = from_source[from++];+ output[_out++] = from_source[from++];+ len -= 3;+ }+ if (len) {+ output[_out++] = from_source[from++];+ if (len > 1) {+ output[_out++] = from_source[from++];+ }+ }+ }+ else {+ from = _out - dist; /* copy direct from output */+ do { /* minimum length is three */+ output[_out++] = output[from++];+ output[_out++] = output[from++];+ output[_out++] = output[from++];+ len -= 3;+ } while (len > 2);+ if (len) {+ output[_out++] = output[from++];+ if (len > 1) {+ output[_out++] = output[from++];+ }+ }+ }+ }+ else if ((op & 64) === 0) { /* 2nd level distance code */+ here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];+ continue dodist;+ }+ else {+ strm.msg = 'invalid distance code';+ state.mode = BAD;+ break top;+ }++ break; // need to emulate goto via "continue"}- if (copy > state.wnext) {- copy -= state.wnext;- from = state.wsize - copy;- }- else {- from = state.wnext - copy;- }- if (copy > state.length) { copy = state.length; }- from_source = state.window;}- else { /* copy from output */- from_source = output;- from = put - state.offset;- copy = state.length;+ else if ((op & 64) === 0) { /* 2nd level length code */+ here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];+ continue dolen;}- if (copy > left) { copy = left; }- left -= copy;- state.length -= copy;- do {- output[put++] = from_source[from++];- } while (--copy);- if (state.length === 0) { state.mode = LEN; }- break;- case LIT:- if (left === 0) { break inf_leave; }- output[put++] = state.length;- left--;- state.mode = LEN;- break;- case CHECK:- if (state.wrap) {- //=== NEEDBITS(32);- while (bits < 32) {- if (have === 0) { break inf_leave; }- have--;- // Use '|' insdead of '+' to make sure that result is signed- hold |= input[next++] << bits;- bits += 8;- }- //===//- _out -= left;- strm.total_out += _out;- state.total += _out;- if (_out) {- strm.adler = state.check =- /*UPDATE(state.check, put - _out, _out);*/- (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));-- }- _out = left;- // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too- if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {- strm.msg = 'incorrect data check';- state.mode = BAD;- break;- }- //=== INITBITS();- hold = 0;- bits = 0;- //===//- //Tracev((stderr, "inflate: check matches trailer\n"));+ else if (op & 32) { /* end-of-block */+ //Tracevv((stderr, "inflate: end of block\n"));+ state.mode = TYPE;+ break top;}- state.mode = LENGTH;- /* falls through */- case LENGTH:- if (state.wrap && state.flags) {- //=== NEEDBITS(32);- while (bits < 32) {- if (have === 0) { break inf_leave; }- have--;- hold += input[next++] << bits;- bits += 8;- }- //===//- if (hold !== (state.total & 0xffffffff)) {- strm.msg = 'incorrect length check';- state.mode = BAD;- break;- }- //=== INITBITS();- hold = 0;- bits = 0;- //===//- //Tracev((stderr, "inflate: length matches trailer\n"));+ else {+ strm.msg = 'invalid literal/length code';+ state.mode = BAD;+ break top;}- state.mode = DONE;- /* falls through */- case DONE:- ret = Z_STREAM_END;- break inf_leave;- case BAD:- ret = Z_DATA_ERROR;- break inf_leave;- case MEM:- return Z_MEM_ERROR;- case SYNC:- /* falls through */- default:- return Z_STREAM_ERROR;++ break; // need to emulate goto via "continue"}- }+ } while (_in < last && _out < end);++ /* return unused bytes (on entry, bits < 8, so in won't go too far back) */+ len = bits >> 3;+ _in -= len;+ bits -= len << 3;+ hold &= (1 << bits) - 1;++ /* update state and return */+ strm.next_in = _in;+ strm.next_out = _out;+ strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));+ strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));+ state.hold = hold;+ state.bits = bits;+ return;+};++},{}],78:[function(require,module,exports){+'use strict';+++var utils = require('../utils/common');+var adler32 = require('./adler32');+var crc32 = require('./crc32');+var inflate_fast = require('./inffast');+var inflate_table = require('./inftrees');++var CODES = 0;+var LENS = 1;+var DISTS = 2;++/* Public constants ==========================================================*/+/* ===========================================================================*/+++/* Allowed flush values; see deflate() and inflate() below for details */+//var Z_NO_FLUSH = 0;+//var Z_PARTIAL_FLUSH = 1;+//var Z_SYNC_FLUSH = 2;+//var Z_FULL_FLUSH = 3;+var Z_FINISH = 4;+var Z_BLOCK = 5;+var Z_TREES = 6;+++/* Return codes for the compression/decompression functions. Negative values+ * are errors, positive values are used for special but normal events.+ */+var Z_OK = 0;+var Z_STREAM_END = 1;+var Z_NEED_DICT = 2;+//var Z_ERRNO = -1;+var Z_STREAM_ERROR = -2;+var Z_DATA_ERROR = -3;+var Z_MEM_ERROR = -4;+var Z_BUF_ERROR = -5;+//var Z_VERSION_ERROR = -6;++/* The deflate compression method */+var Z_DEFLATED = 8;+++/* STATES ====================================================================*/+/* ===========================================================================*/+++var HEAD = 1; /* i: waiting for magic header */+var FLAGS = 2; /* i: waiting for method and flags (gzip) */+var TIME = 3; /* i: waiting for modification time (gzip) */+var OS = 4; /* i: waiting for extra flags and operating system (gzip) */+var EXLEN = 5; /* i: waiting for extra length (gzip) */+var EXTRA = 6; /* i: waiting for extra bytes (gzip) */+var NAME = 7; /* i: waiting for end of file name (gzip) */+var COMMENT = 8; /* i: waiting for end of comment (gzip) */+var HCRC = 9; /* i: waiting for header crc (gzip) */+var DICTID = 10; /* i: waiting for dictionary check value */+var DICT = 11; /* waiting for inflateSetDictionary() call */+var TYPE = 12; /* i: waiting for type bits, including last-flag bit */+var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */+var STORED = 14; /* i: waiting for stored size (length and complement) */+var COPY_ = 15; /* i/o: same as COPY below, but only first time in */+var COPY = 16; /* i/o: waiting for input or output to copy stored block */+var TABLE = 17; /* i: waiting for dynamic block table lengths */+var LENLENS = 18; /* i: waiting for code length code lengths */+var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */+var LEN_ = 20; /* i: same as LEN below, but only first time in */+var LEN = 21; /* i: waiting for length/lit/eob code */+var LENEXT = 22; /* i: waiting for length extra bits */+var DIST = 23; /* i: waiting for distance code */+var DISTEXT = 24; /* i: waiting for distance extra bits */+var MATCH = 25; /* o: waiting for output space to copy string */+var LIT = 26; /* o: waiting for output space to write literal */+var CHECK = 27; /* i: waiting for 32-bit check value */+var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */+var DONE = 29; /* finished check, done -- remain here until reset */+var BAD = 30; /* got a data error -- remain here until reset */+var MEM = 31; /* got an inflate() memory error -- remain here until reset */+var SYNC = 32; /* looking for synchronization bytes to restart inflate() */++/* ===========================================================================*/++++var ENOUGH_LENS = 852;+var ENOUGH_DISTS = 592;+//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);++var MAX_WBITS = 15;+/* 32K LZ77 window */+var DEF_WBITS = MAX_WBITS;+++function ZSWAP32(q) {+ return (((q >>> 24) & 0xff) ++ ((q >>> 8) & 0xff00) ++ ((q & 0xff00) << 8) ++ ((q & 0xff) << 24));+}+++function InflateState() {+ this.mode = 0; /* current inflate mode */+ this.last = false; /* true if processing last block */+ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */+ this.havedict = false; /* true if dictionary provided */+ this.flags = 0; /* gzip header method and flags (0 if zlib) */+ this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */+ this.check = 0; /* protected copy of check value */+ this.total = 0; /* protected copy of output count */+ // TODO: may be {}+ this.head = null; /* where to save gzip header information */++ /* sliding window */+ this.wbits = 0; /* log base 2 of requested window size */+ this.wsize = 0; /* window size or zero if not using window */+ this.whave = 0; /* valid bytes in the window */+ this.wnext = 0; /* window write index */+ this.window = null; /* allocated sliding window, if needed */++ /* bit accumulator */+ this.hold = 0; /* input bit accumulator */+ this.bits = 0; /* number of bits in "in" */++ /* for string and stored block copying */+ this.length = 0; /* literal or length of data to copy */+ this.offset = 0; /* distance back to copy string from */++ /* for table and code decoding */+ this.extra = 0; /* extra bits needed */++ /* fixed and dynamic code tables */+ this.lencode = null; /* starting table for length/literal codes */+ this.distcode = null; /* starting table for distance codes */+ this.lenbits = 0; /* index bits for lencode */+ this.distbits = 0; /* index bits for distcode */- // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"+ /* dynamic table building */+ this.ncode = 0; /* number of code length code lengths */+ this.nlen = 0; /* number of length code lengths */+ this.ndist = 0; /* number of distance code lengths */+ this.have = 0; /* number of code lengths in lens[] */+ this.next = null; /* next available space in codes[] */++ this.lens = new utils.Buf16(320); /* temporary storage for code lengths */+ this.work = new utils.Buf16(288); /* work area for code table building *//*- Return from inflate(), updating the total counts and the check value.- If there was no progress during the inflate() call, return a buffer- error. Call updatewindow() to create and/or update the window state.- Note: a memory error from inflate() is non-recoverable.- */+ because we don't have pointers in js, we use lencode and distcode directly+ as buffers so we don't need codes+ */+ //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */+ this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */+ this.distdyn = null; /* dynamic table for distance codes (JS specific) */+ this.sane = 0; /* if false, allow invalid distance too far */+ this.back = 0; /* bits back of last unprocessed length/lit */+ this.was = 0; /* initial length of match */+}- //--- RESTORE() ---- strm.next_out = put;- strm.avail_out = left;- strm.next_in = next;- strm.avail_in = have;- state.hold = hold;- state.bits = bits;- //---+function inflateResetKeep(strm) {+ var state;- if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&- (state.mode < CHECK || flush !== Z_FINISH))) {- if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {- state.mode = MEM;- return Z_MEM_ERROR;- }- }- _in -= strm.avail_in;- _out -= strm.avail_out;- strm.total_in += _in;- strm.total_out += _out;- state.total += _out;- if (state.wrap && _out) {- strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/- (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));- }- strm.data_type = state.bits + (state.last ? 64 : 0) +- (state.mode === TYPE ? 128 : 0) +- (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);- if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {- ret = Z_BUF_ERROR;+ if (!strm || !strm.state) { return Z_STREAM_ERROR; }+ state = strm.state;+ strm.total_in = strm.total_out = state.total = 0;+ strm.msg = ''; /*Z_NULL*/+ if (state.wrap) { /* to support ill-conceived Java test suite */+ strm.adler = state.wrap & 1;}- return ret;+ state.mode = HEAD;+ state.last = 0;+ state.havedict = 0;+ state.dmax = 32768;+ state.head = null/*Z_NULL*/;+ state.hold = 0;+ state.bits = 0;+ //state.lencode = state.distcode = state.next = state.codes;+ state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);+ state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);++ state.sane = 1;+ state.back = -1;+ //Tracev((stderr, "inflate: reset\n"));+ return Z_OK;}-function inflateEnd(strm) {+function inflateReset(strm) {+ var state;- if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {- return Z_STREAM_ERROR;- }+ if (!strm || !strm.state) { return Z_STREAM_ERROR; }+ state = strm.state;+ state.wsize = 0;+ state.whave = 0;+ state.wnext = 0;+ return inflateResetKeep(strm);- var state = strm.state;- if (state.window) {- state.window = null;- }- strm.state = null;- return Z_OK;}-function inflateGetHeader(strm, head) {+function inflateReset2(strm, windowBits) {+ var wrap;var state;- /* check state */+ /* get the state */if (!strm || !strm.state) { return Z_STREAM_ERROR; }state = strm.state;- if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }- /* save header structure */- state.head = head;- head.done = false;- return Z_OK;+ /* extract wrap request from windowBits parameter */+ if (windowBits < 0) {+ wrap = 0;+ windowBits = -windowBits;+ }+ else {+ wrap = (windowBits >> 4) + 1;+ if (windowBits < 48) {+ windowBits &= 15;+ }+ }++ /* set number of window bits, free window if different */+ if (windowBits && (windowBits < 8 || windowBits > 15)) {+ return Z_STREAM_ERROR;+ }+ if (state.window !== null && state.wbits !== windowBits) {+ state.window = null;+ }++ /* update state and reset the rest of it */+ state.wrap = wrap;+ state.wbits = windowBits;+ return inflateReset(strm);}+function inflateInit2(strm, windowBits) {+ var ret;+ var state;-exports.inflateReset = inflateReset;-exports.inflateReset2 = inflateReset2;-exports.inflateResetKeep = inflateResetKeep;-exports.inflateInit = inflateInit;-exports.inflateInit2 = inflateInit2;-exports.inflate = inflate;-exports.inflateEnd = inflateEnd;-exports.inflateGetHeader = inflateGetHeader;-exports.inflateInfo = 'pako inflate (from Nodeca project)';+ if (!strm) { return Z_STREAM_ERROR; }+ //strm.msg = Z_NULL; /* in case we return an error */-/* Not implemented-exports.inflateCopy = inflateCopy;-exports.inflateGetDictionary = inflateGetDictionary;-exports.inflateMark = inflateMark;-exports.inflatePrime = inflatePrime;-exports.inflateSetDictionary = inflateSetDictionary;-exports.inflateSync = inflateSync;-exports.inflateSyncPoint = inflateSyncPoint;-exports.inflateUndermine = inflateUndermine;-*/-},{"../utils/common":69,"./adler32":71,"./crc32":73,"./inffast":76,"./inftrees":78}],78:[function(require,module,exports){-'use strict';+ state = new InflateState();+ //if (state === Z_NULL) return Z_MEM_ERROR;+ //Tracev((stderr, "inflate: allocated\n"));+ strm.state = state;+ state.window = null/*Z_NULL*/;+ ret = inflateReset2(strm, windowBits);+ if (ret !== Z_OK) {+ strm.state = null/*Z_NULL*/;+ }+ return ret;+}-var utils = require('../utils/common');+function inflateInit(strm) {+ return inflateInit2(strm, DEF_WBITS);+}-var MAXBITS = 15;-var ENOUGH_LENS = 852;-var ENOUGH_DISTS = 592;-//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);-var CODES = 0;-var LENS = 1;-var DISTS = 2;+/*+ Return state with length and distance decoding tables and index sizes set to+ fixed code decoding. Normally this returns fixed tables from inffixed.h.+ If BUILDFIXED is defined, then instead this routine builds the tables the+ first time it's called, and returns those tables the first time and+ thereafter. This reduces the size of the code by about 2K bytes, in+ exchange for a little execution time. However, BUILDFIXED should not be+ used for threaded applications, since the rewriting of the tables and virgin+ may not be thread-safe.+ */+var virgin = true;-var lbase = [ /* Length codes 257..285 base */- 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,- 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0-];+var lenfix, distfix; // We have no pointers in JS, so keep tables separate-var lext = [ /* Length codes 257..285 extra */- 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,- 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78-];+function fixedtables(state) {+ /* build fixed huffman tables if first call (may not be thread safe) */+ if (virgin) {+ var sym;-var dbase = [ /* Distance codes 0..29 base */- 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,- 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,- 8193, 12289, 16385, 24577, 0, 0-];+ lenfix = new utils.Buf32(512);+ distfix = new utils.Buf32(32);-var dext = [ /* Distance codes 0..29 extra */- 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,- 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,- 28, 28, 29, 29, 64, 64-];+ /* literal/length table */+ sym = 0;+ while (sym < 144) { state.lens[sym++] = 8; }+ while (sym < 256) { state.lens[sym++] = 9; }+ while (sym < 280) { state.lens[sym++] = 7; }+ while (sym < 288) { state.lens[sym++] = 8; }-module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)-{- var bits = opts.bits;- //here = opts.here; /* table entry for duplication */+ inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});- var len = 0; /* a code's length in bits */- var sym = 0; /* index of code symbols */- var min = 0, max = 0; /* minimum and maximum code lengths */- var root = 0; /* number of index bits for root table */- var curr = 0; /* number of index bits for current table */- var drop = 0; /* code bits to drop for sub-table */- var left = 0; /* number of prefix codes available */- var used = 0; /* code entries in table used */- var huff = 0; /* Huffman code */- var incr; /* for incrementing code, index */- var fill; /* index for replicating entries */- var low; /* low bits for current root entry */- var mask; /* mask for low root bits */- var next; /* next available space in table */- var base = null; /* base value table to use */- var base_index = 0;-// var shoextra; /* extra bits table to use */- var end; /* use base and extra for symbol > end */- var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */- var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */- var extra = null;- var extra_index = 0;+ /* distance table */+ sym = 0;+ while (sym < 32) { state.lens[sym++] = 5; }++ inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});++ /* do this just once */+ virgin = false;+ }- var here_bits, here_op, here_val;+ state.lencode = lenfix;+ state.lenbits = 9;+ state.distcode = distfix;+ state.distbits = 5;+}- /*- Process a set of code lengths to create a canonical Huffman code. The- code lengths are lens[0..codes-1]. Each length corresponds to the- symbols 0..codes-1. The Huffman code is generated by first sorting the- symbols by length from short to long, and retaining the symbol order- for codes with equal lengths. Then the code starts with all zero bits- for the first code of the shortest length, and the codes are integer- increments for the same length, and zeros are appended as the length- increases. For the deflate format, these bits are stored backwards- from their more natural integer increment ordering, and so when the- decoding tables are built in the large loop below, the integer codes- are incremented backwards.- This routine assumes, but does not check, that all of the entries in- lens[] are in the range 0..MAXBITS. The caller must assure this.- 1..MAXBITS is interpreted as that code length. zero means that that- symbol does not occur in this code.+/*+ Update the window with the last wsize (normally 32K) bytes written before+ returning. If window does not exist yet, create it. This is only called+ when a window is already in use, or when output has been written during this+ inflate call, but the end of the deflate stream has not been reached yet.+ It is also called to create a window for dictionary data when a dictionary+ is loaded.- The codes are sorted by computing a count of codes for each length,- creating from that a table of starting indices for each length in the- sorted table, and then entering the symbols in order in the sorted- table. The sorted table is work[], with that space being provided by- the caller.+ Providing output buffers larger than 32K to inflate() should provide a speed+ advantage, since only the last 32K of output is copied to the sliding window+ upon return from inflate(), and since all distances after the first 32K of+ output will fall in the output data, making match copies simpler and faster.+ The advantage may be dependent on the size of the processor's data caches.+ */+function updatewindow(strm, src, end, copy) {+ var dist;+ var state = strm.state;- The length counts are used for other purposes as well, i.e. finding- the minimum and maximum length codes, determining if there are any- codes at all, checking for a valid set of lengths, and looking ahead- at length counts to determine sub-table sizes when building the- decoding tables.- */+ /* if it hasn't been done already, allocate space for the window */+ if (state.window === null) {+ state.wsize = 1 << state.wbits;+ state.wnext = 0;+ state.whave = 0;- /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */- for (len = 0; len <= MAXBITS; len++) {- count[len] = 0;- }- for (sym = 0; sym < codes; sym++) {- count[lens[lens_index + sym]]++;+ state.window = new utils.Buf8(state.wsize);}- /* bound code lengths, force root to be within code lengths */- root = bits;- for (max = MAXBITS; max >= 1; max--) {- if (count[max] !== 0) { break; }+ /* copy state->wsize or less output bytes into the circular window */+ if (copy >= state.wsize) {+ utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);+ state.wnext = 0;+ state.whave = state.wsize;}- if (root > max) {- root = max;+ else {+ dist = state.wsize - state.wnext;+ if (dist > copy) {+ dist = copy;+ }+ //zmemcpy(state->window + state->wnext, end - copy, dist);+ utils.arraySet(state.window,src, end - copy, dist, state.wnext);+ copy -= dist;+ if (copy) {+ //zmemcpy(state->window, end - copy, copy);+ utils.arraySet(state.window,src, end - copy, copy, 0);+ state.wnext = copy;+ state.whave = state.wsize;+ }+ else {+ state.wnext += dist;+ if (state.wnext === state.wsize) { state.wnext = 0; }+ if (state.whave < state.wsize) { state.whave += dist; }+ }}- if (max === 0) { /* no symbols to code at all */- //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */- //table.bits[opts.table_index] = 1; //here.bits = (var char)1;- //table.val[opts.table_index++] = 0; //here.val = (var short)0;- table[table_index++] = (1 << 24) | (64 << 16) | 0;+ return 0;+}+function inflate(strm, flush) {+ var state;+ var input, output; // input/output buffers+ var next; /* next input INDEX */+ var put; /* next output INDEX */+ var have, left; /* available input and output */+ var hold; /* bit buffer */+ var bits; /* bits in bit buffer */+ var _in, _out; /* save starting available input and output */+ var copy; /* number of stored or match bytes to copy */+ var from; /* where to copy match bytes from */+ var from_source;+ var here = 0; /* current decoding table entry */+ var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)+ //var last; /* parent table entry */+ var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)+ var len; /* length to copy for repeats, bits to drop */+ var ret; /* return code */+ var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */+ var opts;- //table.op[opts.table_index] = 64;- //table.bits[opts.table_index] = 1;- //table.val[opts.table_index++] = 0;- table[table_index++] = (1 << 24) | (64 << 16) | 0;+ var n; // temporary var for NEED_BITS- opts.bits = 1;- return 0; /* no symbols, but wait for decoding to report error */- }- for (min = 1; min < max; min++) {- if (count[min] !== 0) { break; }- }- if (root < min) {- root = min;- }+ var order = /* permutation of code lengths */+ [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];- /* check for an over-subscribed or incomplete set of lengths */- left = 1;- for (len = 1; len <= MAXBITS; len++) {- left <<= 1;- left -= count[len];- if (left < 0) {- return -1;- } /* over-subscribed */- }- if (left > 0 && (type === CODES || max !== 1)) {- return -1; /* incomplete set */++ if (!strm || !strm.state || !strm.output ||+ (!strm.input && strm.avail_in !== 0)) {+ return Z_STREAM_ERROR;}- /* generate offsets into symbol table for each length for sorting */- offs[1] = 0;- for (len = 1; len < MAXBITS; len++) {- offs[len + 1] = offs[len] + count[len];- }+ state = strm.state;+ if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */+++ //--- LOAD() ---+ put = strm.next_out;+ output = strm.output;+ left = strm.avail_out;+ next = strm.next_in;+ input = strm.input;+ have = strm.avail_in;+ hold = state.hold;+ bits = state.bits;+ //---++ _in = have;+ _out = left;+ ret = Z_OK;++ inf_leave: // goto emulation+ for (;;) {+ switch (state.mode) {+ case HEAD:+ if (state.wrap === 0) {+ state.mode = TYPEDO;+ break;+ }+ //=== NEEDBITS(16);+ while (bits < 16) {+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ }+ //===//+ if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */+ state.check = 0/*crc32(0L, Z_NULL, 0)*/;+ //=== CRC2(state.check, hold);+ hbuf[0] = hold & 0xff;+ hbuf[1] = (hold >>> 8) & 0xff;+ state.check = crc32(state.check, hbuf, 2, 0);+ //===//++ //=== INITBITS();+ hold = 0;+ bits = 0;+ //===//+ state.mode = FLAGS;+ break;+ }+ state.flags = 0; /* expect zlib header */+ if (state.head) {+ state.head.done = false;+ }+ if (!(state.wrap & 1) || /* check if zlib header allowed */+ (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {+ strm.msg = 'incorrect header check';+ state.mode = BAD;+ break;+ }+ if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {+ strm.msg = 'unknown compression method';+ state.mode = BAD;+ break;+ }+ //--- DROPBITS(4) ---//+ hold >>>= 4;+ bits -= 4;+ //---//+ len = (hold & 0x0f)/*BITS(4)*/ + 8;+ if (state.wbits === 0) {+ state.wbits = len;+ }+ else if (len > state.wbits) {+ strm.msg = 'invalid window size';+ state.mode = BAD;+ break;+ }+ state.dmax = 1 << len;+ //Tracev((stderr, "inflate: zlib header ok\n"));+ strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;+ state.mode = hold & 0x200 ? DICTID : TYPE;+ //=== INITBITS();+ hold = 0;+ bits = 0;+ //===//+ break;+ case FLAGS:+ //=== NEEDBITS(16); */+ while (bits < 16) {+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ }+ //===//+ state.flags = hold;+ if ((state.flags & 0xff) !== Z_DEFLATED) {+ strm.msg = 'unknown compression method';+ state.mode = BAD;+ break;+ }+ if (state.flags & 0xe000) {+ strm.msg = 'unknown header flags set';+ state.mode = BAD;+ break;+ }+ if (state.head) {+ state.head.text = ((hold >> 8) & 1);+ }+ if (state.flags & 0x0200) {+ //=== CRC2(state.check, hold);+ hbuf[0] = hold & 0xff;+ hbuf[1] = (hold >>> 8) & 0xff;+ state.check = crc32(state.check, hbuf, 2, 0);+ //===//+ }+ //=== INITBITS();+ hold = 0;+ bits = 0;+ //===//+ state.mode = TIME;+ /* falls through */+ case TIME:+ //=== NEEDBITS(32); */+ while (bits < 32) {+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ }+ //===//+ if (state.head) {+ state.head.time = hold;+ }+ if (state.flags & 0x0200) {+ //=== CRC4(state.check, hold)+ hbuf[0] = hold & 0xff;+ hbuf[1] = (hold >>> 8) & 0xff;+ hbuf[2] = (hold >>> 16) & 0xff;+ hbuf[3] = (hold >>> 24) & 0xff;+ state.check = crc32(state.check, hbuf, 4, 0);+ //===+ }+ //=== INITBITS();+ hold = 0;+ bits = 0;+ //===//+ state.mode = OS;+ /* falls through */+ case OS:+ //=== NEEDBITS(16); */+ while (bits < 16) {+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ }+ //===//+ if (state.head) {+ state.head.xflags = (hold & 0xff);+ state.head.os = (hold >> 8);+ }+ if (state.flags & 0x0200) {+ //=== CRC2(state.check, hold);+ hbuf[0] = hold & 0xff;+ hbuf[1] = (hold >>> 8) & 0xff;+ state.check = crc32(state.check, hbuf, 2, 0);+ //===//+ }+ //=== INITBITS();+ hold = 0;+ bits = 0;+ //===//+ state.mode = EXLEN;+ /* falls through */+ case EXLEN:+ if (state.flags & 0x0400) {+ //=== NEEDBITS(16); */+ while (bits < 16) {+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ }+ //===//+ state.length = hold;+ if (state.head) {+ state.head.extra_len = hold;+ }+ if (state.flags & 0x0200) {+ //=== CRC2(state.check, hold);+ hbuf[0] = hold & 0xff;+ hbuf[1] = (hold >>> 8) & 0xff;+ state.check = crc32(state.check, hbuf, 2, 0);+ //===//+ }+ //=== INITBITS();+ hold = 0;+ bits = 0;+ //===//+ }+ else if (state.head) {+ state.head.extra = null/*Z_NULL*/;+ }+ state.mode = EXTRA;+ /* falls through */+ case EXTRA:+ if (state.flags & 0x0400) {+ copy = state.length;+ if (copy > have) { copy = have; }+ if (copy) {+ if (state.head) {+ len = state.head.extra_len - state.length;+ if (!state.head.extra) {+ // Use untyped array for more conveniend processing later+ state.head.extra = new Array(state.head.extra_len);+ }+ utils.arraySet(+ state.head.extra,+ input,+ next,+ // extra field is limited to 65536 bytes+ // - no need for additional size check+ copy,+ /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/+ len+ );+ //zmemcpy(state.head.extra + len, next,+ // len + copy > state.head.extra_max ?+ // state.head.extra_max - len : copy);+ }+ if (state.flags & 0x0200) {+ state.check = crc32(state.check, input, copy, next);+ }+ have -= copy;+ next += copy;+ state.length -= copy;+ }+ if (state.length) { break inf_leave; }+ }+ state.length = 0;+ state.mode = NAME;+ /* falls through */+ case NAME:+ if (state.flags & 0x0800) {+ if (have === 0) { break inf_leave; }+ copy = 0;+ do {+ // TODO: 2 or 1 bytes?+ len = input[next + copy++];+ /* use constant limit because in js we should not preallocate memory */+ if (state.head && len &&+ (state.length < 65536 /*state.head.name_max*/)) {+ state.head.name += String.fromCharCode(len);+ }+ } while (len && copy < have);++ if (state.flags & 0x0200) {+ state.check = crc32(state.check, input, copy, next);+ }+ have -= copy;+ next += copy;+ if (len) { break inf_leave; }+ }+ else if (state.head) {+ state.head.name = null;+ }+ state.length = 0;+ state.mode = COMMENT;+ /* falls through */+ case COMMENT:+ if (state.flags & 0x1000) {+ if (have === 0) { break inf_leave; }+ copy = 0;+ do {+ len = input[next + copy++];+ /* use constant limit because in js we should not preallocate memory */+ if (state.head && len &&+ (state.length < 65536 /*state.head.comm_max*/)) {+ state.head.comment += String.fromCharCode(len);+ }+ } while (len && copy < have);+ if (state.flags & 0x0200) {+ state.check = crc32(state.check, input, copy, next);+ }+ have -= copy;+ next += copy;+ if (len) { break inf_leave; }+ }+ else if (state.head) {+ state.head.comment = null;+ }+ state.mode = HCRC;+ /* falls through */+ case HCRC:+ if (state.flags & 0x0200) {+ //=== NEEDBITS(16); */+ while (bits < 16) {+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ }+ //===//+ if (hold !== (state.check & 0xffff)) {+ strm.msg = 'header crc mismatch';+ state.mode = BAD;+ break;+ }+ //=== INITBITS();+ hold = 0;+ bits = 0;+ //===//+ }+ if (state.head) {+ state.head.hcrc = ((state.flags >> 9) & 1);+ state.head.done = true;+ }+ strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;+ state.mode = TYPE;+ break;+ case DICTID:+ //=== NEEDBITS(32); */+ while (bits < 32) {+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ }+ //===//+ strm.adler = state.check = ZSWAP32(hold);+ //=== INITBITS();+ hold = 0;+ bits = 0;+ //===//+ state.mode = DICT;+ /* falls through */+ case DICT:+ if (state.havedict === 0) {+ //--- RESTORE() ---+ strm.next_out = put;+ strm.avail_out = left;+ strm.next_in = next;+ strm.avail_in = have;+ state.hold = hold;+ state.bits = bits;+ //---+ return Z_NEED_DICT;+ }+ strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;+ state.mode = TYPE;+ /* falls through */+ case TYPE:+ if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }+ /* falls through */+ case TYPEDO:+ if (state.last) {+ //--- BYTEBITS() ---//+ hold >>>= bits & 7;+ bits -= bits & 7;+ //---//+ state.mode = CHECK;+ break;+ }+ //=== NEEDBITS(3); */+ while (bits < 3) {+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ }+ //===//+ state.last = (hold & 0x01)/*BITS(1)*/;+ //--- DROPBITS(1) ---//+ hold >>>= 1;+ bits -= 1;+ //---//- /* sort symbols by length, by symbol order within each length */- for (sym = 0; sym < codes; sym++) {- if (lens[lens_index + sym] !== 0) {- work[offs[lens[lens_index + sym]]++] = sym;- }- }+ switch ((hold & 0x03)/*BITS(2)*/) {+ case 0: /* stored block */+ //Tracev((stderr, "inflate: stored block%s\n",+ // state.last ? " (last)" : ""));+ state.mode = STORED;+ break;+ case 1: /* fixed block */+ fixedtables(state);+ //Tracev((stderr, "inflate: fixed codes block%s\n",+ // state.last ? " (last)" : ""));+ state.mode = LEN_; /* decode codes */+ if (flush === Z_TREES) {+ //--- DROPBITS(2) ---//+ hold >>>= 2;+ bits -= 2;+ //---//+ break inf_leave;+ }+ break;+ case 2: /* dynamic block */+ //Tracev((stderr, "inflate: dynamic codes block%s\n",+ // state.last ? " (last)" : ""));+ state.mode = TABLE;+ break;+ case 3:+ strm.msg = 'invalid block type';+ state.mode = BAD;+ }+ //--- DROPBITS(2) ---//+ hold >>>= 2;+ bits -= 2;+ //---//+ break;+ case STORED:+ //--- BYTEBITS() ---// /* go to byte boundary */+ hold >>>= bits & 7;+ bits -= bits & 7;+ //---//+ //=== NEEDBITS(32); */+ while (bits < 32) {+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ }+ //===//+ if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {+ strm.msg = 'invalid stored block lengths';+ state.mode = BAD;+ break;+ }+ state.length = hold & 0xffff;+ //Tracev((stderr, "inflate: stored length %u\n",+ // state.length));+ //=== INITBITS();+ hold = 0;+ bits = 0;+ //===//+ state.mode = COPY_;+ if (flush === Z_TREES) { break inf_leave; }+ /* falls through */+ case COPY_:+ state.mode = COPY;+ /* falls through */+ case COPY:+ copy = state.length;+ if (copy) {+ if (copy > have) { copy = have; }+ if (copy > left) { copy = left; }+ if (copy === 0) { break inf_leave; }+ //--- zmemcpy(put, next, copy); ---+ utils.arraySet(output, input, next, copy, put);+ //---//+ have -= copy;+ next += copy;+ left -= copy;+ put += copy;+ state.length -= copy;+ break;+ }+ //Tracev((stderr, "inflate: stored end\n"));+ state.mode = TYPE;+ break;+ case TABLE:+ //=== NEEDBITS(14); */+ while (bits < 14) {+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ }+ //===//+ state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;+ //--- DROPBITS(5) ---//+ hold >>>= 5;+ bits -= 5;+ //---//+ state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;+ //--- DROPBITS(5) ---//+ hold >>>= 5;+ bits -= 5;+ //---//+ state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;+ //--- DROPBITS(4) ---//+ hold >>>= 4;+ bits -= 4;+ //---//+//#ifndef PKZIP_BUG_WORKAROUND+ if (state.nlen > 286 || state.ndist > 30) {+ strm.msg = 'too many length or distance symbols';+ state.mode = BAD;+ break;+ }+//#endif+ //Tracev((stderr, "inflate: table sizes ok\n"));+ state.have = 0;+ state.mode = LENLENS;+ /* falls through */+ case LENLENS:+ while (state.have < state.ncode) {+ //=== NEEDBITS(3);+ while (bits < 3) {+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ }+ //===//+ state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);+ //--- DROPBITS(3) ---//+ hold >>>= 3;+ bits -= 3;+ //---//+ }+ while (state.have < 19) {+ state.lens[order[state.have++]] = 0;+ }+ // We have separate tables & no pointers. 2 commented lines below not needed.+ //state.next = state.codes;+ //state.lencode = state.next;+ // Switch to use dynamic table+ state.lencode = state.lendyn;+ state.lenbits = 7;- /*- Create and fill in decoding tables. In this loop, the table being- filled is at next and has curr index bits. The code being used is huff- with length len. That code is converted to an index by dropping drop- bits off of the bottom. For codes where len is less than drop + curr,- those top drop + curr - len bits are incremented through all values to- fill the table with replicated entries.+ opts = {bits: state.lenbits};+ ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);+ state.lenbits = opts.bits;- root is the number of index bits for the root table. When len exceeds- root, sub-tables are created pointed to by the root entry with an index- of the low root bits of huff. This is saved in low to check for when a- new sub-table should be started. drop is zero when the root table is- being filled, and drop is root when sub-tables are being filled.+ if (ret) {+ strm.msg = 'invalid code lengths set';+ state.mode = BAD;+ break;+ }+ //Tracev((stderr, "inflate: code lengths ok\n"));+ state.have = 0;+ state.mode = CODELENS;+ /* falls through */+ case CODELENS:+ while (state.have < state.nlen + state.ndist) {+ for (;;) {+ here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/+ here_bits = here >>> 24;+ here_op = (here >>> 16) & 0xff;+ here_val = here & 0xffff;- When a new sub-table is needed, it is necessary to look ahead in the- code lengths to determine what size sub-table is needed. The length- counts are used for this, and so count[] is decremented as codes are- entered in the tables.+ if ((here_bits) <= bits) { break; }+ //--- PULLBYTE() ---//+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ //---//+ }+ if (here_val < 16) {+ //--- DROPBITS(here.bits) ---//+ hold >>>= here_bits;+ bits -= here_bits;+ //---//+ state.lens[state.have++] = here_val;+ }+ else {+ if (here_val === 16) {+ //=== NEEDBITS(here.bits + 2);+ n = here_bits + 2;+ while (bits < n) {+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ }+ //===//+ //--- DROPBITS(here.bits) ---//+ hold >>>= here_bits;+ bits -= here_bits;+ //---//+ if (state.have === 0) {+ strm.msg = 'invalid bit length repeat';+ state.mode = BAD;+ break;+ }+ len = state.lens[state.have - 1];+ copy = 3 + (hold & 0x03);//BITS(2);+ //--- DROPBITS(2) ---//+ hold >>>= 2;+ bits -= 2;+ //---//+ }+ else if (here_val === 17) {+ //=== NEEDBITS(here.bits + 3);+ n = here_bits + 3;+ while (bits < n) {+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ }+ //===//+ //--- DROPBITS(here.bits) ---//+ hold >>>= here_bits;+ bits -= here_bits;+ //---//+ len = 0;+ copy = 3 + (hold & 0x07);//BITS(3);+ //--- DROPBITS(3) ---//+ hold >>>= 3;+ bits -= 3;+ //---//+ }+ else {+ //=== NEEDBITS(here.bits + 7);+ n = here_bits + 7;+ while (bits < n) {+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ }+ //===//+ //--- DROPBITS(here.bits) ---//+ hold >>>= here_bits;+ bits -= here_bits;+ //---//+ len = 0;+ copy = 11 + (hold & 0x7f);//BITS(7);+ //--- DROPBITS(7) ---//+ hold >>>= 7;+ bits -= 7;+ //---//+ }+ if (state.have + copy > state.nlen + state.ndist) {+ strm.msg = 'invalid bit length repeat';+ state.mode = BAD;+ break;+ }+ while (copy--) {+ state.lens[state.have++] = len;+ }+ }+ }- used keeps track of how many table entries have been allocated from the- provided *table space. It is checked for LENS and DIST tables against- the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in- the initial root table size constants. See the comments in inftrees.h- for more information.+ /* handle error breaks in while */+ if (state.mode === BAD) { break; }- sym increments through all symbols, and the loop terminates when- all codes of length max, i.e. all codes, have been processed. This- routine permits incomplete codes, so another loop after this one fills- in the rest of the decoding tables with invalid code markers.- */+ /* check for end-of-block code (better have one) */+ if (state.lens[256] === 0) {+ strm.msg = 'invalid code -- missing end-of-block';+ state.mode = BAD;+ break;+ }- /* set up for code type */- // poor man optimization - use if-else instead of switch,- // to avoid deopts in old v8- if (type === CODES) {- base = extra = work; /* dummy value--not used */- end = 19;- } else if (type === LENS) {- base = lbase;- base_index -= 257;- extra = lext;- extra_index -= 257;- end = 256;- } else { /* DISTS */- base = dbase;- extra = dext;- end = -1;- }+ /* build code tables -- note: do not change the lenbits or distbits+ values here (9 and 6) without reading the comments in inftrees.h+ concerning the ENOUGH constants, which depend on those values */+ state.lenbits = 9;- /* initialize opts for loop */- huff = 0; /* starting code */- sym = 0; /* starting code symbol */- len = min; /* starting code length */- next = table_index; /* current table to fill in */- curr = root; /* current table index bits */- drop = 0; /* current bits to drop from code for index */- low = -1; /* trigger new sub-table when len > root */- used = 1 << root; /* use root table entries */- mask = used - 1; /* mask for comparing low */+ opts = {bits: state.lenbits};+ ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);+ // We have separate tables & no pointers. 2 commented lines below not needed.+ // state.next_index = opts.table_index;+ state.lenbits = opts.bits;+ // state.lencode = state.next;- /* check available table space */- if ((type === LENS && used > ENOUGH_LENS) ||- (type === DISTS && used > ENOUGH_DISTS)) {- return 1;- }+ if (ret) {+ strm.msg = 'invalid literal/lengths set';+ state.mode = BAD;+ break;+ }- var i=0;- /* process all codes and make table entries */- for (;;) {- i++;- /* create table entry */- here_bits = len - drop;- if (work[sym] < end) {- here_op = 0;- here_val = work[sym];- }- else if (work[sym] > end) {- here_op = extra[extra_index + work[sym]];- here_val = base[base_index + work[sym]];- }- else {- here_op = 32 + 64; /* end of block */- here_val = 0;- }+ state.distbits = 6;+ //state.distcode.copy(state.codes);+ // Switch to use dynamic table+ state.distcode = state.distdyn;+ opts = {bits: state.distbits};+ ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);+ // We have separate tables & no pointers. 2 commented lines below not needed.+ // state.next_index = opts.table_index;+ state.distbits = opts.bits;+ // state.distcode = state.next;- /* replicate for those indices with low len bits equal to huff */- incr = 1 << (len - drop);- fill = 1 << curr;- min = fill; /* save offset to next table */- do {- fill -= incr;- table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;- } while (fill !== 0);+ if (ret) {+ strm.msg = 'invalid distances set';+ state.mode = BAD;+ break;+ }+ //Tracev((stderr, 'inflate: codes ok\n'));+ state.mode = LEN_;+ if (flush === Z_TREES) { break inf_leave; }+ /* falls through */+ case LEN_:+ state.mode = LEN;+ /* falls through */+ case LEN:+ if (have >= 6 && left >= 258) {+ //--- RESTORE() ---+ strm.next_out = put;+ strm.avail_out = left;+ strm.next_in = next;+ strm.avail_in = have;+ state.hold = hold;+ state.bits = bits;+ //---+ inflate_fast(strm, _out);+ //--- LOAD() ---+ put = strm.next_out;+ output = strm.output;+ left = strm.avail_out;+ next = strm.next_in;+ input = strm.input;+ have = strm.avail_in;+ hold = state.hold;+ bits = state.bits;+ //---- /* backwards increment the len-bit code huff */- incr = 1 << (len - 1);- while (huff & incr) {- incr >>= 1;- }- if (incr !== 0) {- huff &= incr - 1;- huff += incr;- } else {- huff = 0;- }+ if (state.mode === TYPE) {+ state.back = -1;+ }+ break;+ }+ state.back = 0;+ for (;;) {+ here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/+ here_bits = here >>> 24;+ here_op = (here >>> 16) & 0xff;+ here_val = here & 0xffff;- /* go to next symbol, update count, len */- sym++;- if (--count[len] === 0) {- if (len === max) { break; }- len = lens[lens_index + work[sym]];- }+ if (here_bits <= bits) { break; }+ //--- PULLBYTE() ---//+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ //---//+ }+ if (here_op && (here_op & 0xf0) === 0) {+ last_bits = here_bits;+ last_op = here_op;+ last_val = here_val;+ for (;;) {+ here = state.lencode[last_val ++ ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];+ here_bits = here >>> 24;+ here_op = (here >>> 16) & 0xff;+ here_val = here & 0xffff;- /* create new sub-table if needed */- if (len > root && (huff & mask) !== low) {- /* if first time, transition to sub-tables */- if (drop === 0) {- drop = root;+ if ((last_bits + here_bits) <= bits) { break; }+ //--- PULLBYTE() ---//+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ //---//+ }+ //--- DROPBITS(last.bits) ---//+ hold >>>= last_bits;+ bits -= last_bits;+ //---//+ state.back += last_bits;+ }+ //--- DROPBITS(here.bits) ---//+ hold >>>= here_bits;+ bits -= here_bits;+ //---//+ state.back += here_bits;+ state.length = here_val;+ if (here_op === 0) {+ //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?+ // "inflate: literal '%c'\n" :+ // "inflate: literal 0x%02x\n", here.val));+ state.mode = LIT;+ break;+ }+ if (here_op & 32) {+ //Tracevv((stderr, "inflate: end of block\n"));+ state.back = -1;+ state.mode = TYPE;+ break;}+ if (here_op & 64) {+ strm.msg = 'invalid literal/length code';+ state.mode = BAD;+ break;+ }+ state.extra = here_op & 15;+ state.mode = LENEXT;+ /* falls through */+ case LENEXT:+ if (state.extra) {+ //=== NEEDBITS(state.extra);+ n = state.extra;+ while (bits < n) {+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ }+ //===//+ state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;+ //--- DROPBITS(state.extra) ---//+ hold >>>= state.extra;+ bits -= state.extra;+ //---//+ state.back += state.extra;+ }+ //Tracevv((stderr, "inflate: length %u\n", state.length));+ state.was = state.length;+ state.mode = DIST;+ /* falls through */+ case DIST:+ for (;;) {+ here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/+ here_bits = here >>> 24;+ here_op = (here >>> 16) & 0xff;+ here_val = here & 0xffff;- /* increment past last table */- next += min; /* here min is 1 << curr */-- /* determine length of next table */- curr = len - drop;- left = 1 << curr;- while (curr + drop < max) {- left -= count[curr + drop];- if (left <= 0) { break; }- curr++;- left <<= 1;+ if ((here_bits) <= bits) { break; }+ //--- PULLBYTE() ---//+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ //---//}+ if ((here_op & 0xf0) === 0) {+ last_bits = here_bits;+ last_op = here_op;+ last_val = here_val;+ for (;;) {+ here = state.distcode[last_val ++ ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];+ here_bits = here >>> 24;+ here_op = (here >>> 16) & 0xff;+ here_val = here & 0xffff;- /* check for enough space */- used += 1 << curr;- if ((type === LENS && used > ENOUGH_LENS) ||- (type === DISTS && used > ENOUGH_DISTS)) {- return 1;+ if ((last_bits + here_bits) <= bits) { break; }+ //--- PULLBYTE() ---//+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ //---//+ }+ //--- DROPBITS(last.bits) ---//+ hold >>>= last_bits;+ bits -= last_bits;+ //---//+ state.back += last_bits;+ }+ //--- DROPBITS(here.bits) ---//+ hold >>>= here_bits;+ bits -= here_bits;+ //---//+ state.back += here_bits;+ if (here_op & 64) {+ strm.msg = 'invalid distance code';+ state.mode = BAD;+ break;+ }+ state.offset = here_val;+ state.extra = (here_op) & 15;+ state.mode = DISTEXT;+ /* falls through */+ case DISTEXT:+ if (state.extra) {+ //=== NEEDBITS(state.extra);+ n = state.extra;+ while (bits < n) {+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ }+ //===//+ state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;+ //--- DROPBITS(state.extra) ---//+ hold >>>= state.extra;+ bits -= state.extra;+ //---//+ state.back += state.extra;+ }+//#ifdef INFLATE_STRICT+ if (state.offset > state.dmax) {+ strm.msg = 'invalid distance too far back';+ state.mode = BAD;+ break;+ }+//#endif+ //Tracevv((stderr, "inflate: distance %u\n", state.offset));+ state.mode = MATCH;+ /* falls through */+ case MATCH:+ if (left === 0) { break inf_leave; }+ copy = _out - left;+ if (state.offset > copy) { /* copy from window */+ copy = state.offset - copy;+ if (copy > state.whave) {+ if (state.sane) {+ strm.msg = 'invalid distance too far back';+ state.mode = BAD;+ break;+ }+// (!) This block is disabled in zlib defailts,+// don't enable it for binary compatibility+//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR+// Trace((stderr, "inflate.c too far\n"));+// copy -= state.whave;+// if (copy > state.length) { copy = state.length; }+// if (copy > left) { copy = left; }+// left -= copy;+// state.length -= copy;+// do {+// output[put++] = 0;+// } while (--copy);+// if (state.length === 0) { state.mode = LEN; }+// break;+//#endif+ }+ if (copy > state.wnext) {+ copy -= state.wnext;+ from = state.wsize - copy;+ }+ else {+ from = state.wnext - copy;+ }+ if (copy > state.length) { copy = state.length; }+ from_source = state.window;+ }+ else { /* copy from output */+ from_source = output;+ from = put - state.offset;+ copy = state.length;}+ if (copy > left) { copy = left; }+ left -= copy;+ state.length -= copy;+ do {+ output[put++] = from_source[from++];+ } while (--copy);+ if (state.length === 0) { state.mode = LEN; }+ break;+ case LIT:+ if (left === 0) { break inf_leave; }+ output[put++] = state.length;+ left--;+ state.mode = LEN;+ break;+ case CHECK:+ if (state.wrap) {+ //=== NEEDBITS(32);+ while (bits < 32) {+ if (have === 0) { break inf_leave; }+ have--;+ // Use '|' insdead of '+' to make sure that result is signed+ hold |= input[next++] << bits;+ bits += 8;+ }+ //===//+ _out -= left;+ strm.total_out += _out;+ state.total += _out;+ if (_out) {+ strm.adler = state.check =+ /*UPDATE(state.check, put - _out, _out);*/+ (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));- /* point entry in root table to sub-table */- low = huff & mask;- /*table.op[low] = curr;- table.bits[low] = root;- table.val[low] = next - opts.table_index;*/- table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;+ }+ _out = left;+ // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too+ if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {+ strm.msg = 'incorrect data check';+ state.mode = BAD;+ break;+ }+ //=== INITBITS();+ hold = 0;+ bits = 0;+ //===//+ //Tracev((stderr, "inflate: check matches trailer\n"));+ }+ state.mode = LENGTH;+ /* falls through */+ case LENGTH:+ if (state.wrap && state.flags) {+ //=== NEEDBITS(32);+ while (bits < 32) {+ if (have === 0) { break inf_leave; }+ have--;+ hold += input[next++] << bits;+ bits += 8;+ }+ //===//+ if (hold !== (state.total & 0xffffffff)) {+ strm.msg = 'incorrect length check';+ state.mode = BAD;+ break;+ }+ //=== INITBITS();+ hold = 0;+ bits = 0;+ //===//+ //Tracev((stderr, "inflate: length matches trailer\n"));+ }+ state.mode = DONE;+ /* falls through */+ case DONE:+ ret = Z_STREAM_END;+ break inf_leave;+ case BAD:+ ret = Z_DATA_ERROR;+ break inf_leave;+ case MEM:+ return Z_MEM_ERROR;+ case SYNC:+ /* falls through */+ default:+ return Z_STREAM_ERROR;}}- /* fill in remaining table entry if code is incomplete (guaranteed to have- at most one remaining entry, since if the code is incomplete, the- maximum code length that was allowed to get this far is one bit) */- if (huff !== 0) {- //table.op[next + huff] = 64; /* invalid code marker */- //table.bits[next + huff] = len - drop;- //table.val[next + huff] = 0;- table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;- }-- /* set return parameters */- //opts.table_index += used;- opts.bits = root;- return 0;-};--},{"../utils/common":69}],79:[function(require,module,exports){-'use strict';--module.exports = {- '2': 'need dictionary', /* Z_NEED_DICT 2 */- '1': 'stream end', /* Z_STREAM_END 1 */- '0': '', /* Z_OK 0 */- '-1': 'file error', /* Z_ERRNO (-1) */- '-2': 'stream error', /* Z_STREAM_ERROR (-2) */- '-3': 'data error', /* Z_DATA_ERROR (-3) */- '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */- '-5': 'buffer error', /* Z_BUF_ERROR (-5) */- '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */-};-},{}],80:[function(require,module,exports){-'use strict';---var utils = require('../utils/common');--/* Public constants ==========================================================*/-/* ===========================================================================*/---//var Z_FILTERED = 1;-//var Z_HUFFMAN_ONLY = 2;-//var Z_RLE = 3;-var Z_FIXED = 4;-//var Z_DEFAULT_STRATEGY = 0;--/* Possible values of the data_type field (though see inflate()) */-var Z_BINARY = 0;-var Z_TEXT = 1;-//var Z_ASCII = 1; // = Z_TEXT-var Z_UNKNOWN = 2;--/*============================================================================*/---function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }--// From zutil.h--var STORED_BLOCK = 0;-var STATIC_TREES = 1;-var DYN_TREES = 2;-/* The three kinds of block type */--var MIN_MATCH = 3;-var MAX_MATCH = 258;-/* The minimum and maximum match lengths */--// From deflate.h-/* ===========================================================================- * Internal compression state.- */--var LENGTH_CODES = 29;-/* number of length codes, not counting the special END_BLOCK code */--var LITERALS = 256;-/* number of literal bytes 0..255 */--var L_CODES = LITERALS + 1 + LENGTH_CODES;-/* number of Literal or Length codes, including the END_BLOCK code */--var D_CODES = 30;-/* number of distance codes */--var BL_CODES = 19;-/* number of codes used to transfer the bit lengths */--var HEAP_SIZE = 2*L_CODES + 1;-/* maximum heap size */--var MAX_BITS = 15;-/* All codes must not exceed MAX_BITS bits */--var Buf_size = 16;-/* size of bit buffer in bi_buf */---/* ===========================================================================- * Constants- */--var MAX_BL_BITS = 7;-/* Bit length codes must not exceed MAX_BL_BITS bits */--var END_BLOCK = 256;-/* end of block literal code */--var REP_3_6 = 16;-/* repeat previous bit length 3-6 times (2 bits of repeat count) */--var REPZ_3_10 = 17;-/* repeat a zero length 3-10 times (3 bits of repeat count) */--var REPZ_11_138 = 18;-/* repeat a zero length 11-138 times (7 bits of repeat count) */+ // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"-var extra_lbits = /* extra bits for each length code */- [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];+ /*+ Return from inflate(), updating the total counts and the check value.+ If there was no progress during the inflate() call, return a buffer+ error. Call updatewindow() to create and/or update the window state.+ Note: a memory error from inflate() is non-recoverable.+ */-var extra_dbits = /* extra bits for each distance code */- [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];+ //--- RESTORE() ---+ strm.next_out = put;+ strm.avail_out = left;+ strm.next_in = next;+ strm.avail_in = have;+ state.hold = hold;+ state.bits = bits;+ //----var extra_blbits = /* extra bits for each bit length code */- [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];+ if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&+ (state.mode < CHECK || flush !== Z_FINISH))) {+ if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {+ state.mode = MEM;+ return Z_MEM_ERROR;+ }+ }+ _in -= strm.avail_in;+ _out -= strm.avail_out;+ strm.total_in += _in;+ strm.total_out += _out;+ state.total += _out;+ if (state.wrap && _out) {+ strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/+ (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));+ }+ strm.data_type = state.bits + (state.last ? 64 : 0) ++ (state.mode === TYPE ? 128 : 0) ++ (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);+ if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {+ ret = Z_BUF_ERROR;+ }+ return ret;+}-var bl_order =- [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];-/* The lengths of the bit length codes are sent in order of decreasing- * probability, to avoid transmitting the lengths for unused bit length codes.- */+function inflateEnd(strm) {-/* ===========================================================================- * Local data. These are initialized only once.- */+ if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {+ return Z_STREAM_ERROR;+ }-// We pre-fill arrays with 0 to avoid uninitialized gaps+ var state = strm.state;+ if (state.window) {+ state.window = null;+ }+ strm.state = null;+ return Z_OK;+}-var DIST_CODE_LEN = 512; /* see definition of array dist_code below */+function inflateGetHeader(strm, head) {+ var state;-// !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1-var static_ltree = new Array((L_CODES+2) * 2);-zero(static_ltree);-/* The static literal tree. Since the bit lengths are imposed, there is no- * need for the L_CODES extra codes used during heap construction. However- * The codes 286 and 287 are needed to build a canonical tree (see _tr_init- * below).- */+ /* check state */+ if (!strm || !strm.state) { return Z_STREAM_ERROR; }+ state = strm.state;+ if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }-var static_dtree = new Array(D_CODES * 2);-zero(static_dtree);-/* The static distance tree. (Actually a trivial tree since all codes use- * 5 bits.)- */+ /* save header structure */+ state.head = head;+ head.done = false;+ return Z_OK;+}-var _dist_code = new Array(DIST_CODE_LEN);-zero(_dist_code);-/* Distance codes. The first 256 values correspond to the distances- * 3 .. 258, the last 256 values correspond to the top 8 bits of- * the 15 bit distances.- */-var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);-zero(_length_code);-/* length code for each normalized match length (0 == MIN_MATCH) */+exports.inflateReset = inflateReset;+exports.inflateReset2 = inflateReset2;+exports.inflateResetKeep = inflateResetKeep;+exports.inflateInit = inflateInit;+exports.inflateInit2 = inflateInit2;+exports.inflate = inflate;+exports.inflateEnd = inflateEnd;+exports.inflateGetHeader = inflateGetHeader;+exports.inflateInfo = 'pako inflate (from Nodeca project)';-var base_length = new Array(LENGTH_CODES);-zero(base_length);-/* First normalized length for each code (0 = MIN_MATCH) */+/* Not implemented+exports.inflateCopy = inflateCopy;+exports.inflateGetDictionary = inflateGetDictionary;+exports.inflateMark = inflateMark;+exports.inflatePrime = inflatePrime;+exports.inflateSetDictionary = inflateSetDictionary;+exports.inflateSync = inflateSync;+exports.inflateSyncPoint = inflateSyncPoint;+exports.inflateUndermine = inflateUndermine;+*/+},{"../utils/common":70,"./adler32":72,"./crc32":74,"./inffast":77,"./inftrees":79}],79:[function(require,module,exports){+'use strict';-var base_dist = new Array(D_CODES);-zero(base_dist);-/* First normalized distance for each code (0 = distance of 1) */+var utils = require('../utils/common');-var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {+var MAXBITS = 15;+var ENOUGH_LENS = 852;+var ENOUGH_DISTS = 592;+//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);- this.static_tree = static_tree; /* static tree or NULL */- this.extra_bits = extra_bits; /* extra bits for each code or NULL */- this.extra_base = extra_base; /* base index for extra_bits */- this.elems = elems; /* max number of elements in the tree */- this.max_length = max_length; /* max bit length for the codes */+var CODES = 0;+var LENS = 1;+var DISTS = 2;- // show if `static_tree` has data or dummy - needed for monomorphic objects- this.has_stree = static_tree && static_tree.length;-};+var lbase = [ /* Length codes 257..285 base */+ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,+ 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0+];+var lext = [ /* Length codes 257..285 extra */+ 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,+ 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78+];-var static_l_desc;-var static_d_desc;-var static_bl_desc;+var dbase = [ /* Distance codes 0..29 base */+ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,+ 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,+ 8193, 12289, 16385, 24577, 0, 0+];+var dext = [ /* Distance codes 0..29 extra */+ 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,+ 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,+ 28, 28, 29, 29, 64, 64+];-var TreeDesc = function(dyn_tree, stat_desc) {- this.dyn_tree = dyn_tree; /* the dynamic tree */- this.max_code = 0; /* largest code with non zero frequency */- this.stat_desc = stat_desc; /* the corresponding static tree */-};+module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)+{+ var bits = opts.bits;+ //here = opts.here; /* table entry for duplication */+ var len = 0; /* a code's length in bits */+ var sym = 0; /* index of code symbols */+ var min = 0, max = 0; /* minimum and maximum code lengths */+ var root = 0; /* number of index bits for root table */+ var curr = 0; /* number of index bits for current table */+ var drop = 0; /* code bits to drop for sub-table */+ var left = 0; /* number of prefix codes available */+ var used = 0; /* code entries in table used */+ var huff = 0; /* Huffman code */+ var incr; /* for incrementing code, index */+ var fill; /* index for replicating entries */+ var low; /* low bits for current root entry */+ var mask; /* mask for low root bits */+ var next; /* next available space in table */+ var base = null; /* base value table to use */+ var base_index = 0;+// var shoextra; /* extra bits table to use */+ var end; /* use base and extra for symbol > end */+ var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */+ var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */+ var extra = null;+ var extra_index = 0;+ var here_bits, here_op, here_val;-function d_code(dist) {- return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];-}+ /*+ Process a set of code lengths to create a canonical Huffman code. The+ code lengths are lens[0..codes-1]. Each length corresponds to the+ symbols 0..codes-1. The Huffman code is generated by first sorting the+ symbols by length from short to long, and retaining the symbol order+ for codes with equal lengths. Then the code starts with all zero bits+ for the first code of the shortest length, and the codes are integer+ increments for the same length, and zeros are appended as the length+ increases. For the deflate format, these bits are stored backwards+ from their more natural integer increment ordering, and so when the+ decoding tables are built in the large loop below, the integer codes+ are incremented backwards.+ This routine assumes, but does not check, that all of the entries in+ lens[] are in the range 0..MAXBITS. The caller must assure this.+ 1..MAXBITS is interpreted as that code length. zero means that that+ symbol does not occur in this code.-/* ===========================================================================- * Output a short LSB first on the stream.- * IN assertion: there is enough room in pendingBuf.- */-function put_short (s, w) {-// put_byte(s, (uch)((w) & 0xff));-// put_byte(s, (uch)((ush)(w) >> 8));- s.pending_buf[s.pending++] = (w) & 0xff;- s.pending_buf[s.pending++] = (w >>> 8) & 0xff;-}+ The codes are sorted by computing a count of codes for each length,+ creating from that a table of starting indices for each length in the+ sorted table, and then entering the symbols in order in the sorted+ table. The sorted table is work[], with that space being provided by+ the caller.+ The length counts are used for other purposes as well, i.e. finding+ the minimum and maximum length codes, determining if there are any+ codes at all, checking for a valid set of lengths, and looking ahead+ at length counts to determine sub-table sizes when building the+ decoding tables.+ */-/* ===========================================================================- * Send a value on a given number of bits.- * IN assertion: length <= 16 and value fits in length bits.- */-function send_bits(s, value, length) {- if (s.bi_valid > (Buf_size - length)) {- s.bi_buf |= (value << s.bi_valid) & 0xffff;- put_short(s, s.bi_buf);- s.bi_buf = value >> (Buf_size - s.bi_valid);- s.bi_valid += length - Buf_size;- } else {- s.bi_buf |= (value << s.bi_valid) & 0xffff;- s.bi_valid += length;+ /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */+ for (len = 0; len <= MAXBITS; len++) {+ count[len] = 0;+ }+ for (sym = 0; sym < codes; sym++) {+ count[lens[lens_index + sym]]++;}-}+ /* bound code lengths, force root to be within code lengths */+ root = bits;+ for (max = MAXBITS; max >= 1; max--) {+ if (count[max] !== 0) { break; }+ }+ if (root > max) {+ root = max;+ }+ if (max === 0) { /* no symbols to code at all */+ //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */+ //table.bits[opts.table_index] = 1; //here.bits = (var char)1;+ //table.val[opts.table_index++] = 0; //here.val = (var short)0;+ table[table_index++] = (1 << 24) | (64 << 16) | 0;-function send_code(s, c, tree) {- send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);-}+ //table.op[opts.table_index] = 64;+ //table.bits[opts.table_index] = 1;+ //table.val[opts.table_index++] = 0;+ table[table_index++] = (1 << 24) | (64 << 16) | 0;-/* ===========================================================================- * Reverse the first len bits of a code, using straightforward code (a faster- * method would use a table)- * IN assertion: 1 <= len <= 15- */-function bi_reverse(code, len) {- var res = 0;- do {- res |= code & 1;- code >>>= 1;- res <<= 1;- } while (--len > 0);- return res >>> 1;-}+ opts.bits = 1;+ return 0; /* no symbols, but wait for decoding to report error */+ }+ for (min = 1; min < max; min++) {+ if (count[min] !== 0) { break; }+ }+ if (root < min) {+ root = min;+ }+ /* check for an over-subscribed or incomplete set of lengths */+ left = 1;+ for (len = 1; len <= MAXBITS; len++) {+ left <<= 1;+ left -= count[len];+ if (left < 0) {+ return -1;+ } /* over-subscribed */+ }+ if (left > 0 && (type === CODES || max !== 1)) {+ return -1; /* incomplete set */+ }-/* ===========================================================================- * Flush the bit buffer, keeping at most 7 bits in it.- */-function bi_flush(s) {- if (s.bi_valid === 16) {- put_short(s, s.bi_buf);- s.bi_buf = 0;- s.bi_valid = 0;+ /* generate offsets into symbol table for each length for sorting */+ offs[1] = 0;+ for (len = 1; len < MAXBITS; len++) {+ offs[len + 1] = offs[len] + count[len];+ }- } else if (s.bi_valid >= 8) {- s.pending_buf[s.pending++] = s.bi_buf & 0xff;- s.bi_buf >>= 8;- s.bi_valid -= 8;+ /* sort symbols by length, by symbol order within each length */+ for (sym = 0; sym < codes; sym++) {+ if (lens[lens_index + sym] !== 0) {+ work[offs[lens[lens_index + sym]]++] = sym;+ }}-}+ /*+ Create and fill in decoding tables. In this loop, the table being+ filled is at next and has curr index bits. The code being used is huff+ with length len. That code is converted to an index by dropping drop+ bits off of the bottom. For codes where len is less than drop + curr,+ those top drop + curr - len bits are incremented through all values to+ fill the table with replicated entries.-/* ===========================================================================- * Compute the optimal bit lengths for a tree and update the total bit length- * for the current block.- * IN assertion: the fields freq and dad are set, heap[heap_max] and- * above are the tree nodes sorted by increasing frequency.- * OUT assertions: the field len is set to the optimal bit length, the- * array bl_count contains the frequencies for each bit length.- * The length opt_len is updated; static_len is also updated if stree is- * not null.- */-function gen_bitlen(s, desc)-// deflate_state *s;-// tree_desc *desc; /* the tree descriptor */-{- var tree = desc.dyn_tree;- var max_code = desc.max_code;- var stree = desc.stat_desc.static_tree;- var has_stree = desc.stat_desc.has_stree;- var extra = desc.stat_desc.extra_bits;- var base = desc.stat_desc.extra_base;- var max_length = desc.stat_desc.max_length;- var h; /* heap index */- var n, m; /* iterate over the tree elements */- var bits; /* bit length */- var xbits; /* extra bits */- var f; /* frequency */- var overflow = 0; /* number of elements with bit length too large */+ root is the number of index bits for the root table. When len exceeds+ root, sub-tables are created pointed to by the root entry with an index+ of the low root bits of huff. This is saved in low to check for when a+ new sub-table should be started. drop is zero when the root table is+ being filled, and drop is root when sub-tables are being filled.- for (bits = 0; bits <= MAX_BITS; bits++) {- s.bl_count[bits] = 0;+ When a new sub-table is needed, it is necessary to look ahead in the+ code lengths to determine what size sub-table is needed. The length+ counts are used for this, and so count[] is decremented as codes are+ entered in the tables.++ used keeps track of how many table entries have been allocated from the+ provided *table space. It is checked for LENS and DIST tables against+ the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in+ the initial root table size constants. See the comments in inftrees.h+ for more information.++ sym increments through all symbols, and the loop terminates when+ all codes of length max, i.e. all codes, have been processed. This+ routine permits incomplete codes, so another loop after this one fills+ in the rest of the decoding tables with invalid code markers.+ */++ /* set up for code type */+ // poor man optimization - use if-else instead of switch,+ // to avoid deopts in old v8+ if (type === CODES) {+ base = extra = work; /* dummy value--not used */+ end = 19;+ } else if (type === LENS) {+ base = lbase;+ base_index -= 257;+ extra = lext;+ extra_index -= 257;+ end = 256;+ } else { /* DISTS */+ base = dbase;+ extra = dext;+ end = -1;}- /* In a first pass, compute the optimal bit lengths (which may- * overflow in the case of the bit length tree).- */- tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */+ /* initialize opts for loop */+ huff = 0; /* starting code */+ sym = 0; /* starting code symbol */+ len = min; /* starting code length */+ next = table_index; /* current table to fill in */+ curr = root; /* current table index bits */+ drop = 0; /* current bits to drop from code for index */+ low = -1; /* trigger new sub-table when len > root */+ used = 1 << root; /* use root table entries */+ mask = used - 1; /* mask for comparing low */- for (h = s.heap_max+1; h < HEAP_SIZE; h++) {- n = s.heap[h];- bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;- if (bits > max_length) {- bits = max_length;- overflow++;+ /* check available table space */+ if ((type === LENS && used > ENOUGH_LENS) ||+ (type === DISTS && used > ENOUGH_DISTS)) {+ return 1;+ }++ var i=0;+ /* process all codes and make table entries */+ for (;;) {+ i++;+ /* create table entry */+ here_bits = len - drop;+ if (work[sym] < end) {+ here_op = 0;+ here_val = work[sym];+ }+ else if (work[sym] > end) {+ here_op = extra[extra_index + work[sym]];+ here_val = base[base_index + work[sym]];+ }+ else {+ here_op = 32 + 64; /* end of block */+ here_val = 0;}- tree[n*2 + 1]/*.Len*/ = bits;- /* We overwrite tree[n].Dad which is no longer needed */- if (n > max_code) { continue; } /* not a leaf node */+ /* replicate for those indices with low len bits equal to huff */+ incr = 1 << (len - drop);+ fill = 1 << curr;+ min = fill; /* save offset to next table */+ do {+ fill -= incr;+ table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;+ } while (fill !== 0);- s.bl_count[bits]++;- xbits = 0;- if (n >= base) {- xbits = extra[n-base];+ /* backwards increment the len-bit code huff */+ incr = 1 << (len - 1);+ while (huff & incr) {+ incr >>= 1;}- f = tree[n * 2]/*.Freq*/;- s.opt_len += f * (bits + xbits);- if (has_stree) {- s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);+ if (incr !== 0) {+ huff &= incr - 1;+ huff += incr;+ } else {+ huff = 0;}- }- if (overflow === 0) { return; }- // Trace((stderr,"\nbit length overflow\n"));- /* This happens for example on obj2 and pic of the Calgary corpus */+ /* go to next symbol, update count, len */+ sym++;+ if (--count[len] === 0) {+ if (len === max) { break; }+ len = lens[lens_index + work[sym]];+ }- /* Find the first bit length which could increase: */- do {- bits = max_length-1;- while (s.bl_count[bits] === 0) { bits--; }- s.bl_count[bits]--; /* move one leaf down the tree */- s.bl_count[bits+1] += 2; /* move one overflow item as its brother */- s.bl_count[max_length]--;- /* The brother of the overflow item also moves one step up,- * but this does not affect bl_count[max_length]- */- overflow -= 2;- } while (overflow > 0);+ /* create new sub-table if needed */+ if (len > root && (huff & mask) !== low) {+ /* if first time, transition to sub-tables */+ if (drop === 0) {+ drop = root;+ }- /* Now recompute all bit lengths, scanning in increasing frequency.- * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all- * lengths instead of fixing only the wrong ones. This idea is taken- * from 'ar' written by Haruhiko Okumura.)- */- for (bits = max_length; bits !== 0; bits--) {- n = s.bl_count[bits];- while (n !== 0) {- m = s.heap[--h];- if (m > max_code) { continue; }- if (tree[m*2 + 1]/*.Len*/ !== bits) {- // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));- s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;- tree[m*2 + 1]/*.Len*/ = bits;+ /* increment past last table */+ next += min; /* here min is 1 << curr */++ /* determine length of next table */+ curr = len - drop;+ left = 1 << curr;+ while (curr + drop < max) {+ left -= count[curr + drop];+ if (left <= 0) { break; }+ curr++;+ left <<= 1;}- n--;- }- }-}+ /* check for enough space */+ used += 1 << curr;+ if ((type === LENS && used > ENOUGH_LENS) ||+ (type === DISTS && used > ENOUGH_DISTS)) {+ return 1;+ }-/* ===========================================================================- * Generate the codes for a given tree and bit counts (which need not be- * optimal).- * IN assertion: the array bl_count contains the bit length statistics for- * the given tree and the field len is set for all tree elements.- * OUT assertion: the field code is set for all tree elements of non- * zero code length.- */-function gen_codes(tree, max_code, bl_count)-// ct_data *tree; /* the tree to decorate */-// int max_code; /* largest code with non zero frequency */-// ushf *bl_count; /* number of codes at each bit length */-{- var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */- var code = 0; /* running code value */- var bits; /* bit index */- var n; /* code index */+ /* point entry in root table to sub-table */+ low = huff & mask;+ /*table.op[low] = curr;+ table.bits[low] = root;+ table.val[low] = next - opts.table_index;*/+ table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;+ }+ }- /* The distribution counts are first used to generate the code values- * without bit reversal.- */- for (bits = 1; bits <= MAX_BITS; bits++) {- next_code[bits] = code = (code + bl_count[bits-1]) << 1;+ /* fill in remaining table entry if code is incomplete (guaranteed to have+ at most one remaining entry, since if the code is incomplete, the+ maximum code length that was allowed to get this far is one bit) */+ if (huff !== 0) {+ //table.op[next + huff] = 64; /* invalid code marker */+ //table.bits[next + huff] = len - drop;+ //table.val[next + huff] = 0;+ table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;}- /* Check that the bit counts in bl_count are consistent. The last code- * must be all ones.- */- //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,- // "inconsistent bit counts");- //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));- for (n = 0; n <= max_code; n++) {- var len = tree[n*2 + 1]/*.Len*/;- if (len === 0) { continue; }- /* Now reverse the bits */- tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);+ /* set return parameters */+ //opts.table_index += used;+ opts.bits = root;+ return 0;+};- //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",- // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));- }-}+},{"../utils/common":70}],80:[function(require,module,exports){+'use strict';+module.exports = {+ '2': 'need dictionary', /* Z_NEED_DICT 2 */+ '1': 'stream end', /* Z_STREAM_END 1 */+ '0': '', /* Z_OK 0 */+ '-1': 'file error', /* Z_ERRNO (-1) */+ '-2': 'stream error', /* Z_STREAM_ERROR (-2) */+ '-3': 'data error', /* Z_DATA_ERROR (-3) */+ '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */+ '-5': 'buffer error', /* Z_BUF_ERROR (-5) */+ '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */+};+},{}],81:[function(require,module,exports){+'use strict';-/* ===========================================================================- * Initialize the various 'constant' tables.- */-function tr_static_init() {- var n; /* iterates over tree elements */- var bits; /* bit counter */- var length; /* length value */- var code; /* code value */- var dist; /* distance index */- var bl_count = new Array(MAX_BITS+1);- /* number of codes at each bit length for an optimal tree */- // do check in _tr_init()- //if (static_init_done) return;+var utils = require('../utils/common');- /* For some embedded targets, global variables are not initialized: */-/*#ifdef NO_INIT_GLOBAL_POINTERS- static_l_desc.static_tree = static_ltree;- static_l_desc.extra_bits = extra_lbits;- static_d_desc.static_tree = static_dtree;- static_d_desc.extra_bits = extra_dbits;- static_bl_desc.extra_bits = extra_blbits;-#endif*/+/* Public constants ==========================================================*/+/* ===========================================================================*/- /* Initialize the mapping length (0..255) -> length code (0..28) */- length = 0;- for (code = 0; code < LENGTH_CODES-1; code++) {- base_length[code] = length;- for (n = 0; n < (1<<extra_lbits[code]); n++) {- _length_code[length++] = code;- }- }- //Assert (length == 256, "tr_static_init: length != 256");- /* Note that the length 255 (match length 258) can be represented- * in two different ways: code 284 + 5 bits or code 285, so we- * overwrite length_code[255] to use the best encoding:- */- _length_code[length-1] = code;- /* Initialize the mapping dist (0..32K) -> dist code (0..29) */- dist = 0;- for (code = 0 ; code < 16; code++) {- base_dist[code] = dist;- for (n = 0; n < (1<<extra_dbits[code]); n++) {- _dist_code[dist++] = code;- }- }- //Assert (dist == 256, "tr_static_init: dist != 256");- dist >>= 7; /* from now on, all distances are divided by 128 */- for ( ; code < D_CODES; code++) {- base_dist[code] = dist << 7;- for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {- _dist_code[256 + dist++] = code;- }- }- //Assert (dist == 256, "tr_static_init: 256+dist != 512");+//var Z_FILTERED = 1;+//var Z_HUFFMAN_ONLY = 2;+//var Z_RLE = 3;+var Z_FIXED = 4;+//var Z_DEFAULT_STRATEGY = 0;++/* Possible values of the data_type field (though see inflate()) */+var Z_BINARY = 0;+var Z_TEXT = 1;+//var Z_ASCII = 1; // = Z_TEXT+var Z_UNKNOWN = 2;- /* Construct the codes of the static literal tree */- for (bits = 0; bits <= MAX_BITS; bits++) {- bl_count[bits] = 0;- }+/*============================================================================*/- n = 0;- while (n <= 143) {- static_ltree[n*2 + 1]/*.Len*/ = 8;- n++;- bl_count[8]++;- }- while (n <= 255) {- static_ltree[n*2 + 1]/*.Len*/ = 9;- n++;- bl_count[9]++;- }- while (n <= 279) {- static_ltree[n*2 + 1]/*.Len*/ = 7;- n++;- bl_count[7]++;- }- while (n <= 287) {- static_ltree[n*2 + 1]/*.Len*/ = 8;- n++;- bl_count[8]++;- }- /* Codes 286 and 287 do not exist, but we must include them in the- * tree construction to get a canonical Huffman tree (longest code- * all ones)- */- gen_codes(static_ltree, L_CODES+1, bl_count);- /* The static distance tree is trivial: */- for (n = 0; n < D_CODES; n++) {- static_dtree[n*2 + 1]/*.Len*/ = 5;- static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);- }+function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }- // Now data ready and we can init static trees- static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);- static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);- static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);+// From zutil.h- //static_init_done = true;-}+var STORED_BLOCK = 0;+var STATIC_TREES = 1;+var DYN_TREES = 2;+/* The three kinds of block type */+var MIN_MATCH = 3;+var MAX_MATCH = 258;+/* The minimum and maximum match lengths */+// From deflate.h/* ===========================================================================- * Initialize a new block.+ * Internal compression state.*/-function init_block(s) {- var n; /* iterates over tree elements */- /* Initialize the trees. */- for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }- for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }- for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }+var LENGTH_CODES = 29;+/* number of length codes, not counting the special END_BLOCK code */- s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;- s.opt_len = s.static_len = 0;- s.last_lit = s.matches = 0;-}+var LITERALS = 256;+/* number of literal bytes 0..255 */+var L_CODES = LITERALS + 1 + LENGTH_CODES;+/* number of Literal or Length codes, including the END_BLOCK code */-/* ===========================================================================- * Flush the bit buffer and align the output on a byte boundary- */-function bi_windup(s)-{- if (s.bi_valid > 8) {- put_short(s, s.bi_buf);- } else if (s.bi_valid > 0) {- //put_byte(s, (Byte)s->bi_buf);- s.pending_buf[s.pending++] = s.bi_buf;- }- s.bi_buf = 0;- s.bi_valid = 0;-}+var D_CODES = 30;+/* number of distance codes */-/* ===========================================================================- * Copy a stored block, storing first the length and its- * one's complement if requested.- */-function copy_block(s, buf, len, header)-//DeflateState *s;-//charf *buf; /* the input data */-//unsigned len; /* its length */-//int header; /* true if block header must be written */-{- bi_windup(s); /* align on byte boundary */+var BL_CODES = 19;+/* number of codes used to transfer the bit lengths */- if (header) {- put_short(s, len);- put_short(s, ~len);- }-// while (len--) {-// put_byte(s, *buf++);-// }- utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);- s.pending += len;-}+var HEAP_SIZE = 2*L_CODES + 1;+/* maximum heap size */++var MAX_BITS = 15;+/* All codes must not exceed MAX_BITS bits */++var Buf_size = 16;+/* size of bit buffer in bi_buf */-/* ===========================================================================- * Compares to subtrees, using the tree depth as tie breaker when- * the subtrees have equal frequency. This minimizes the worst case length.- */-function smaller(tree, n, m, depth) {- var _n2 = n*2;- var _m2 = m*2;- return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||- (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));-}/* ===========================================================================- * Restore the heap property by moving down the tree starting at node k,- * exchanging a node with the smallest of its two sons if necessary, stopping- * when the heap property is re-established (each father smaller than its- * two sons).+ * Constants*/-function pqdownheap(s, tree, k)-// deflate_state *s;-// ct_data *tree; /* the tree to restore */-// int k; /* node to move down */-{- var v = s.heap[k];- var j = k << 1; /* left son of k */- while (j <= s.heap_len) {- /* Set j to the smallest of the two sons: */- if (j < s.heap_len &&- smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {- j++;- }- /* Exit if v is smaller than both sons */- if (smaller(tree, v, s.heap[j], s.depth)) { break; }- /* Exchange v with the smallest son */- s.heap[k] = s.heap[j];- k = j;+var MAX_BL_BITS = 7;+/* Bit length codes must not exceed MAX_BL_BITS bits */- /* And continue down the tree, setting j to the left son of k */- j <<= 1;- }- s.heap[k] = v;-}+var END_BLOCK = 256;+/* end of block literal code */+var REP_3_6 = 16;+/* repeat previous bit length 3-6 times (2 bits of repeat count) */-// inlined manually-// var SMALLEST = 1;+var REPZ_3_10 = 17;+/* repeat a zero length 3-10 times (3 bits of repeat count) */++var REPZ_11_138 = 18;+/* repeat a zero length 11-138 times (7 bits of repeat count) */++var extra_lbits = /* extra bits for each length code */+ [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];++var extra_dbits = /* extra bits for each distance code */+ [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];++var extra_blbits = /* extra bits for each bit length code */+ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];++var bl_order =+ [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];+/* The lengths of the bit length codes are sent in order of decreasing+ * probability, to avoid transmitting the lengths for unused bit length codes.+ *//* ===========================================================================- * Send the block data compressed using the given Huffman trees+ * Local data. These are initialized only once.*/-function compress_block(s, ltree, dtree)-// deflate_state *s;-// const ct_data *ltree; /* literal tree */-// const ct_data *dtree; /* distance tree */-{- var dist; /* distance of matched string */- var lc; /* match length or unmatched char (if dist == 0) */- var lx = 0; /* running index in l_buf */- var code; /* the code to send */- var extra; /* number of extra bits to send */- if (s.last_lit !== 0) {- do {- dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);- lc = s.pending_buf[s.l_buf + lx];- lx++;+// We pre-fill arrays with 0 to avoid uninitialized gaps- if (dist === 0) {- send_code(s, lc, ltree); /* send a literal byte */- //Tracecv(isgraph(lc), (stderr," '%c' ", lc));- } else {- /* Here, lc is the match length - MIN_MATCH */- code = _length_code[lc];- send_code(s, code+LITERALS+1, ltree); /* send the length code */- extra = extra_lbits[code];- if (extra !== 0) {- lc -= base_length[code];- send_bits(s, lc, extra); /* send the extra length bits */- }- dist--; /* dist is now the match distance - 1 */- code = d_code(dist);- //Assert (code < D_CODES, "bad d_code");+var DIST_CODE_LEN = 512; /* see definition of array dist_code below */++// !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1+var static_ltree = new Array((L_CODES+2) * 2);+zero(static_ltree);+/* The static literal tree. Since the bit lengths are imposed, there is no+ * need for the L_CODES extra codes used during heap construction. However+ * The codes 286 and 287 are needed to build a canonical tree (see _tr_init+ * below).+ */++var static_dtree = new Array(D_CODES * 2);+zero(static_dtree);+/* The static distance tree. (Actually a trivial tree since all codes use+ * 5 bits.)+ */- send_code(s, code, dtree); /* send the distance code */- extra = extra_dbits[code];- if (extra !== 0) {- dist -= base_dist[code];- send_bits(s, dist, extra); /* send the extra distance bits */- }- } /* literal or match pair ? */+var _dist_code = new Array(DIST_CODE_LEN);+zero(_dist_code);+/* Distance codes. The first 256 values correspond to the distances+ * 3 .. 258, the last 256 values correspond to the top 8 bits of+ * the 15 bit distances.+ */- /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */- //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,- // "pendingBuf overflow");+var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);+zero(_length_code);+/* length code for each normalized match length (0 == MIN_MATCH) */- } while (lx < s.last_lit);- }+var base_length = new Array(LENGTH_CODES);+zero(base_length);+/* First normalized length for each code (0 = MIN_MATCH) */- send_code(s, END_BLOCK, ltree);-}+var base_dist = new Array(D_CODES);+zero(base_dist);+/* First normalized distance for each code (0 = distance of 1) */-/* ===========================================================================- * Construct one Huffman tree and assigns the code bit strings and lengths.- * Update the total bit length for the current block.- * IN assertion: the field freq is set for all tree elements.- * OUT assertions: the fields len and code are set to the optimal bit length- * and corresponding code. The length opt_len is updated; static_len is- * also updated if stree is not null. The field max_code is set.- */-function build_tree(s, desc)-// deflate_state *s;-// tree_desc *desc; /* the tree descriptor */-{- var tree = desc.dyn_tree;- var stree = desc.stat_desc.static_tree;- var has_stree = desc.stat_desc.has_stree;- var elems = desc.stat_desc.elems;- var n, m; /* iterate over heap elements */- var max_code = -1; /* largest code with non zero frequency */- var node; /* new node being created */+var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {- /* Construct the initial heap, with least frequent element in- * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].- * heap[0] is not used.- */- s.heap_len = 0;- s.heap_max = HEAP_SIZE;+ this.static_tree = static_tree; /* static tree or NULL */+ this.extra_bits = extra_bits; /* extra bits for each code or NULL */+ this.extra_base = extra_base; /* base index for extra_bits */+ this.elems = elems; /* max number of elements in the tree */+ this.max_length = max_length; /* max bit length for the codes */- for (n = 0; n < elems; n++) {- if (tree[n * 2]/*.Freq*/ !== 0) {- s.heap[++s.heap_len] = max_code = n;- s.depth[n] = 0;+ // show if `static_tree` has data or dummy - needed for monomorphic objects+ this.has_stree = static_tree && static_tree.length;+};- } else {- tree[n*2 + 1]/*.Len*/ = 0;- }- }- /* The pkzip format requires that at least one distance code exists,- * and that at least one bit should be sent even if there is only one- * possible code. So to avoid special checks later on we force at least- * two codes of non zero frequency.- */- while (s.heap_len < 2) {- node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);- tree[node * 2]/*.Freq*/ = 1;- s.depth[node] = 0;- s.opt_len--;+var static_l_desc;+var static_d_desc;+var static_bl_desc;- if (has_stree) {- s.static_len -= stree[node*2 + 1]/*.Len*/;- }- /* node is 0 or 1 so it does not have extra bits */- }- desc.max_code = max_code;- /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,- * establish sub-heaps of increasing lengths:- */- for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }+var TreeDesc = function(dyn_tree, stat_desc) {+ this.dyn_tree = dyn_tree; /* the dynamic tree */+ this.max_code = 0; /* largest code with non zero frequency */+ this.stat_desc = stat_desc; /* the corresponding static tree */+};- /* Construct the Huffman tree by repeatedly combining the least two- * frequent nodes.- */- node = elems; /* next internal node of the tree */- do {- //pqremove(s, tree, n); /* n = node of least frequency */- /*** pqremove ***/- n = s.heap[1/*SMALLEST*/];- s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];- pqdownheap(s, tree, 1/*SMALLEST*/);- /***/- m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */- s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */- s.heap[--s.heap_max] = m;+function d_code(dist) {+ return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];+}- /* Create a new node father of n and m */- tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;- s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;- tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;- /* and insert the new node in the heap */- s.heap[1/*SMALLEST*/] = node++;- pqdownheap(s, tree, 1/*SMALLEST*/);+/* ===========================================================================+ * Output a short LSB first on the stream.+ * IN assertion: there is enough room in pendingBuf.+ */+function put_short (s, w) {+// put_byte(s, (uch)((w) & 0xff));+// put_byte(s, (uch)((ush)(w) >> 8));+ s.pending_buf[s.pending++] = (w) & 0xff;+ s.pending_buf[s.pending++] = (w >>> 8) & 0xff;+}- } while (s.heap_len >= 2);- s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];+/* ===========================================================================+ * Send a value on a given number of bits.+ * IN assertion: length <= 16 and value fits in length bits.+ */+function send_bits(s, value, length) {+ if (s.bi_valid > (Buf_size - length)) {+ s.bi_buf |= (value << s.bi_valid) & 0xffff;+ put_short(s, s.bi_buf);+ s.bi_buf = value >> (Buf_size - s.bi_valid);+ s.bi_valid += length - Buf_size;+ } else {+ s.bi_buf |= (value << s.bi_valid) & 0xffff;+ s.bi_valid += length;+ }+}- /* At this point, the fields freq and dad are set. We can now- * generate the bit lengths.- */- gen_bitlen(s, desc);- /* The field len is now set, we can generate the bit codes */- gen_codes(tree, max_code, s.bl_count);+function send_code(s, c, tree) {+ send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);}/* ===========================================================================- * Scan a literal or distance tree to determine the frequencies of the codes- * in the bit length tree.+ * Reverse the first len bits of a code, using straightforward code (a faster+ * method would use a table)+ * IN assertion: 1 <= len <= 15*/-function scan_tree(s, tree, max_code)-// deflate_state *s;-// ct_data *tree; /* the tree to be scanned */-// int max_code; /* and its largest code of non zero frequency */-{- var n; /* iterates over all tree elements */- var prevlen = -1; /* last emitted length */- var curlen; /* length of current code */+function bi_reverse(code, len) {+ var res = 0;+ do {+ res |= code & 1;+ code >>>= 1;+ res <<= 1;+ } while (--len > 0);+ return res >>> 1;+}- var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */- var count = 0; /* repeat count of the current code */- var max_count = 7; /* max repeat count */- var min_count = 4; /* min repeat count */+/* ===========================================================================+ * Flush the bit buffer, keeping at most 7 bits in it.+ */+function bi_flush(s) {+ if (s.bi_valid === 16) {+ put_short(s, s.bi_buf);+ s.bi_buf = 0;+ s.bi_valid = 0;- if (nextlen === 0) {- max_count = 138;- min_count = 3;+ } else if (s.bi_valid >= 8) {+ s.pending_buf[s.pending++] = s.bi_buf & 0xff;+ s.bi_buf >>= 8;+ s.bi_valid -= 8;}- tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */+}- for (n = 0; n <= max_code; n++) {- curlen = nextlen;- nextlen = tree[(n+1)*2 + 1]/*.Len*/;- if (++count < max_count && curlen === nextlen) {- continue;+/* ===========================================================================+ * Compute the optimal bit lengths for a tree and update the total bit length+ * for the current block.+ * IN assertion: the fields freq and dad are set, heap[heap_max] and+ * above are the tree nodes sorted by increasing frequency.+ * OUT assertions: the field len is set to the optimal bit length, the+ * array bl_count contains the frequencies for each bit length.+ * The length opt_len is updated; static_len is also updated if stree is+ * not null.+ */+function gen_bitlen(s, desc)+// deflate_state *s;+// tree_desc *desc; /* the tree descriptor */+{+ var tree = desc.dyn_tree;+ var max_code = desc.max_code;+ var stree = desc.stat_desc.static_tree;+ var has_stree = desc.stat_desc.has_stree;+ var extra = desc.stat_desc.extra_bits;+ var base = desc.stat_desc.extra_base;+ var max_length = desc.stat_desc.max_length;+ var h; /* heap index */+ var n, m; /* iterate over the tree elements */+ var bits; /* bit length */+ var xbits; /* extra bits */+ var f; /* frequency */+ var overflow = 0; /* number of elements with bit length too large */- } else if (count < min_count) {- s.bl_tree[curlen * 2]/*.Freq*/ += count;+ for (bits = 0; bits <= MAX_BITS; bits++) {+ s.bl_count[bits] = 0;+ }- } else if (curlen !== 0) {+ /* In a first pass, compute the optimal bit lengths (which may+ * overflow in the case of the bit length tree).+ */+ tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */- if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }- s.bl_tree[REP_3_6*2]/*.Freq*/++;+ for (h = s.heap_max+1; h < HEAP_SIZE; h++) {+ n = s.heap[h];+ bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;+ if (bits > max_length) {+ bits = max_length;+ overflow++;+ }+ tree[n*2 + 1]/*.Len*/ = bits;+ /* We overwrite tree[n].Dad which is no longer needed */- } else if (count <= 10) {- s.bl_tree[REPZ_3_10*2]/*.Freq*/++;+ if (n > max_code) { continue; } /* not a leaf node */- } else {- s.bl_tree[REPZ_11_138*2]/*.Freq*/++;+ s.bl_count[bits]++;+ xbits = 0;+ if (n >= base) {+ xbits = extra[n-base];}+ f = tree[n * 2]/*.Freq*/;+ s.opt_len += f * (bits + xbits);+ if (has_stree) {+ s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);+ }+ }+ if (overflow === 0) { return; }- count = 0;- prevlen = curlen;-- if (nextlen === 0) {- max_count = 138;- min_count = 3;+ // Trace((stderr,"\nbit length overflow\n"));+ /* This happens for example on obj2 and pic of the Calgary corpus */- } else if (curlen === nextlen) {- max_count = 6;- min_count = 3;+ /* Find the first bit length which could increase: */+ do {+ bits = max_length-1;+ while (s.bl_count[bits] === 0) { bits--; }+ s.bl_count[bits]--; /* move one leaf down the tree */+ s.bl_count[bits+1] += 2; /* move one overflow item as its brother */+ s.bl_count[max_length]--;+ /* The brother of the overflow item also moves one step up,+ * but this does not affect bl_count[max_length]+ */+ overflow -= 2;+ } while (overflow > 0);- } else {- max_count = 7;- min_count = 4;+ /* Now recompute all bit lengths, scanning in increasing frequency.+ * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all+ * lengths instead of fixing only the wrong ones. This idea is taken+ * from 'ar' written by Haruhiko Okumura.)+ */+ for (bits = max_length; bits !== 0; bits--) {+ n = s.bl_count[bits];+ while (n !== 0) {+ m = s.heap[--h];+ if (m > max_code) { continue; }+ if (tree[m*2 + 1]/*.Len*/ !== bits) {+ // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));+ s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;+ tree[m*2 + 1]/*.Len*/ = bits;+ }+ n--;}}}/* ===========================================================================- * Send a literal or distance tree in compressed form, using the codes in- * bl_tree.+ * Generate the codes for a given tree and bit counts (which need not be+ * optimal).+ * IN assertion: the array bl_count contains the bit length statistics for+ * the given tree and the field len is set for all tree elements.+ * OUT assertion: the field code is set for all tree elements of non+ * zero code length.*/-function send_tree(s, tree, max_code)-// deflate_state *s;-// ct_data *tree; /* the tree to be scanned */-// int max_code; /* and its largest code of non zero frequency */+function gen_codes(tree, max_code, bl_count)+// ct_data *tree; /* the tree to decorate */+// int max_code; /* largest code with non zero frequency */+// ushf *bl_count; /* number of codes at each bit length */{- var n; /* iterates over all tree elements */- var prevlen = -1; /* last emitted length */- var curlen; /* length of current code */-- var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */-- var count = 0; /* repeat count of the current code */- var max_count = 7; /* max repeat count */- var min_count = 4; /* min repeat count */+ var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */+ var code = 0; /* running code value */+ var bits; /* bit index */+ var n; /* code index */- /* tree[max_code+1].Len = -1; */ /* guard already set */- if (nextlen === 0) {- max_count = 138;- min_count = 3;+ /* The distribution counts are first used to generate the code values+ * without bit reversal.+ */+ for (bits = 1; bits <= MAX_BITS; bits++) {+ next_code[bits] = code = (code + bl_count[bits-1]) << 1;}+ /* Check that the bit counts in bl_count are consistent. The last code+ * must be all ones.+ */+ //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,+ // "inconsistent bit counts");+ //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));- for (n = 0; n <= max_code; n++) {- curlen = nextlen;- nextlen = tree[(n+1)*2 + 1]/*.Len*/;-- if (++count < max_count && curlen === nextlen) {- continue;-- } else if (count < min_count) {- do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);-- } else if (curlen !== 0) {- if (curlen !== prevlen) {- send_code(s, curlen, s.bl_tree);- count--;- }- //Assert(count >= 3 && count <= 6, " 3_6?");- send_code(s, REP_3_6, s.bl_tree);- send_bits(s, count-3, 2);-- } else if (count <= 10) {- send_code(s, REPZ_3_10, s.bl_tree);- send_bits(s, count-3, 3);-- } else {- send_code(s, REPZ_11_138, s.bl_tree);- send_bits(s, count-11, 7);- }-- count = 0;- prevlen = curlen;- if (nextlen === 0) {- max_count = 138;- min_count = 3;-- } else if (curlen === nextlen) {- max_count = 6;- min_count = 3;+ for (n = 0; n <= max_code; n++) {+ var len = tree[n*2 + 1]/*.Len*/;+ if (len === 0) { continue; }+ /* Now reverse the bits */+ tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);- } else {- max_count = 7;- min_count = 4;- }+ //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",+ // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));}}/* ===========================================================================- * Construct the Huffman tree for the bit lengths and return the index in- * bl_order of the last bit length code to send.+ * Initialize the various 'constant' tables.*/-function build_bl_tree(s) {- var max_blindex; /* index of last bit length code of non zero freq */+function tr_static_init() {+ var n; /* iterates over tree elements */+ var bits; /* bit counter */+ var length; /* length value */+ var code; /* code value */+ var dist; /* distance index */+ var bl_count = new Array(MAX_BITS+1);+ /* number of codes at each bit length for an optimal tree */- /* Determine the bit length frequencies for literal and distance trees */- scan_tree(s, s.dyn_ltree, s.l_desc.max_code);- scan_tree(s, s.dyn_dtree, s.d_desc.max_code);+ // do check in _tr_init()+ //if (static_init_done) return;- /* Build the bit length tree: */- build_tree(s, s.bl_desc);- /* opt_len now includes the length of the tree representations, except- * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.- */+ /* For some embedded targets, global variables are not initialized: */+/*#ifdef NO_INIT_GLOBAL_POINTERS+ static_l_desc.static_tree = static_ltree;+ static_l_desc.extra_bits = extra_lbits;+ static_d_desc.static_tree = static_dtree;+ static_d_desc.extra_bits = extra_dbits;+ static_bl_desc.extra_bits = extra_blbits;+#endif*/- /* Determine the number of bit length codes to send. The pkzip format- * requires that at least 4 bit length codes be sent. (appnote.txt says- * 3 but the actual value used is 4.)- */- for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {- if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {- break;+ /* Initialize the mapping length (0..255) -> length code (0..28) */+ length = 0;+ for (code = 0; code < LENGTH_CODES-1; code++) {+ base_length[code] = length;+ for (n = 0; n < (1<<extra_lbits[code]); n++) {+ _length_code[length++] = code;}}- /* Update opt_len to include the bit length tree and counts */- s.opt_len += 3*(max_blindex+1) + 5+5+4;- //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",- // s->opt_len, s->static_len));+ //Assert (length == 256, "tr_static_init: length != 256");+ /* Note that the length 255 (match length 258) can be represented+ * in two different ways: code 284 + 5 bits or code 285, so we+ * overwrite length_code[255] to use the best encoding:+ */+ _length_code[length-1] = code;- return max_blindex;-}+ /* Initialize the mapping dist (0..32K) -> dist code (0..29) */+ dist = 0;+ for (code = 0 ; code < 16; code++) {+ base_dist[code] = dist;+ for (n = 0; n < (1<<extra_dbits[code]); n++) {+ _dist_code[dist++] = code;+ }+ }+ //Assert (dist == 256, "tr_static_init: dist != 256");+ dist >>= 7; /* from now on, all distances are divided by 128 */+ for ( ; code < D_CODES; code++) {+ base_dist[code] = dist << 7;+ for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {+ _dist_code[256 + dist++] = code;+ }+ }+ //Assert (dist == 256, "tr_static_init: 256+dist != 512");+ /* Construct the codes of the static literal tree */+ for (bits = 0; bits <= MAX_BITS; bits++) {+ bl_count[bits] = 0;+ }-/* ===========================================================================- * Send the header for a block using dynamic Huffman trees: the counts, the- * lengths of the bit length codes, the literal tree and the distance tree.- * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.- */-function send_all_trees(s, lcodes, dcodes, blcodes)-// deflate_state *s;-// int lcodes, dcodes, blcodes; /* number of codes for each tree */-{- var rank; /* index in bl_order */+ n = 0;+ while (n <= 143) {+ static_ltree[n*2 + 1]/*.Len*/ = 8;+ n++;+ bl_count[8]++;+ }+ while (n <= 255) {+ static_ltree[n*2 + 1]/*.Len*/ = 9;+ n++;+ bl_count[9]++;+ }+ while (n <= 279) {+ static_ltree[n*2 + 1]/*.Len*/ = 7;+ n++;+ bl_count[7]++;+ }+ while (n <= 287) {+ static_ltree[n*2 + 1]/*.Len*/ = 8;+ n++;+ bl_count[8]++;+ }+ /* Codes 286 and 287 do not exist, but we must include them in the+ * tree construction to get a canonical Huffman tree (longest code+ * all ones)+ */+ gen_codes(static_ltree, L_CODES+1, bl_count);- //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");- //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,- // "too many codes");- //Tracev((stderr, "\nbl counts: "));- send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */- send_bits(s, dcodes-1, 5);- send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */- for (rank = 0; rank < blcodes; rank++) {- //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));- send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);+ /* The static distance tree is trivial: */+ for (n = 0; n < D_CODES; n++) {+ static_dtree[n*2 + 1]/*.Len*/ = 5;+ static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);}- //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));- send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */- //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));+ // Now data ready and we can init static trees+ static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);+ static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);+ static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);- send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */- //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));+ //static_init_done = true;}/* ===========================================================================- * Check if the data type is TEXT or BINARY, using the following algorithm:- * - TEXT if the two conditions below are satisfied:- * a) There are no non-portable control characters belonging to the- * "black list" (0..6, 14..25, 28..31).- * b) There is at least one printable character belonging to the- * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).- * - BINARY otherwise.- * - The following partially-portable control characters form a- * "gray list" that is ignored in this detection algorithm:- * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).- * IN assertion: the fields Freq of dyn_ltree are set.+ * Initialize a new block.*/-function detect_data_type(s) {- /* black_mask is the bit mask of black-listed bytes- * set bits 0..6, 14..25, and 28..31- * 0xf3ffc07f = binary 11110011111111111100000001111111- */- var black_mask = 0xf3ffc07f;- var n;-- /* Check for non-textual ("black-listed") bytes. */- for (n = 0; n <= 31; n++, black_mask >>>= 1) {- if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {- return Z_BINARY;- }- }+function init_block(s) {+ var n; /* iterates over tree elements */- /* Check for textual ("white-listed") bytes. */- if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||- s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {- return Z_TEXT;- }- for (n = 32; n < LITERALS; n++) {- if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {- return Z_TEXT;- }- }+ /* Initialize the trees. */+ for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }+ for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }+ for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }- /* There are no "black-listed" or "white-listed" bytes:- * this stream either is empty or has tolerated ("gray-listed") bytes only.- */- return Z_BINARY;+ s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;+ s.opt_len = s.static_len = 0;+ s.last_lit = s.matches = 0;}-var static_init_done = false;-/* ===========================================================================- * Initialize the tree data structures for a new zlib stream.+ * Flush the bit buffer and align the output on a byte boundary*/-function _tr_init(s)+function bi_windup(s){-- if (!static_init_done) {- tr_static_init();- static_init_done = true;+ if (s.bi_valid > 8) {+ put_short(s, s.bi_buf);+ } else if (s.bi_valid > 0) {+ //put_byte(s, (Byte)s->bi_buf);+ s.pending_buf[s.pending++] = s.bi_buf;}-- s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);- s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);- s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);-s.bi_buf = 0;s.bi_valid = 0;+}- /* Initialize the first block of the first file: */- init_block(s);+/* ===========================================================================+ * Copy a stored block, storing first the length and its+ * one's complement if requested.+ */+function copy_block(s, buf, len, header)+//DeflateState *s;+//charf *buf; /* the input data */+//unsigned len; /* its length */+//int header; /* true if block header must be written */+{+ bi_windup(s); /* align on byte boundary */++ if (header) {+ put_short(s, len);+ put_short(s, ~len);+ }+// while (len--) {+// put_byte(s, *buf++);+// }+ utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);+ s.pending += len;}+/* ===========================================================================+ * Compares to subtrees, using the tree depth as tie breaker when+ * the subtrees have equal frequency. This minimizes the worst case length.+ */+function smaller(tree, n, m, depth) {+ var _n2 = n*2;+ var _m2 = m*2;+ return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||+ (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));+}/* ===========================================================================- * Send a stored block+ * Restore the heap property by moving down the tree starting at node k,+ * exchanging a node with the smallest of its two sons if necessary, stopping+ * when the heap property is re-established (each father smaller than its+ * two sons).*/-function _tr_stored_block(s, buf, stored_len, last)-//DeflateState *s;-//charf *buf; /* input block */-//ulg stored_len; /* length of input block */-//int last; /* one if this is the last block for a file */+function pqdownheap(s, tree, k)+// deflate_state *s;+// ct_data *tree; /* the tree to restore */+// int k; /* node to move down */{- send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */- copy_block(s, buf, stored_len, true); /* with header */+ var v = s.heap[k];+ var j = k << 1; /* left son of k */+ while (j <= s.heap_len) {+ /* Set j to the smallest of the two sons: */+ if (j < s.heap_len &&+ smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {+ j++;+ }+ /* Exit if v is smaller than both sons */+ if (smaller(tree, v, s.heap[j], s.depth)) { break; }++ /* Exchange v with the smallest son */+ s.heap[k] = s.heap[j];+ k = j;++ /* And continue down the tree, setting j to the left son of k */+ j <<= 1;+ }+ s.heap[k] = v;}+// inlined manually+// var SMALLEST = 1;+/* ===========================================================================- * Send one empty static block to give enough lookahead for inflate.- * This takes 10 bits, of which 7 may remain in the bit buffer.+ * Send the block data compressed using the given Huffman trees*/-function _tr_align(s) {- send_bits(s, STATIC_TREES<<1, 3);- send_code(s, END_BLOCK, static_ltree);- bi_flush(s);+function compress_block(s, ltree, dtree)+// deflate_state *s;+// const ct_data *ltree; /* literal tree */+// const ct_data *dtree; /* distance tree */+{+ var dist; /* distance of matched string */+ var lc; /* match length or unmatched char (if dist == 0) */+ var lx = 0; /* running index in l_buf */+ var code; /* the code to send */+ var extra; /* number of extra bits to send */++ if (s.last_lit !== 0) {+ do {+ dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);+ lc = s.pending_buf[s.l_buf + lx];+ lx++;++ if (dist === 0) {+ send_code(s, lc, ltree); /* send a literal byte */+ //Tracecv(isgraph(lc), (stderr," '%c' ", lc));+ } else {+ /* Here, lc is the match length - MIN_MATCH */+ code = _length_code[lc];+ send_code(s, code+LITERALS+1, ltree); /* send the length code */+ extra = extra_lbits[code];+ if (extra !== 0) {+ lc -= base_length[code];+ send_bits(s, lc, extra); /* send the extra length bits */+ }+ dist--; /* dist is now the match distance - 1 */+ code = d_code(dist);+ //Assert (code < D_CODES, "bad d_code");++ send_code(s, code, dtree); /* send the distance code */+ extra = extra_dbits[code];+ if (extra !== 0) {+ dist -= base_dist[code];+ send_bits(s, dist, extra); /* send the extra distance bits */+ }+ } /* literal or match pair ? */++ /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */+ //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,+ // "pendingBuf overflow");++ } while (lx < s.last_lit);+ }++ send_code(s, END_BLOCK, ltree);}/* ===========================================================================- * Determine the best encoding for the current block: dynamic trees, static- * trees or store, and output the encoded block to the zip file.+ * Construct one Huffman tree and assigns the code bit strings and lengths.+ * Update the total bit length for the current block.+ * IN assertion: the field freq is set for all tree elements.+ * OUT assertions: the fields len and code are set to the optimal bit length+ * and corresponding code. The length opt_len is updated; static_len is+ * also updated if stree is not null. The field max_code is set.*/-function _tr_flush_block(s, buf, stored_len, last)-//DeflateState *s;-//charf *buf; /* input block, or NULL if too old */-//ulg stored_len; /* length of input block */-//int last; /* one if this is the last block for a file */+function build_tree(s, desc)+// deflate_state *s;+// tree_desc *desc; /* the tree descriptor */{- var opt_lenb, static_lenb; /* opt_len and static_len in bytes */- var max_blindex = 0; /* index of last bit length code of non zero freq */+ var tree = desc.dyn_tree;+ var stree = desc.stat_desc.static_tree;+ var has_stree = desc.stat_desc.has_stree;+ var elems = desc.stat_desc.elems;+ var n, m; /* iterate over heap elements */+ var max_code = -1; /* largest code with non zero frequency */+ var node; /* new node being created */++ /* Construct the initial heap, with least frequent element in+ * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].+ * heap[0] is not used.+ */+ s.heap_len = 0;+ s.heap_max = HEAP_SIZE;- /* Build the Huffman trees unless a stored block is forced */- if (s.level > 0) {+ for (n = 0; n < elems; n++) {+ if (tree[n * 2]/*.Freq*/ !== 0) {+ s.heap[++s.heap_len] = max_code = n;+ s.depth[n] = 0;- /* Check if the file is binary or text */- if (s.strm.data_type === Z_UNKNOWN) {- s.strm.data_type = detect_data_type(s);+ } else {+ tree[n*2 + 1]/*.Len*/ = 0;}+ }- /* Construct the literal and distance trees */- build_tree(s, s.l_desc);- // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,- // s->static_len));-- build_tree(s, s.d_desc);- // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,- // s->static_len));- /* At this point, opt_len and static_len are the total bit lengths of- * the compressed block data, excluding the tree representations.- */+ /* The pkzip format requires that at least one distance code exists,+ * and that at least one bit should be sent even if there is only one+ * possible code. So to avoid special checks later on we force at least+ * two codes of non zero frequency.+ */+ while (s.heap_len < 2) {+ node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);+ tree[node * 2]/*.Freq*/ = 1;+ s.depth[node] = 0;+ s.opt_len--;- /* Build the bit length tree for the above two trees, and get the index- * in bl_order of the last bit length code to send.- */- max_blindex = build_bl_tree(s);+ if (has_stree) {+ s.static_len -= stree[node*2 + 1]/*.Len*/;+ }+ /* node is 0 or 1 so it does not have extra bits */+ }+ desc.max_code = max_code;- /* Determine the best encoding. Compute the block lengths in bytes. */- opt_lenb = (s.opt_len+3+7) >>> 3;- static_lenb = (s.static_len+3+7) >>> 3;+ /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,+ * establish sub-heaps of increasing lengths:+ */+ for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }- // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",- // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,- // s->last_lit));+ /* Construct the Huffman tree by repeatedly combining the least two+ * frequent nodes.+ */+ node = elems; /* next internal node of the tree */+ do {+ //pqremove(s, tree, n); /* n = node of least frequency */+ /*** pqremove ***/+ n = s.heap[1/*SMALLEST*/];+ s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];+ pqdownheap(s, tree, 1/*SMALLEST*/);+ /***/- if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }+ m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */- } else {- // Assert(buf != (char*)0, "lost buf");- opt_lenb = static_lenb = stored_len + 5; /* force a stored block */- }+ s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */+ s.heap[--s.heap_max] = m;- if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {- /* 4: two words for the lengths */+ /* Create a new node father of n and m */+ tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;+ s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;+ tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;- /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.- * Otherwise we can't have processed more than WSIZE input bytes since- * the last block flush, because compression would have been- * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to- * transform a block into a stored block.- */- _tr_stored_block(s, buf, stored_len, last);+ /* and insert the new node in the heap */+ s.heap[1/*SMALLEST*/] = node++;+ pqdownheap(s, tree, 1/*SMALLEST*/);- } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {+ } while (s.heap_len >= 2);- send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);- compress_block(s, static_ltree, static_dtree);+ s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];- } else {- send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);- send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);- compress_block(s, s.dyn_ltree, s.dyn_dtree);- }- // Assert (s->compressed_len == s->bits_sent, "bad compressed size");- /* The above check is made mod 2^32, for files larger than 512 MB- * and uLong implemented on 32 bits.+ /* At this point, the fields freq and dad are set. We can now+ * generate the bit lengths.*/- init_block(s);+ gen_bitlen(s, desc);- if (last) {- bi_windup(s);- }- // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,- // s->compressed_len-7*last));+ /* The field len is now set, we can generate the bit codes */+ gen_codes(tree, max_code, s.bl_count);}+/* ===========================================================================- * Save the match info and tally the frequency counts. Return true if- * the current block must be flushed.+ * Scan a literal or distance tree to determine the frequencies of the codes+ * in the bit length tree.*/-function _tr_tally(s, dist, lc)+function scan_tree(s, tree, max_code)// deflate_state *s;-// unsigned dist; /* distance of matched string */-// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */+// ct_data *tree; /* the tree to be scanned */+// int max_code; /* and its largest code of non zero frequency */{- //var out_length, in_length, dcode;-- s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;- s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;+ var n; /* iterates over all tree elements */+ var prevlen = -1; /* last emitted length */+ var curlen; /* length of current code */- s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;- s.last_lit++;+ var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */- if (dist === 0) {- /* lc is the unmatched char */- s.dyn_ltree[lc*2]/*.Freq*/++;- } else {- s.matches++;- /* Here, lc is the match length - MIN_MATCH */- dist--; /* dist = match distance - 1 */- //Assert((ush)dist < (ush)MAX_DIST(s) &&- // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&- // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");+ var count = 0; /* repeat count of the current code */+ var max_count = 7; /* max repeat count */+ var min_count = 4; /* min repeat count */- s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;- s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;+ if (nextlen === 0) {+ max_count = 138;+ min_count = 3;}+ tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */-// (!) This block is disabled in zlib defailts,-// don't enable it for binary compatibility--//#ifdef TRUNCATE_BLOCK-// /* Try to guess if it is profitable to stop the current block here */-// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {-// /* Compute an upper bound for the compressed length */-// out_length = s.last_lit*8;-// in_length = s.strstart - s.block_start;-//-// for (dcode = 0; dcode < D_CODES; dcode++) {-// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);-// }-// out_length >>>= 3;-// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",-// // s->last_lit, in_length, out_length,-// // 100L - out_length*100L/in_length));-// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {-// return true;-// }-// }-//#endif+ for (n = 0; n <= max_code; n++) {+ curlen = nextlen;+ nextlen = tree[(n+1)*2 + 1]/*.Len*/;- return (s.last_lit === s.lit_bufsize-1);- /* We avoid equality with lit_bufsize because of wraparound at 64K- * on 16 bit machines and because stored blocks are restricted to- * 64K-1 bytes.- */-}+ if (++count < max_count && curlen === nextlen) {+ continue;-exports._tr_init = _tr_init;-exports._tr_stored_block = _tr_stored_block;-exports._tr_flush_block = _tr_flush_block;-exports._tr_tally = _tr_tally;-exports._tr_align = _tr_align;-},{"../utils/common":69}],81:[function(require,module,exports){-'use strict';+ } else if (count < min_count) {+ s.bl_tree[curlen * 2]/*.Freq*/ += count;+ } else if (curlen !== 0) {-function ZStream() {- /* next input byte */- this.input = null; // JS specific, because we have no pointers- this.next_in = 0;- /* number of bytes available at input */- this.avail_in = 0;- /* total number of input bytes read so far */- this.total_in = 0;- /* next output byte should be put there */- this.output = null; // JS specific, because we have no pointers- this.next_out = 0;- /* remaining free space at output */- this.avail_out = 0;- /* total number of bytes output so far */- this.total_out = 0;- /* last error message, NULL if no error */- this.msg = ''/*Z_NULL*/;- /* not visible by applications */- this.state = null;- /* best guess about the data type: binary or text */- this.data_type = 2/*Z_UNKNOWN*/;- /* adler32 value of the uncompressed data */- this.adler = 0;-}+ if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }+ s.bl_tree[REP_3_6*2]/*.Freq*/++;-module.exports = ZStream;-},{}],82:[function(require,module,exports){-module.exports = require('./lib/retry');-},{"./lib/retry":83}],83:[function(require,module,exports){-var RetryOperation = require('./retry_operation');+ } else if (count <= 10) {+ s.bl_tree[REPZ_3_10*2]/*.Freq*/++;-exports.operation = function(options) {- var timeouts = exports.timeouts(options);- return new RetryOperation(timeouts);-};+ } else {+ s.bl_tree[REPZ_11_138*2]/*.Freq*/++;+ }-exports.timeouts = function(options) {- if (options instanceof Array) {- return [].concat(options);- }+ count = 0;+ prevlen = curlen;- var opts = {- retries: 10,- factor: 2,- minTimeout: 1 * 1000,- maxTimeout: Infinity,- randomize: false- };- for (var key in options) {- opts[key] = options[key];- }+ if (nextlen === 0) {+ max_count = 138;+ min_count = 3;- if (opts.minTimeout > opts.maxTimeout) {- throw new Error('minTimeout is greater than maxTimeout');- }+ } else if (curlen === nextlen) {+ max_count = 6;+ min_count = 3;- var timeouts = [];- for (var i = 0; i < opts.retries; i++) {- timeouts.push(this._createTimeout(i, opts));+ } else {+ max_count = 7;+ min_count = 4;+ }}+}- // sort the array numerically ascending- timeouts.sort(function(a,b) {- return a - b;- });-- return timeouts;-};-exports._createTimeout = function(attempt, opts) {- var random = (opts.randomize)- ? (Math.random() + 1)- : 1;+/* ===========================================================================+ * Send a literal or distance tree in compressed form, using the codes in+ * bl_tree.+ */+function send_tree(s, tree, max_code)+// deflate_state *s;+// ct_data *tree; /* the tree to be scanned */+// int max_code; /* and its largest code of non zero frequency */+{+ var n; /* iterates over all tree elements */+ var prevlen = -1; /* last emitted length */+ var curlen; /* length of current code */- var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));- timeout = Math.min(timeout, opts.maxTimeout);+ var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */- return timeout;-};-},{"./retry_operation":84}],84:[function(require,module,exports){-function RetryOperation(timeouts) {- this._timeouts = timeouts;- this._fn = null;- this._errors = [];- this._attempts = 1;- this._operationTimeout = null;- this._operationTimeoutCb = null;- this._timeout = null;-}-module.exports = RetryOperation;+ var count = 0; /* repeat count of the current code */+ var max_count = 7; /* max repeat count */+ var min_count = 4; /* min repeat count */-RetryOperation.prototype.retry = function(err) {- if (this._timeout) {- clearTimeout(this._timeout);+ /* tree[max_code+1].Len = -1; */ /* guard already set */+ if (nextlen === 0) {+ max_count = 138;+ min_count = 3;}- if (!err) {- return false;- }+ for (n = 0; n <= max_code; n++) {+ curlen = nextlen;+ nextlen = tree[(n+1)*2 + 1]/*.Len*/;- this._errors.push(err);+ if (++count < max_count && curlen === nextlen) {+ continue;- var timeout = this._timeouts.shift();- if (timeout === undefined) {- return false;- }+ } else if (count < min_count) {+ do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);- this._attempts++;+ } else if (curlen !== 0) {+ if (curlen !== prevlen) {+ send_code(s, curlen, s.bl_tree);+ count--;+ }+ //Assert(count >= 3 && count <= 6, " 3_6?");+ send_code(s, REP_3_6, s.bl_tree);+ send_bits(s, count-3, 2);- var self = this;- setTimeout(function() {- self._fn(self._attempts);+ } else if (count <= 10) {+ send_code(s, REPZ_3_10, s.bl_tree);+ send_bits(s, count-3, 3);- if (self._operationTimeoutCb) {- self._timeout = setTimeout(function() {- self._operationTimeoutCb(self._attempts);- }, self._operationTimeout);+ } else {+ send_code(s, REPZ_11_138, s.bl_tree);+ send_bits(s, count-11, 7);}- }, timeout);- return true;-};+ count = 0;+ prevlen = curlen;+ if (nextlen === 0) {+ max_count = 138;+ min_count = 3;-RetryOperation.prototype.attempt = function(fn, timeoutOps) {- this._fn = fn;+ } else if (curlen === nextlen) {+ max_count = 6;+ min_count = 3;- if (timeoutOps) {- if (timeoutOps.timeout) {- this._operationTimeout = timeoutOps.timeout;+ } else {+ max_count = 7;+ min_count = 4;}- if (timeoutOps.cb) {- this._operationTimeoutCb = timeoutOps.cb;+ }+}+++/* ===========================================================================+ * Construct the Huffman tree for the bit lengths and return the index in+ * bl_order of the last bit length code to send.+ */+function build_bl_tree(s) {+ var max_blindex; /* index of last bit length code of non zero freq */++ /* Determine the bit length frequencies for literal and distance trees */+ scan_tree(s, s.dyn_ltree, s.l_desc.max_code);+ scan_tree(s, s.dyn_dtree, s.d_desc.max_code);++ /* Build the bit length tree: */+ build_tree(s, s.bl_desc);+ /* opt_len now includes the length of the tree representations, except+ * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.+ */++ /* Determine the number of bit length codes to send. The pkzip format+ * requires that at least 4 bit length codes be sent. (appnote.txt says+ * 3 but the actual value used is 4.)+ */+ for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {+ if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {+ break;}}+ /* Update opt_len to include the bit length tree and counts */+ s.opt_len += 3*(max_blindex+1) + 5+5+4;+ //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",+ // s->opt_len, s->static_len));- this._fn(this._attempts);+ return max_blindex;+}- var self = this;- if (this._operationTimeoutCb) {- this._timeout = setTimeout(function() {- self._operationTimeoutCb();- }, self._operationTimeout);++/* ===========================================================================+ * Send the header for a block using dynamic Huffman trees: the counts, the+ * lengths of the bit length codes, the literal tree and the distance tree.+ * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.+ */+function send_all_trees(s, lcodes, dcodes, blcodes)+// deflate_state *s;+// int lcodes, dcodes, blcodes; /* number of codes for each tree */+{+ var rank; /* index in bl_order */++ //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");+ //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,+ // "too many codes");+ //Tracev((stderr, "\nbl counts: "));+ send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */+ send_bits(s, dcodes-1, 5);+ send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */+ for (rank = 0; rank < blcodes; rank++) {+ //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));+ send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);}-};+ //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));-RetryOperation.prototype.try = function(fn) {- console.log('Using RetryOperation.try() is deprecated');- this.attempt(fn);-};+ send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */+ //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));-RetryOperation.prototype.start = function(fn) {- console.log('Using RetryOperation.start() is deprecated');- this.attempt(fn);-};+ send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */+ //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));+}-RetryOperation.prototype.start = RetryOperation.prototype.try;-RetryOperation.prototype.errors = function() {- return this._errors;-};+/* ===========================================================================+ * Check if the data type is TEXT or BINARY, using the following algorithm:+ * - TEXT if the two conditions below are satisfied:+ * a) There are no non-portable control characters belonging to the+ * "black list" (0..6, 14..25, 28..31).+ * b) There is at least one printable character belonging to the+ * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).+ * - BINARY otherwise.+ * - The following partially-portable control characters form a+ * "gray list" that is ignored in this detection algorithm:+ * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).+ * IN assertion: the fields Freq of dyn_ltree are set.+ */+function detect_data_type(s) {+ /* black_mask is the bit mask of black-listed bytes+ * set bits 0..6, 14..25, and 28..31+ * 0xf3ffc07f = binary 11110011111111111100000001111111+ */+ var black_mask = 0xf3ffc07f;+ var n;-RetryOperation.prototype.attempts = function() {- return this._attempts;-};+ /* Check for non-textual ("black-listed") bytes. */+ for (n = 0; n <= 31; n++, black_mask >>>= 1) {+ if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {+ return Z_BINARY;+ }+ }-RetryOperation.prototype.mainError = function() {- if (this._errors.length === 0) {- return null;+ /* Check for textual ("white-listed") bytes. */+ if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||+ s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {+ return Z_TEXT;+ }+ for (n = 32; n < LITERALS; n++) {+ if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {+ return Z_TEXT;+ }}- var counts = {};- var mainError = null;- var mainErrorCount = 0;+ /* There are no "black-listed" or "white-listed" bytes:+ * this stream either is empty or has tolerated ("gray-listed") bytes only.+ */+ return Z_BINARY;+}- for (var i = 0; i < this._errors.length; i++) {- var error = this._errors[i];- var message = error.message;- var count = (counts[message] || 0) + 1;- counts[message] = count;+var static_init_done = false;++/* ===========================================================================+ * Initialize the tree data structures for a new zlib stream.+ */+function _tr_init(s)+{- if (count >= mainErrorCount) {- mainError = error;- mainErrorCount = count;- }+ if (!static_init_done) {+ tr_static_init();+ static_init_done = true;}- return mainError;-};-},{}],85:[function(require,module,exports){-module.exports = function arrayEquals(array) {- // if the other array is a falsy value, return- if (!array)- return false;+ s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);+ s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);+ s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);- // compare lengths - can save a lot of time- if (this.length != array.length)- return false;+ s.bi_buf = 0;+ s.bi_valid = 0;- for (var i = 0, l = this.length; i < l; i++) {- // Check if we have nested arrays- if (this[i] instanceof Array && array[i] instanceof Array) {- // recurse into the nested arrays- if (!arrayEquals.apply(this[i], [array[i]]))- return false;- } else if (this[i] != array[i]) {- // Warning - two different object instances will never be equal:- // {x:20} != {x:20}- return false;- }- }- return true;+ /* Initialize the first block of the first file: */+ init_block(s);}-},{}],86:[function(require,module,exports){-exports.Interop = require('./interop');--},{"./interop":87}],87:[function(require,module,exports){-var transform = require('./transform');-var arrayEquals = require('./array-equals');--function Interop() { }-module.exports = Interop;--/**- * This map holds the most recent Plan A offer/answer SDP that was converted- * to Plan B, with the SDP type ('offer' or 'answer') as keys and the SDP- * string as values.- *- * @type {{}}+/* ===========================================================================+ * Send a stored block*/-var cache = {};+function _tr_stored_block(s, buf, stored_len, last)+//DeflateState *s;+//charf *buf; /* input block */+//ulg stored_len; /* length of input block */+//int last; /* one if this is the last block for a file */+{+ send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */+ copy_block(s, buf, stored_len, true); /* with header */+}-/**- * This method transforms a Plan A SDP to an equivalent Plan B SDP. A- * PeerConnection wrapper transforms the SDP to Plan B before passing it to the- * application.- *- * @param desc- * @returns {*}- */-Interop.prototype.toPlanB = function(desc) {- //#region Preliminary input validation.+/* ===========================================================================+ * Send one empty static block to give enough lookahead for inflate.+ * This takes 10 bits, of which 7 may remain in the bit buffer.+ */+function _tr_align(s) {+ send_bits(s, STATIC_TREES<<1, 3);+ send_code(s, END_BLOCK, static_ltree);+ bi_flush(s);+}- if (typeof desc !== 'object' || desc === null ||- typeof desc.sdp !== 'string') {- console.warn('An empty description was passed as an argument.');- return desc;- }- // Objectify the SDP for easier manipulation.- var session = transform.parse(desc.sdp);+/* ===========================================================================+ * Determine the best encoding for the current block: dynamic trees, static+ * trees or store, and output the encoded block to the zip file.+ */+function _tr_flush_block(s, buf, stored_len, last)+//DeflateState *s;+//charf *buf; /* input block, or NULL if too old */+//ulg stored_len; /* length of input block */+//int last; /* one if this is the last block for a file */+{+ var opt_lenb, static_lenb; /* opt_len and static_len in bytes */+ var max_blindex = 0; /* index of last bit length code of non zero freq */- // If the SDP contains no media, there's nothing to transform.- if (typeof session.media === 'undefined' ||- !Array.isArray(session.media) || session.media.length === 0) {- console.warn('The description has no media.');- return desc;- }+ /* Build the Huffman trees unless a stored block is forced */+ if (s.level > 0) {- // Try some heuristics to "make sure" this is a Plan A SDP. Plan B SDP has- // a video, an audio and a data "channel" at most.- if (session.media.length <= 3 && session.media.every(function(m) {- return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;- })) {- console.warn('This description does not look like Plan A.');- return desc;+ /* Check if the file is binary or text */+ if (s.strm.data_type === Z_UNKNOWN) {+ s.strm.data_type = detect_data_type(s);}- //#endregion+ /* Construct the literal and distance trees */+ build_tree(s, s.l_desc);+ // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,+ // s->static_len));- // Plan A SDP is our "precious". Cache it for later use in the Plan B ->- // Plan A transformation.- cache[desc.type] = desc.sdp;+ build_tree(s, s.d_desc);+ // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,+ // s->static_len));+ /* At this point, opt_len and static_len are the total bit lengths of+ * the compressed block data, excluding the tree representations.+ */- //#region Convert from Plan A to Plan B.+ /* Build the bit length tree for the above two trees, and get the index+ * in bl_order of the last bit length code to send.+ */+ max_blindex = build_bl_tree(s);- // We rebuild the session.media array.- var media = session.media;- session.media = [];+ /* Determine the best encoding. Compute the block lengths in bytes. */+ opt_lenb = (s.opt_len+3+7) >>> 3;+ static_lenb = (s.static_len+3+7) >>> 3;- // Associative array that maps channel types to channel objects for fast- // access to channel objects by their type, e.g. channels['audio']->channel- // obj.- var channels = {};+ // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",+ // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,+ // s->last_lit));- // Used to build the group:BUNDLE value after the channels construction- // loop.- var types = [];+ if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }- // Implode the Plan A m-lines/tracks into Plan B "channels".- media.forEach(function(mLine) {+ } else {+ // Assert(buf != (char*)0, "lost buf");+ opt_lenb = static_lenb = stored_len + 5; /* force a stored block */+ }- // rtcp-mux is required in the Plan B SDP.- if (typeof mLine.rtcpMux !== 'string' ||- mLine.rtcpMux !== 'rtcp-mux') {- throw new Error('Cannot convert to Plan B because m-lines ' +- 'without the rtcp-mux attribute were found.');- }+ if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {+ /* 4: two words for the lengths */- // If we don't have a channel for this mLine.type, then use this mLine- // as the channel basis.- if (typeof channels[mLine.type] === 'undefined') {- channels[mLine.type] = mLine;- }+ /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.+ * Otherwise we can't have processed more than WSIZE input bytes since+ * the last block flush, because compression would have been+ * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to+ * transform a block into a stored block.+ */+ _tr_stored_block(s, buf, stored_len, last);- // Add sources to the channel and handle a=msid.- if (typeof mLine.sources === 'object') {- Object.keys(mLine.sources).forEach(function(ssrc) {- // Assign the sources to the channel.- channels[mLine.type].sources[ssrc] = mLine.sources[ssrc];+ } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {- // In Plan B the msid is an SSRC attribute. Also, we don't care- // about the obsolete label and mslabel attributes.- channels[mLine.type].sources[ssrc].msid = mLine.msid;+ send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);+ compress_block(s, static_ltree, static_dtree);- // NOTE ssrcs in ssrc groups will share msids, as- // draft-uberti-rtcweb-plan-00 mandates.- });- }+ } else {+ send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);+ send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);+ compress_block(s, s.dyn_ltree, s.dyn_dtree);+ }+ // Assert (s->compressed_len == s->bits_sent, "bad compressed size");+ /* The above check is made mod 2^32, for files larger than 512 MB+ * and uLong implemented on 32 bits.+ */+ init_block(s);- // Add ssrc groups to the channel.- if (typeof mLine.ssrcGroups !== 'undefined' &&- Array.isArray(mLine.ssrcGroups)) {+ if (last) {+ bi_windup(s);+ }+ // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,+ // s->compressed_len-7*last));+}- // Create the ssrcGroups array, if it's not defined.- if (typeof channel.ssrcGroups === 'undefined' ||- !Array.isArray(channel.ssrcGroups)) {- channel.ssrcGroups = [];- }+/* ===========================================================================+ * Save the match info and tally the frequency counts. Return true if+ * the current block must be flushed.+ */+function _tr_tally(s, dist, lc)+// deflate_state *s;+// unsigned dist; /* distance of matched string */+// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */+{+ //var out_length, in_length, dcode;- channel.ssrcGroups = channel.ssrcGroups.concat(mLine.ssrcGroups);- }+ s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;+ s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;- if (channels[mLine.type] === mLine) {- // Copy ICE related stuff from the principal media line.- mLine.candidates = media[0].candidates;- mLine.iceUfrag = media[0].iceUfrag;- mLine.icePwd = media[0].icePwd;- mLine.fingerprint = media[0].fingerprint;+ s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;+ s.last_lit++;- // Plan B mids are in ['audio', 'video', 'data']- mLine.mid = mLine.type;+ if (dist === 0) {+ /* lc is the unmatched char */+ s.dyn_ltree[lc*2]/*.Freq*/++;+ } else {+ s.matches++;+ /* Here, lc is the match length - MIN_MATCH */+ dist--; /* dist = match distance - 1 */+ //Assert((ush)dist < (ush)MAX_DIST(s) &&+ // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&+ // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");- // Plan B doesn't support/need the bundle-only attribute.- delete mLine.bundleOnly;+ s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;+ s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;+ }- // In Plan B the msid is an SSRC attribute.- delete mLine.msid;+// (!) This block is disabled in zlib defailts,+// don't enable it for binary compatibility- // Used to build the group:BUNDLE value after this loop.- types.push(mLine.type);+//#ifdef TRUNCATE_BLOCK+// /* Try to guess if it is profitable to stop the current block here */+// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {+// /* Compute an upper bound for the compressed length */+// out_length = s.last_lit*8;+// in_length = s.strstart - s.block_start;+//+// for (dcode = 0; dcode < D_CODES; dcode++) {+// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);+// }+// out_length >>>= 3;+// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",+// // s->last_lit, in_length, out_length,+// // 100L - out_length*100L/in_length));+// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {+// return true;+// }+// }+//#endif- // Add the channel to the new media array.- session.media.push(mLine);- }- });+ return (s.last_lit === s.lit_bufsize-1);+ /* We avoid equality with lit_bufsize because of wraparound at 64K+ * on 16 bit machines and because stored blocks are restricted to+ * 64K-1 bytes.+ */+}- // We regenerate the BUNDLE group with the new mids.- session.groups.every(function(group) {- if (group.type === 'BUNDLE') {- group.mids = types.join(' ');- return false;- } else {- return true;- }- });+exports._tr_init = _tr_init;+exports._tr_stored_block = _tr_stored_block;+exports._tr_flush_block = _tr_flush_block;+exports._tr_tally = _tr_tally;+exports._tr_align = _tr_align;+},{"../utils/common":70}],82:[function(require,module,exports){+'use strict';- // msid semantic- session.msidSemantic = {- semantic: 'WMS',- token: '*'- };- var resStr = transform.write(session);+function ZStream() {+ /* next input byte */+ this.input = null; // JS specific, because we have no pointers+ this.next_in = 0;+ /* number of bytes available at input */+ this.avail_in = 0;+ /* total number of input bytes read so far */+ this.total_in = 0;+ /* next output byte should be put there */+ this.output = null; // JS specific, because we have no pointers+ this.next_out = 0;+ /* remaining free space at output */+ this.avail_out = 0;+ /* total number of bytes output so far */+ this.total_out = 0;+ /* last error message, NULL if no error */+ this.msg = ''/*Z_NULL*/;+ /* not visible by applications */+ this.state = null;+ /* best guess about the data type: binary or text */+ this.data_type = 2/*Z_UNKNOWN*/;+ /* adler32 value of the uncompressed data */+ this.adler = 0;+}- return new RTCSessionDescription({- type: desc.type,- sdp: resStr- });+module.exports = ZStream;+},{}],83:[function(require,module,exports){+module.exports = require('./lib/retry');+},{"./lib/retry":84}],84:[function(require,module,exports){+var RetryOperation = require('./retry_operation');- //#endregion+exports.operation = function(options) {+ var timeouts = exports.timeouts(options);+ return new RetryOperation(timeouts);};-/**- * This method transforms a Plan B SDP to an equivalent Plan A SDP. A- * PeerConnection wrapper transforms the SDP to Plan A before passing it to FF.- *- * @param desc- * @returns {*}- */-Interop.prototype.toPlanA = function(desc) {+exports.timeouts = function(options) {+ if (options instanceof Array) {+ return [].concat(options);+ }- //#region Preliminary input validation.+ var opts = {+ retries: 10,+ factor: 2,+ minTimeout: 1 * 1000,+ maxTimeout: Infinity,+ randomize: false+ };+ for (var key in options) {+ opts[key] = options[key];+ }- if (typeof desc !== 'object' || desc === null ||- typeof desc.sdp !== 'string') {- console.warn('An empty description was passed as an argument.');- return desc;- }+ if (opts.minTimeout > opts.maxTimeout) {+ throw new Error('minTimeout is greater than maxTimeout');+ }- var session = transform.parse(desc.sdp);+ var timeouts = [];+ for (var i = 0; i < opts.retries; i++) {+ timeouts.push(this._createTimeout(i, opts));+ }- // If the SDP contains no media, there's nothing to transform.- if (typeof session.media === 'undefined' ||- !Array.isArray(session.media) || session.media.length === 0) {- console.warn('The description has no media.');- return desc;- }+ // sort the array numerically ascending+ timeouts.sort(function(a,b) {+ return a - b;+ });- // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has- // a video, an audio and a data "channel" at most.- if (session.media.length > 3 || !session.media.every(function(m) {- return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;- })) {- console.warn('This description does not look like Plan B.');- return desc;- }+ return timeouts;+};- // Make sure this Plan B SDP can be converted to a Plan A SDP.- var mids = [];- session.media.forEach(function(m) {- mids.push(m.mid);- });+exports._createTimeout = function(attempt, opts) {+ var random = (opts.randomize)+ ? (Math.random() + 1)+ : 1;- var hasBundle = false;- if (typeof session.groups !== 'undefined' &&- Array.isArray(session.groups)) {- hasBundle = session.groups.every(function(g) {- return g.type !== 'BUNDLE' ||- arrayEquals.apply(g.mids.sort(), [mids.sort()]);- });- }+ var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));+ timeout = Math.min(timeout, opts.maxTimeout);- if (!hasBundle) {- throw new Error("Cannot convert to Plan A because m-lines that are " +- "not bundled were found.");- }+ return timeout;+};+},{"./retry_operation":85}],85:[function(require,module,exports){+function RetryOperation(timeouts) {+ this._timeouts = timeouts;+ this._fn = null;+ this._errors = [];+ this._attempts = 1;+ this._operationTimeout = null;+ this._operationTimeoutCb = null;+ this._timeout = null;+}+module.exports = RetryOperation;- //#endregion+RetryOperation.prototype.retry = function(err) {+ if (this._timeout) {+ clearTimeout(this._timeout);+ }+ if (!err) {+ return false;+ }- //#region Convert from Plan B to Plan A.+ this._errors.push(err);- // Unfortunately, a Plan B offer/answer doesn't have enough information to- // rebuild an equivalent Plan A offer/answer.- //- // For example, if this is a local answer (in Plan A style) that we convert- // to Plan B prior to handing it over to the application (the- // PeerConnection wrapper called us, for instance, after a successful- // createAnswer), we want to remember the m-line at which we've seen the- // (local) SSRC. That's because when the application wants to do call the- // SLD method, forcing us to do the inverse transformation (from Plan B to- // Plan A), we need to know to which m-line to assign the (local) SSRC. We- // also need to know all the other m-lines that the original answer had and- // include them in the transformed answer as well.- //- // Another example is if this is a remote offer that we convert to Plan B- // prior to giving it to the application, we want to remember the mid at- // which we've seen the (remote) SSRC.- //- // In the iteration that follows, we use the cached Plan A (if it exists)- // to assign mids to ssrcs.+ var timeout = this._timeouts.shift();+ if (timeout === undefined) {+ return false;+ }- var cached;- if (typeof cache[desc.type] !== 'undefined') {- cached = transform.parse(cache[desc.type]);+ this._attempts++;++ var self = this;+ setTimeout(function() {+ self._fn(self._attempts);++ if (self._operationTimeoutCb) {+ self._timeout = setTimeout(function() {+ self._operationTimeoutCb(self._attempts);+ }, self._operationTimeout);}+ }, timeout);- // A helper map that sends mids to m-line objects. We use it later to- // rebuild the Plan A style session.media array.- var media = {};- session.media.forEach(function(channel) {- if (typeof channel.rtcpMux !== 'string' ||- channel.rtcpMux !== 'rtcp-mux') {- throw new Error("Cannot convert to Plan A because m-lines " +- "without the rtcp-mux attribute were found.");- }+ return true;+};- // With rtcp-mux and bundle all the channels should have the same ICE- // stuff.- var sources = channel.sources;- var ssrcGroups = channel.ssrcGroups;- var candidates = channel.candidates;- var iceUfrag = channel.iceUfrag;- var icePwd = channel.icePwd;- var fingerprint = channel.fingerprint;- var port = channel.port;-- // We'll use the "channel" object as a prototype for each new "mLine"- // that we create, but first we need to clean it up a bit.- delete channel.sources;- delete channel.ssrcGroups;- delete channel.candidates;- delete channel.iceUfrag;- delete channel.icePwd;- delete channel.fingerprint;- delete channel.port;- delete channel.mid;+RetryOperation.prototype.attempt = function(fn, timeoutOps) {+ this._fn = fn;- // inverted ssrc group map- var invertedGroups = {};- if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {- ssrcGroups.forEach(function (ssrcGroup) {+ if (timeoutOps) {+ if (timeoutOps.timeout) {+ this._operationTimeout = timeoutOps.timeout;+ }+ if (timeoutOps.cb) {+ this._operationTimeoutCb = timeoutOps.cb;+ }+ }- // TODO(gp) find out how to receive simulcast with FF. For the- // time being, hide it.- if (ssrcGroup.semantics === 'SIM') {- return;- }+ this._fn(this._attempts);- if (typeof ssrcGroup.ssrcs !== 'undefined' &&- Array.isArray(ssrcGroup.ssrcs)) {- ssrcGroup.ssrcs.forEach(function (ssrc) {- if (typeof invertedGroups[ssrc] === 'undefined') {- invertedGroups[ssrc] = [];- }+ var self = this;+ if (this._operationTimeoutCb) {+ this._timeout = setTimeout(function() {+ self._operationTimeoutCb();+ }, self._operationTimeout);+ }+};- invertedGroups[ssrc].push(ssrcGroup);- });- }- });- }+RetryOperation.prototype.try = function(fn) {+ console.log('Using RetryOperation.try() is deprecated');+ this.attempt(fn);+};- // ssrc to m-line index.- var mLines = {};+RetryOperation.prototype.start = function(fn) {+ console.log('Using RetryOperation.start() is deprecated');+ this.attempt(fn);+};- if (typeof sources === 'object') {+RetryOperation.prototype.start = RetryOperation.prototype.try;- // Explode the Plan B channel sources with one m-line per source.- Object.keys(sources).forEach(function(ssrc) {+RetryOperation.prototype.errors = function() {+ return this._errors;+};- var mLine;- if (typeof invertedGroups[ssrc] !== 'undefined' &&- Array.isArray(invertedGroups[ssrc])) {- invertedGroups[ssrc].every(function (ssrcGroup) {- // ssrcGroup.ssrcs *is* an Array, no need to check- // again here.- return ssrcGroup.ssrcs.every(function (related) {- if (typeof mLines[related] === 'object') {- mLine = mLines[related];- return false;- } else {- return true;- }- });- });- }+RetryOperation.prototype.attempts = function() {+ return this._attempts;+};- if (typeof mLine === 'object') {- // the m-line already exists. Just add the source.- mLine.sources[ssrc] = sources[ssrc];- delete sources[ssrc].msid;- } else {- // Use the "channel" as a prototype for the "mLine".- mLine = Object.create(channel);- mLines[ssrc] = mLine;-- // Assign the msid of the source to the m-line.- mLine.msid = sources[ssrc].msid;- delete sources[ssrc].msid;-- // We assign one SSRC per media line.- mLine.sources = {};- mLine.sources[ssrc] = sources[ssrc];- mLine.ssrcGroups = invertedGroups[ssrc];-- // Use the cached Plan A SDP (if it exists) to assign SSRCs to- // mids.- if (typeof cached !== 'undefined' &&- typeof cached.media !== 'undefined' &&- Array.isArray(cached.media)) {-- cached.media.forEach(function(m) {- if (typeof m.sources === 'object') {- Object.keys(m.sources).forEach(function(s) {- if (s === ssrc) {- mLine.mid = m.mid;- }- });- }- });- }+RetryOperation.prototype.mainError = function() {+ if (this._errors.length === 0) {+ return null;+ }- if (typeof mLine.mid === 'undefined') {+ var counts = {};+ var mainError = null;+ var mainErrorCount = 0;- // If this is an SSRC that we see for the first time assign- // it a new mid. This is typically the case when this- // method is called to transform a remote description for- // the first time or when there is a new SSRC in the remote- // description because a new peer has joined the- // conference. Local SSRCs should have already been added- // to the map in the toPlanB method.- //- // Because FF generates answers in Plan A style, we MUST- // already have a cached answer with all the local SSRCs- // mapped to some mLine/mid.+ for (var i = 0; i < this._errors.length; i++) {+ var error = this._errors[i];+ var message = error.message;+ var count = (counts[message] || 0) + 1;- if (desc.type === 'answer') {- throw new Error("An unmapped SSRC was found.");- }+ counts[message] = count;- mLine.mid = [channel.type, '-', ssrc].join('');- }+ if (count >= mainErrorCount) {+ mainError = error;+ mainErrorCount = count;+ }+ }- // Include the candidates in the 1st media line.- mLine.candidates = candidates;- mLine.iceUfrag = iceUfrag;- mLine.icePwd = icePwd;- mLine.fingerprint = fingerprint;- mLine.port = port;+ return mainError;+};+},{}],86:[function(require,module,exports){+module.exports = function arrayEquals(array) {+ // if the other array is a falsy value, return+ if (!array)+ return false;- media[mLine.mid] = mLine;- }- });- }- });+ // compare lengths - can save a lot of time+ if (this.length != array.length)+ return false;- // Rebuild the media array in the right order and add the missing mLines- // (missing from the Plan B SDP).- session.media = [];- mids = []; // reuse+ for (var i = 0, l = this.length; i < l; i++) {+ // Check if we have nested arrays+ if (this[i] instanceof Array && array[i] instanceof Array) {+ // recurse into the nested arrays+ if (!arrayEquals.apply(this[i], [array[i]]))+ return false;+ } else if (this[i] != array[i]) {+ // Warning - two different object instances will never be equal:+ // {x:20} != {x:20}+ return false;+ }+ }+ return true;+}- if (desc.type === 'answer') {- // The media lines in the answer must match the media lines in the- // offer. The order is important too. Here we use the cached offer to- // find the m-lines that are missing (from the converted answer), and- // use the cached answer to complete the converted answer.+},{}],87:[function(require,module,exports){+exports.Interop = require('./interop');- if (typeof cache['offer'] === 'undefined') {- throw new Error("An answer is being processed but we couldn't " +- "find a cached offer.");- }+},{"./interop":88}],88:[function(require,module,exports){+"use strict";- var cachedOffer = transform.parse(cache['offer']);+var transform = require('./transform');+var arrayEquals = require('./array-equals');- if (typeof cachedOffer === 'undefined' ||- typeof cachedOffer.media === 'undefined' ||- !Array.isArray(cachedOffer.media)) {- // FIXME(gp) is this really a problem in the general case?- throw new Error("The cached offer has no media.");- }+function Interop() {- cachedOffer.media.forEach(function(mo) {+ /**+ * This map holds the most recent Unified Plan offer/answer SDP that was+ * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and+ * the SDP string as values.+ *+ * @type {{}}+ */+ this.cache = {};+}- var mLine;- if (typeof media[mo.mid] === 'undefined') {+module.exports = Interop;- // This is probably an m-line containing a remote track only.- // It MUST exist in the cached answer as a remote track only- // mLine.- cached.media.every(function(ma) {- if (mo.mid == ma.mid) {- mLine = ma;- return false;- } else {- return true;- }- });- } else {- mLine = media[mo.mid];- }+/**+ * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A+ * PeerConnection wrapper transforms the SDP to Plan B before passing it to the+ * application.+ *+ * @param desc+ * @returns {*}+ */+Interop.prototype.toPlanB = function(desc) {- if (typeof mLine === 'undefined') {- throw new Error("The cached offer contains an m-line that " +- "doesn't exist neither in the cached answer nor in " +- "the converted answer.");- }+ //#region Preliminary input validation.- session.media.push(mLine);- mids.push(mLine.mid);- });- } else {+ if (typeof desc !== 'object' || desc === null ||+ typeof desc.sdp !== 'string') {+ console.warn('An empty description was passed as an argument.');+ return desc;+ }- // SDP offer/answer (and the JSEP spec) forbids removing an m-section- // under any circumstances. If we are no longer interested in sending a- // track, we just remove the msid and ssrc attributes and set it to- // either a=recvonly (as the reofferer, we must use recvonly if the- // other side was previously sending on the m-section, but we can also- // leave the possibility open if it wasn't previously in use), or- // a=inacive.+ // Objectify the SDP for easier manipulation.+ var session = transform.parse(desc.sdp);- if (typeof cached !== 'undefined' &&- typeof cached.media !== 'undefined' &&- Array.isArray(cached.media)) {- cached.media.forEach(function(pm) {- mids.push(pm.mid);- if (typeof media[pm.mid] !== 'undefined') {- session.media.push(media[pm.mid]);- } else {- delete pm.msid;- delete pm.sources;- delete pm.ssrcGroups;- pm.direction = 'recvonly';- session.media.push(pm);- }- });- }+ // If the SDP contains no media, there's nothing to transform.+ if (typeof session.media === 'undefined' ||+ !Array.isArray(session.media) || session.media.length === 0) {+ console.warn('The description has no media.');+ return desc;+ }- // Add all the remaining (new) m-lines of the transformed SDP.- Object.keys(media).forEach(function(mid) {- if (mids.indexOf(mid) === -1) {- mids.push(mid);- session.media.push(media[mid]);- }- });+ // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B+ // SDP has a video, an audio and a data "channel" at most.+ if (session.media.length <= 3 && session.media.every(function(m) {+ return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;+ })) {+ console.warn('This description does not look like Unified Plan.');+ return desc;}- // We regenerate the BUNDLE group (since we regenerated the mids)- session.groups.every(function(group) {- if (group.type === 'BUNDLE') {- group.mids = mids.join(' ');- return false;- } else {- return true;- }- });+ //#endregion- // msid semantic- session.msidSemantic = {- semantic: 'WMS',- token: '*'- };+ // Unified Plan SDP is our "precious". Cache it for later use in the Plan B+ // -> Unified Plan transformation.+ this.cache[desc.type] = desc.sdp;- var resStr = transform.write(session);+ //#region Convert from Unified Plan to Plan B.- // Cache the transformed SDP (Plan A) for later re-use in this function.- cache[desc.type] = resStr;+ // We rebuild the session.media array.+ var media = session.media;+ session.media = [];- return new RTCSessionDescription({- type: desc.type,- sdp: resStr- });+ // Associative array that maps channel types to channel objects for fast+ // access to channel objects by their type, e.g. type2bl['audio']->channel+ // obj.+ var type2bl = {};- //#endregion-};+ // Used to build the group:BUNDLE value after the channels construction+ // loop.+ var types = [];-},{"./array-equals":85,"./transform":88}],88:[function(require,module,exports){-var transform = require('sdp-transform');+ // Implode the Unified Plan m-lines/tracks into Plan B channels.+ media.forEach(function(unifiedLine) {-exports.write = function(session, opts) {+ // rtcp-mux is required in the Plan B SDP.+ if ((typeof unifiedLine.rtcpMux !== 'string' ||+ unifiedLine.rtcpMux !== 'rtcp-mux') &&+ unifiedLine.direction !== 'inactive') {+ throw new Error('Cannot convert to Plan B because m-lines ' ++ 'without the rtcp-mux attribute were found.');+ }- if (typeof session !== 'undefined' &&- typeof session.media !== 'undefined' &&- Array.isArray(session.media)) {+ if (unifiedLine.type === 'application') {+ session.media.push(unifiedLine);+ types.push(unifiedLine.mid);+ return;+ }- session.media.forEach(function (mLine) {- // expand sources to ssrcs- if (typeof mLine.sources !== 'undefined' &&- Object.keys(mLine.sources).length !== 0) {- mLine.ssrcs = [];- Object.keys(mLine.sources).forEach(function (ssrc) {- var source = mLine.sources[ssrc];- Object.keys(source).forEach(function (attribute) {- mLine.ssrcs.push({- id: ssrc,- attribute: attribute,- value: source[attribute]- });+ // If we don't have a channel for this unifiedLine.type, then use this unifiedLine+ // as the channel basis.+ if (typeof type2bl[unifiedLine.type] === 'undefined') {+ type2bl[unifiedLine.type] = unifiedLine;+ }++ // Add sources to the channel and handle a=msid.+ if (typeof unifiedLine.sources === 'object') {+ Object.keys(unifiedLine.sources).forEach(function(ssrc) {+ if (typeof type2bl[unifiedLine.type].sources !== 'object')+ type2bl[unifiedLine.type].sources = {};++ // Assign the sources to the channel.+ type2bl[unifiedLine.type].sources[ssrc] = unifiedLine.sources[ssrc];++ if (typeof unifiedLine.msid !== 'undefined') {+ // In Plan B the msid is an SSRC attribute. Also, we don't+ // care about the obsolete label and mslabel attributes.+ //+ // Note that it is not guaranteed that the unifiedLine will have+ // an msid. recvonly channels in particular don't have one.+ type2bl[unifiedLine.type].sources[ssrc].msid = unifiedLine.msid;+ }+ // NOTE ssrcs in ssrc groups will share msids, as+ // draft-uberti-rtcweb-plan-00 mandates.});- });- delete mLine.sources;}- // join ssrcs in ssrc groups- if (typeof mLine.ssrcGroups !== 'undefined' &&- Array.isArray(mLine.ssrcGroups)) {- mLine.ssrcGroups.forEach(function (ssrcGroup) {- if (typeof ssrcGroup.ssrcs !== 'undefined' &&- Array.isArray(ssrcGroup.ssrcs)) {- ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');+ // Add ssrc groups to the channel.+ if (typeof unifiedLine.ssrcGroups !== 'undefined' &&+ Array.isArray(unifiedLine.ssrcGroups)) {++ // Create the ssrcGroups array, if it's not defined.+ if (typeof type2bl[unifiedLine.type].ssrcGroups === 'undefined' ||+ !Array.isArray(type2bl[unifiedLine.type].ssrcGroups)) {+ type2bl[unifiedLine.type].ssrcGroups = [];}- });- }- });- }- // join group mids- if (typeof session !== 'undefined' &&- typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {+ type2bl[unifiedLine.type].ssrcGroups = type2bl[unifiedLine.type].ssrcGroups.concat(unifiedLine.ssrcGroups);+ }- session.groups.forEach(function (g) {- if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {- g.mids = g.mids.join(' ');- }- });- }+ if (type2bl[unifiedLine.type] === unifiedLine) {+ // Copy ICE related stuff from the principal media line.+ unifiedLine.candidates = media[0].candidates;+ unifiedLine.iceUfrag = media[0].iceUfrag;+ unifiedLine.icePwd = media[0].icePwd;+ unifiedLine.fingerprint = media[0].fingerprint;- return transform.write(session, opts);-};+ // Plan B mids are in ['audio', 'video', 'data']+ unifiedLine.mid = unifiedLine.type;-exports.parse = function(sdp) {- var session = transform.parse(sdp);+ // Plan B doesn't support/need the bundle-only attribute.+ delete unifiedLine.bundleOnly;- if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&- Array.isArray(session.media)) {+ // In Plan B the msid is an SSRC attribute.+ delete unifiedLine.msid;- session.media.forEach(function (mLine) {- // group sources attributes by ssrc- if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {- mLine.sources = {};- mLine.ssrcs.forEach(function (ssrc) {- if (!mLine.sources[ssrc.id])- mLine.sources[ssrc.id] = {};- mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;- });+ // Used to build the group:BUNDLE value after this loop.+ types.push(unifiedLine.type);- delete mLine.ssrcs;- }+ // Add the channel to the new media array.+ session.media.push(unifiedLine);+ }+ });- // split ssrcs in ssrc groups- if (typeof mLine.ssrcGroups !== 'undefined' &&- Array.isArray(mLine.ssrcGroups)) {- mLine.ssrcGroups.forEach(function (ssrcGroup) {- if (typeof ssrcGroup.ssrcs === 'string') {- ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');- }- });+ // We regenerate the BUNDLE group with the new mids.+ session.groups.some(function(group) {+ if (group.type === 'BUNDLE') {+ group.mids = types.join(' ');+ return true;}});- }- // split group mids- if (typeof session !== 'undefined' &&- typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {- session.groups.forEach(function (g) {- if (typeof g.mids === 'string') {- g.mids = g.mids.split(' ');- }+ // msid semantic+ session.msidSemantic = {+ semantic: 'WMS',+ token: '*'+ };++ var resStr = transform.write(session);++ return new RTCSessionDescription({+ type: desc.type,+ sdp: resStr});- }- return session;+ //#endregion};+/**+ * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A+ * PeerConnection wrapper transforms the SDP to Unified Plan before passing it+ * to FF.+ *+ * @param desc+ * @returns {*}+ */+Interop.prototype.toUnifiedPlan = function(desc) {-},{"sdp-transform":90}],89:[function(require,module,exports){-var grammar = module.exports = {- v: [{- name: 'version',- reg: /^(\d*)$/- }],- o: [{ //o=- 20518 0 IN IP4 203.0.113.1- // NB: sessionId will be a String in most cases because it is huge- name: 'origin',- reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,- names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],- format: "%s %s %d %s IP%d %s"- }],- // default parsing of these only (though some of these feel outdated)- s: [{ name: 'name' }],- i: [{ name: 'description' }],- u: [{ name: 'uri' }],- e: [{ name: 'email' }],- p: [{ name: 'phone' }],- z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..- r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly- //k: [{}], // outdated thing ignored- t: [{ //t=0 0- name: 'timing',- reg: /^(\d*) (\d*)/,- names: ['start', 'stop'],- format: "%d %d"- }],- c: [{ //c=IN IP4 10.47.197.26- name: 'connection',- reg: /^IN IP(\d) (\S*)/,- names: ['version', 'ip'],- format: "IN IP%d %s"- }],- b: [{ //b=AS:4000- push: 'bandwidth',- reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,- names: ['type', 'limit'],- format: "%s:%s"- }],- m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31- // NB: special - pushes to session- // TODO: rtp/fmtp should be filtered by the payloads found here?- reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,- names: ['type', 'port', 'protocol', 'payloads'],- format: "%s %d %s %s"- }],- a: [- { //a=rtpmap:110 opus/48000/2- push: 'rtp',- reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,- names: ['payload', 'codec', 'rate', 'encoding'],- format: function (o) {- return (o.encoding) ?- "rtpmap:%d %s/%s/%s":- "rtpmap:%d %s/%s";- }- },- { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000- push: 'fmtp',- reg: /^fmtp:(\d*) (\S*)/,- names: ['payload', 'config'],- format: "fmtp:%d %s"- },- { //a=control:streamid=0- name: 'control',- reg: /^control:(.*)/,- format: "control:%s"- },- { //a=rtcp:65179 IN IP4 193.84.77.194- name: 'rtcp',- reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,- names: ['port', 'netType', 'ipVer', 'address'],- format: function (o) {- return (o.address != null) ?- "rtcp:%d %s IP%d %s":- "rtcp:%d";- }- },- { //a=rtcp-fb:98 trr-int 100- push: 'rtcpFbTrrInt',- reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,- names: ['payload', 'value'],- format: "rtcp-fb:%d trr-int %d"- },- { //a=rtcp-fb:98 nack rpsi- push: 'rtcpFb',- reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,- names: ['payload', 'type', 'subtype'],- format: function (o) {- return (o.subtype != null) ?- "rtcp-fb:%s %s %s":- "rtcp-fb:%s %s";- }- },- { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset- //a=extmap:1/recvonly URI-gps-string- push: 'ext',- reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,- names: ['value', 'uri', 'config'], // value may include "/direction" suffix- format: function (o) {- return (o.config != null) ?- "extmap:%s %s %s":- "extmap:%s %s";- }- },- {- //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32- push: 'crypto',- reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,- names: ['id', 'suite', 'config', 'sessionConfig'],- format: function (o) {- return (o.sessionConfig != null) ?- "crypto:%d %s %s %s":- "crypto:%d %s %s";- }- },- { //a=setup:actpass- name: 'setup',- reg: /^setup:(\w*)/,- format: "setup:%s"- },- { //a=mid:1- name: 'mid',- reg: /^mid:([^\s]*)/,- format: "mid:%s"- },- { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a- name: 'msid',- reg: /^msid:(.*)/,- format: "msid:%s"- },- { //a=ptime:20- name: 'ptime',- reg: /^ptime:(\d*)/,- format: "ptime:%d"- },- { //a=maxptime:60- name: 'maxptime',- reg: /^maxptime:(\d*)/,- format: "maxptime:%d"- },- { //a=sendrecv- name: 'direction',- reg: /^(sendrecv|recvonly|sendonly|inactive)/- },- { //a=ice-lite- name: 'icelite',- reg: /^(ice-lite)/- },- { //a=ice-ufrag:F7gI- name: 'iceUfrag',- reg: /^ice-ufrag:(\S*)/,- format: "ice-ufrag:%s"- },- { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g- name: 'icePwd',- reg: /^ice-pwd:(\S*)/,- format: "ice-pwd:%s"- },- { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33- name: 'fingerprint',- reg: /^fingerprint:(\S*) (\S*)/,- names: ['type', 'hash'],- format: "fingerprint:%s %s"- },- {- //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host- //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0- //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0- push:'candidates',- reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,- names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],- format: function (o) {- var str = "candidate:%s %d %s %d %s %d typ %s";- // NB: candidate has two optional chunks, so %void middle one if it's missing- str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";- if (o.generation != null) {- str += " generation %d";- }- return str;- }- },- { //a=end-of-candidates (keep after the candidates line for readability)- name: 'endOfCandidates',- reg: /^(end-of-candidates)/- },- { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...- name: 'remoteCandidates',- reg: /^remote-candidates:(.*)/,- format: "remote-candidates:%s"- },- { //a=ice-options:google-ice- name: 'iceOptions',- reg: /^ice-options:(\S*)/,- format: "ice-options:%s"- },- { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1- push: "ssrcs",- reg: /^ssrc:(\d*) ([\w_]*):(.*)/,- names: ['id', 'attribute', 'value'],- format: "ssrc:%d %s:%s"- },- { //a=ssrc-group:FEC 1 2- push: "ssrcGroups",- reg: /^ssrc-group:(\w*) (.*)/,- names: ['semantics', 'ssrcs'],- format: "ssrc-group:%s %s"- },- { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV- name: "msidSemantic",- reg: /^msid-semantic:\s?(\w*) (\S*)/,- names: ['semantic', 'token'],- format: "msid-semantic: %s %s" // space after ":" is not accidental- },- { //a=group:BUNDLE audio video- push: 'groups',- reg: /^group:(\w*) (.*)/,- names: ['type', 'mids'],- format: "group:%s %s"- },- { //a=rtcp-mux- name: 'rtcpMux',- reg: /^(rtcp-mux)/- },- { // any a= that we don't understand is kepts verbatim on media.invalid- push: 'invalid',- names: ["value"]+ //#region Preliminary input validation.++ if (typeof desc !== 'object' || desc === null ||+ typeof desc.sdp !== 'string') {+ console.warn('An empty description was passed as an argument.');+ return desc;+ }++ var session = transform.parse(desc.sdp);++ // If the SDP contains no media, there's nothing to transform.+ if (typeof session.media === 'undefined' ||+ !Array.isArray(session.media) || session.media.length === 0) {+ console.warn('The description has no media.');+ return desc;+ }++ // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has+ // a video, an audio and a data "channel" at most.+ if (session.media.length > 3 || !session.media.every(function(m) {+ return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;+ })) {+ console.warn('This description does not look like Plan B.');+ return desc;}- ]-};-// set sensible defaults to avoid polluting the grammar with boring details-Object.keys(grammar).forEach(function (key) {- var objs = grammar[key];- objs.forEach(function (obj) {- if (!obj.reg) {- obj.reg = /(.*)/;+ // Make sure this Plan B SDP can be converted to a Unified Plan SDP.+ var mids = [];+ session.media.forEach(function(m) {+ mids.push(m.mid);+ });++ var hasBundle = false;+ if (typeof session.groups !== 'undefined' &&+ Array.isArray(session.groups)) {+ hasBundle = session.groups.every(function(g) {+ return g.type !== 'BUNDLE' ||+ arrayEquals.apply(g.mids.sort(), [mids.sort()]);+ });}- if (!obj.format) {- obj.format = "%s";++ if (!hasBundle) {+ throw new Error("Cannot convert to Unified Plan because m-lines that" ++ " are not bundled were found.");}- });-});-},{}],90:[function(require,module,exports){-var parser = require('./parser');-var writer = require('./writer');+ //#endregion-exports.write = writer;-exports.parse = parser.parse;-exports.parseFmtpConfig = parser.parseFmtpConfig;-exports.parsePayloads = parser.parsePayloads;-exports.parseRemoteCandidates = parser.parseRemoteCandidates;-},{"./parser":91,"./writer":92}],91:[function(require,module,exports){-var toIntIfInt = function (v) {- return String(Number(v)) === v ? Number(v) : v;-};+ //#region Convert from Plan B to Unified Plan.-var attachProperties = function (match, location, names, rawName) {- if (rawName && !names) {- location[rawName] = toIntIfInt(match[1]);- }- else {- for (var i = 0; i < names.length; i += 1) {- if (match[i+1] != null) {- location[names[i]] = toIntIfInt(match[i+1]);- }+ // Unfortunately, a Plan B offer/answer doesn't have enough information to+ // rebuild an equivalent Unified Plan offer/answer.+ //+ // For example, if this is a local answer (in Unified Plan style) that we+ // convert to Plan B prior to handing it over to the application (the+ // PeerConnection wrapper called us, for instance, after a successful+ // createAnswer), we want to remember the m-line at which we've seen the+ // (local) SSRC. That's because when the application wants to do call the+ // SLD method, forcing us to do the inverse transformation (from Plan B to+ // Unified Plan), we need to know to which m-line to assign the (local)+ // SSRC. We also need to know all the other m-lines that the original+ // answer had and include them in the transformed answer as well.+ //+ // Another example is if this is a remote offer that we convert to Plan B+ // prior to giving it to the application, we want to remember the mid at+ // which we've seen the (remote) SSRC.+ //+ // In the iteration that follows, we use the cached Unified Plan (if it+ // exists) to assign mids to ssrcs.++ var cached;+ if (typeof this.cache[desc.type] !== 'undefined') {+ cached = transform.parse(this.cache[desc.type]);}- }-};-var parseReg = function (obj, location, content) {- var needsBlank = obj.name && obj.names;- if (obj.push && !location[obj.push]) {- location[obj.push] = [];- }- else if (needsBlank && !location[obj.name]) {- location[obj.name] = {};- }- var keyLocation = obj.push ?- {} : // blank object that will be pushed- needsBlank ? location[obj.name] : location; // otherwise, named location or root+ // A helper map that sends mids to m-line objects. We use it later to+ // rebuild the Unified Plan style session.media array.+ var mid2ul = {};+ session.media.forEach(function(bLine) {+ if ((typeof bLine.rtcpMux !== 'string' ||+ bLine.rtcpMux !== 'rtcp-mux') &&+ bLine.direction !== 'inactive') {+ throw new Error("Cannot convert to Unified Plan because m-lines " ++ "without the rtcp-mux attribute were found.");+ }- attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);+ if (bLine.type === 'application') {+ mid2ul[bLine.mid] = bLine;+ return;+ }- if (obj.push) {- location[obj.push].push(keyLocation);- }-};+ // With rtcp-mux and bundle all the channels should have the same ICE+ // stuff.+ var sources = bLine.sources;+ var ssrcGroups = bLine.ssrcGroups;+ var candidates = bLine.candidates;+ var iceUfrag = bLine.iceUfrag;+ var icePwd = bLine.icePwd;+ var fingerprint = bLine.fingerprint;+ var port = bLine.port;++ // We'll use the "bLine" object as a prototype for each new "mLine"+ // that we create, but first we need to clean it up a bit.+ delete bLine.sources;+ delete bLine.ssrcGroups;+ delete bLine.candidates;+ delete bLine.iceUfrag;+ delete bLine.icePwd;+ delete bLine.fingerprint;+ delete bLine.port;+ delete bLine.mid;-var grammar = require('./grammar');-var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);+ // inverted ssrc group map+ var ssrc2group = {};+ if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {+ ssrcGroups.forEach(function (ssrcGroup) {-exports.parse = function (sdp) {- var session = {}- , media = []- , location = session; // points at where properties go under (one of the above)+ // TODO(gp) find out how to receive simulcast with FF. For the+ // time being, hide it.+ if (ssrcGroup.semantics === 'SIM') {+ return;+ }- // parse lines we understand- sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {- var type = l[0];- var content = l.slice(2);- if (type === 'm') {- media.push({rtp: [], fmtp: []});- location = media[media.length-1]; // point at latest media line- }+ if (typeof ssrcGroup.ssrcs !== 'undefined' &&+ Array.isArray(ssrcGroup.ssrcs)) {+ ssrcGroup.ssrcs.forEach(function (ssrc) {+ if (typeof ssrc2group[ssrc] === 'undefined') {+ ssrc2group[ssrc] = [];+ }- for (var j = 0; j < (grammar[type] || []).length; j += 1) {- var obj = grammar[type][j];- if (obj.reg.test(content)) {- return parseReg(obj, location, content);- }+ ssrc2group[ssrc].push(ssrcGroup);+ });+ }+ });+ }++ // ssrc to m-line index.+ var ssrc2ml = {};++ if (typeof sources === 'object') {++ // Explode the Plan B channel sources with one m-line per source.+ Object.keys(sources).forEach(function(ssrc) {++ // The (unified) m-line for this SSRC. We either create it from+ // scratch or, if it's a grouped SSRC, we re-use a related+ // mline. In other words, if the source is grouped with another+ // source, put the two together in the same m-line.+ var unifiedLine;+ if (typeof ssrc2group[ssrc] !== 'undefined' &&+ Array.isArray(ssrc2group[ssrc])) {+ ssrc2group[ssrc].some(function (ssrcGroup) {+ // ssrcGroup.ssrcs *is* an Array, no need to check+ // again here.+ return ssrcGroup.ssrcs.some(function (related) {+ if (typeof ssrc2ml[related] === 'object') {+ unifiedLine = ssrc2ml[related];+ return true;+ }+ });+ });+ }++ if (typeof unifiedLine === 'object') {+ // the m-line already exists. Just add the source.+ unifiedLine.sources[ssrc] = sources[ssrc];+ delete sources[ssrc].msid;+ } else {+ // Use the "bLine" as a prototype for the "unifiedLine".+ unifiedLine = Object.create(bLine);+ ssrc2ml[ssrc] = unifiedLine;++ if (typeof sources[ssrc].msid !== 'undefined') {+ // Assign the msid of the source to the m-line. Note+ // that it is not guaranteed that the source will have+ // msid. In particular "recvonly" sources don't have an+ // msid. Note that "recvonly" is a term only defined+ // for m-lines.+ unifiedLine.msid = sources[ssrc].msid;+ delete sources[ssrc].msid;+ }++ // We assign one SSRC per media line.+ unifiedLine.sources = {};+ unifiedLine.sources[ssrc] = sources[ssrc];+ unifiedLine.ssrcGroups = ssrc2group[ssrc];++ // Use the cached Unified Plan SDP (if it exists) to assign+ // SSRCs to mids.+ if (typeof cached !== 'undefined' &&+ typeof cached.media !== 'undefined' &&+ Array.isArray(cached.media)) {++ cached.media.forEach(function (m) {+ if (typeof m.sources === 'object') {+ Object.keys(m.sources).forEach(function (s) {+ if (s === ssrc) {+ unifiedLine.mid = m.mid;+ }+ });+ }+ });+ }++ if (typeof unifiedLine.mid === 'undefined') {++ // If this is an SSRC that we see for the first time+ // assign it a new mid. This is typically the case when+ // this method is called to transform a remote+ // description for the first time or when there is a+ // new SSRC in the remote description because a new+ // peer has joined the conference. Local SSRCs should+ // have already been added to the map in the toPlanB+ // method.+ //+ // Because FF generates answers in Unified Plan style,+ // we MUST already have a cached answer with all the+ // local SSRCs mapped to some m-line/mid.++ if (desc.type === 'answer') {+ throw new Error("An unmapped SSRC was found.");+ }++ unifiedLine.mid = [bLine.type, '-', ssrc].join('');+ }++ // Include the candidates in the 1st media line.+ unifiedLine.candidates = candidates;+ unifiedLine.iceUfrag = iceUfrag;+ unifiedLine.icePwd = icePwd;+ unifiedLine.fingerprint = fingerprint;+ unifiedLine.port = port;++ mid2ul[unifiedLine.mid] = unifiedLine;+ }+ });+ }+ });++ // Rebuild the media array in the right order and add the missing mLines+ // (missing from the Plan B SDP).+ session.media = [];+ mids = []; // reuse++ if (desc.type === 'answer') {++ // The media lines in the answer must match the media lines in the+ // offer. The order is important too. Here we assume that Firefox is the+ // answerer, so we merely have to use the reconstructed (unified) answer+ // to update the cached (unified) answer accordingly.+ //+ // In the general case, one would have to use the cached (unified) offer+ // to find the m-lines that are missing from the reconstructed answer,+ // potentially grabbing them from the cached (unified) answer. One has+ // to be carefull with this approach because inactive m-lines do not+ // always have an mid, making it tricky (impossible?) to find where+ // exactly and which m-lines are missing from the reconstructed answer.++ for (var i = 0; i < cached.media.length; i++) {+ var unifiedLine = cached.media[i];++ if (typeof mid2ul[unifiedLine.mid] === 'undefined') {++ // The mid isn't in the reconstructed (unified) answer.+ // This is either a (unified) m-line containing a remote+ // track only, or a (unified) m-line containing a remote+ // track and a local track that has been removed.+ // In either case, it MUST exist in the cached+ // (unified) answer.+ //+ // In case this is a removed local track, clean-up+ // the (unified) m-line and make sure it's 'recvonly' or+ // 'inactive'.++ delete unifiedLine.msid;+ delete unifiedLine.sources;+ delete unifiedLine.ssrcGroups;+ if (!unifiedLine.direction+ || unifiedLine.direction === 'sendrecv')+ unifiedLine.direction = 'recvonly';+ if (!unifiedLine.direction+ || unifiedLine.direction === 'sendonly')+ unifiedLine.direction = 'inactive';+ } else {+ // This is an (unified) m-line/channel that contains a local+ // track (sendrecv or sendonly channel) or it's a unified+ // recvonly m-line/channel. In either case, since we're+ // going from PlanB -> Unified Plan this m-line MUST+ // exist in the cached answer.+ }++ session.media.push(unifiedLine);++ if (typeof unifiedLine.mid === 'string') {+ // inactive lines don't/may not have an mid.+ mids.push(unifiedLine.mid);+ }+ }+ } else {++ // SDP offer/answer (and the JSEP spec) forbids removing an m-section+ // under any circumstances. If we are no longer interested in sending a+ // track, we just remove the msid and ssrc attributes and set it to+ // either a=recvonly (as the reofferer, we must use recvonly if the+ // other side was previously sending on the m-section, but we can also+ // leave the possibility open if it wasn't previously in use), or+ // a=inacive.++ if (typeof cached !== 'undefined' &&+ typeof cached.media !== 'undefined' &&+ Array.isArray(cached.media)) {+ cached.media.forEach(function(unifiedLine) {+ mids.push(unifiedLine.mid);+ if (typeof mid2ul[unifiedLine.mid] !== 'undefined') {+ session.media.push(mid2ul[unifiedLine.mid]);+ } else {+ delete unifiedLine.msid;+ delete unifiedLine.sources;+ delete unifiedLine.ssrcGroups;+ if (!unifiedLine.direction+ || unifiedLine.direction === 'sendrecv')+ unifiedLine.direction = 'recvonly';+ if (!unifiedLine.direction+ || unifiedLine.direction === 'sendonly')+ unifiedLine.direction = 'inactive';+ session.media.push(unifiedLine);+ }+ });+ }++ // Add all the remaining (new) m-lines of the transformed SDP.+ Object.keys(mid2ul).forEach(function(mid) {+ if (mids.indexOf(mid) === -1) {+ mids.push(mid);+ if (typeof mid2ul[mid].direction === 'recvonly') {+ // This is a remote recvonly channel. Add its SSRC to the+ // appropriate sendrecv or sendonly channel.+ // TODO(gp) what if we don't have sendrecv/sendonly channel?+ session.media.some(function (unifiedLine) {+ if ((unifiedLine.direction === 'sendrecv' ||+ unifiedLine.direction === 'sendonly') &&+ unifiedLine.type === mid2ul[mid].type) {++ // mid2ul[mid] shouldn't have any ssrc-groups+ Object.keys(mid2ul[mid].sources).forEach(function (ssrc) {+ unifiedLine.sources[ssrc] = mid2ul[mid].sources[ssrc];+ });++ return true;+ }+ });+ } else {+ session.media.push(mid2ul[mid]);+ }+ }+ });}- });- session.media = media; // link it up- return session;+ // We regenerate the BUNDLE group (since we regenerated the mids)+ session.groups.some(function(group) {+ if (group.type === 'BUNDLE') {+ group.mids = mids.join(' ');+ return true;+ }+ });++ // msid semantic+ session.msidSemantic = {+ semantic: 'WMS',+ token: '*'+ };++ var resStr = transform.write(session);++ // Cache the transformed SDP (Unified Plan) for later re-use in this+ // function.+ this.cache[desc.type] = resStr;++ return new RTCSessionDescription({+ type: desc.type,+ sdp: resStr+ });++ //#endregion};-var fmtpReducer = function (acc, expr) {- var s = expr.split('=');- if (s.length === 2) {- acc[s[0]] = toIntIfInt(s[1]);+},{"./array-equals":86,"./transform":89}],89:[function(require,module,exports){+var transform = require('sdp-transform');++exports.write = function(session, opts) {++ if (typeof session !== 'undefined' &&+ typeof session.media !== 'undefined' &&+ Array.isArray(session.media)) {++ session.media.forEach(function (mLine) {+ // expand sources to ssrcs+ if (typeof mLine.sources !== 'undefined' &&+ Object.keys(mLine.sources).length !== 0) {+ mLine.ssrcs = [];+ Object.keys(mLine.sources).forEach(function (ssrc) {+ var source = mLine.sources[ssrc];+ Object.keys(source).forEach(function (attribute) {+ mLine.ssrcs.push({+ id: ssrc,+ attribute: attribute,+ value: source[attribute]+ });+ });+ });+ delete mLine.sources;+ }++ // join ssrcs in ssrc groups+ if (typeof mLine.ssrcGroups !== 'undefined' &&+ Array.isArray(mLine.ssrcGroups)) {+ mLine.ssrcGroups.forEach(function (ssrcGroup) {+ if (typeof ssrcGroup.ssrcs !== 'undefined' &&+ Array.isArray(ssrcGroup.ssrcs)) {+ ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');+ }+ });+ }+ });}- return acc;-};--exports.parseFmtpConfig = function (str) {- return str.split(';').reduce(fmtpReducer, {});-};-exports.parsePayloads = function (str) {- return str.split(' ').map(Number);-};+ // join group mids+ if (typeof session !== 'undefined' &&+ typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {-exports.parseRemoteCandidates = function (str) {- var candidates = [];- var parts = str.split(' ').map(toIntIfInt);- for (var i = 0; i < parts.length; i += 3) {- candidates.push({- component: parts[i],- ip: parts[i + 1],- port: parts[i + 2]+ session.groups.forEach(function (g) {+ if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {+ g.mids = g.mids.join(' ');+ }});}- return candidates;-};--},{"./grammar":89}],92:[function(require,module,exports){-var grammar = require('./grammar');-// customized util.format - discards excess arguments and can void middle ones-var formatRegExp = /%[sdv%]/g;-var format = function (formatStr) {- var i = 1;- var args = arguments;- var len = args.length;- return formatStr.replace(formatRegExp, function (x) {- if (i >= len) {- return x; // missing argument- }- var arg = args[i];- i += 1;- switch (x) {- case '%%':- return '%';- case '%s':- return String(arg);- case '%d':- return Number(arg);- case '%v':- return '';- }- });- // NB: we discard excess arguments - they are typically undefined from makeLine+ return transform.write(session, opts);};-var makeLine = function (type, obj, location) {- var str = obj.format instanceof Function ?- (obj.format(obj.push ? location : location[obj.name])) :- obj.format;+exports.parse = function(sdp) {+ var session = transform.parse(sdp);- var args = [type + '=' + str];- if (obj.names) {- for (var i = 0; i < obj.names.length; i += 1) {- var n = obj.names[i];- if (obj.name) {- args.push(location[obj.name][n]);- }- else { // for mLine and push attributes- args.push(location[obj.names[i]]);- }- }- }- else {- args.push(location[obj.name]);- }- return format.apply(null, args);-};+ if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&+ Array.isArray(session.media)) {-// RFC specified order-// TODO: extend this with all the rest-var defaultOuterOrder = [- 'v', 'o', 's', 'i',- 'u', 'e', 'p', 'c',- 'b', 't', 'r', 'z', 'a'-];-var defaultInnerOrder = ['i', 'c', 'b', 'a'];+ session.media.forEach(function (mLine) {+ // group sources attributes by ssrc+ if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {+ mLine.sources = {};+ mLine.ssrcs.forEach(function (ssrc) {+ if (!mLine.sources[ssrc.id])+ mLine.sources[ssrc.id] = {};+ mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;+ });+ delete mLine.ssrcs;+ }-module.exports = function (session, opts) {- opts = opts || {};- // ensure certain properties exist- if (session.version == null) {- session.version = 0; // "v=0" must be there (only defined version atm)+ // split ssrcs in ssrc groups+ if (typeof mLine.ssrcGroups !== 'undefined' &&+ Array.isArray(mLine.ssrcGroups)) {+ mLine.ssrcGroups.forEach(function (ssrcGroup) {+ if (typeof ssrcGroup.ssrcs === 'string') {+ ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');+ }+ });+ }+ });}- if (session.name == null) {- session.name = " "; // "s= " must be there if no meaningful name set+ // split group mids+ if (typeof session !== 'undefined' &&+ typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {++ session.groups.forEach(function (g) {+ if (typeof g.mids === 'string') {+ g.mids = g.mids.split(' ');+ }+ });}- session.media.forEach(function (mLine) {- if (mLine.payloads == null) {- mLine.payloads = "";- }- });- var outerOrder = opts.outerOrder || defaultOuterOrder;- var innerOrder = opts.innerOrder || defaultInnerOrder;- var sdp = [];+ return session;+};- // loop through outerOrder for matching properties on session- outerOrder.forEach(function (type) {- grammar[type].forEach(function (obj) {- if (obj.name in session && session[obj.name] != null) {- sdp.push(makeLine(type, obj, session));++},{"sdp-transform":91}],90:[function(require,module,exports){+var grammar = module.exports = {+ v: [{+ name: 'version',+ reg: /^(\d*)$/+ }],+ o: [{ //o=- 20518 0 IN IP4 203.0.113.1+ // NB: sessionId will be a String in most cases because it is huge+ name: 'origin',+ reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,+ names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],+ format: "%s %s %d %s IP%d %s"+ }],+ // default parsing of these only (though some of these feel outdated)+ s: [{ name: 'name' }],+ i: [{ name: 'description' }],+ u: [{ name: 'uri' }],+ e: [{ name: 'email' }],+ p: [{ name: 'phone' }],+ z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..+ r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly+ //k: [{}], // outdated thing ignored+ t: [{ //t=0 0+ name: 'timing',+ reg: /^(\d*) (\d*)/,+ names: ['start', 'stop'],+ format: "%d %d"+ }],+ c: [{ //c=IN IP4 10.47.197.26+ name: 'connection',+ reg: /^IN IP(\d) (\S*)/,+ names: ['version', 'ip'],+ format: "IN IP%d %s"+ }],+ b: [{ //b=AS:4000+ push: 'bandwidth',+ reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,+ names: ['type', 'limit'],+ format: "%s:%s"+ }],+ m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31+ // NB: special - pushes to session+ // TODO: rtp/fmtp should be filtered by the payloads found here?+ reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,+ names: ['type', 'port', 'protocol', 'payloads'],+ format: "%s %d %s %s"+ }],+ a: [+ { //a=rtpmap:110 opus/48000/2+ push: 'rtp',+ reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,+ names: ['payload', 'codec', 'rate', 'encoding'],+ format: function (o) {+ return (o.encoding) ?+ "rtpmap:%d %s/%s/%s":+ "rtpmap:%d %s/%s";+ }+ },+ { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000+ push: 'fmtp',+ reg: /^fmtp:(\d*) (\S*)/,+ names: ['payload', 'config'],+ format: "fmtp:%d %s"+ },+ { //a=control:streamid=0+ name: 'control',+ reg: /^control:(.*)/,+ format: "control:%s"+ },+ { //a=rtcp:65179 IN IP4 193.84.77.194+ name: 'rtcp',+ reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,+ names: ['port', 'netType', 'ipVer', 'address'],+ format: function (o) {+ return (o.address != null) ?+ "rtcp:%d %s IP%d %s":+ "rtcp:%d";+ }+ },+ { //a=rtcp-fb:98 trr-int 100+ push: 'rtcpFbTrrInt',+ reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,+ names: ['payload', 'value'],+ format: "rtcp-fb:%d trr-int %d"+ },+ { //a=rtcp-fb:98 nack rpsi+ push: 'rtcpFb',+ reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,+ names: ['payload', 'type', 'subtype'],+ format: function (o) {+ return (o.subtype != null) ?+ "rtcp-fb:%s %s %s":+ "rtcp-fb:%s %s";+ }+ },+ { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset+ //a=extmap:1/recvonly URI-gps-string+ push: 'ext',+ reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,+ names: ['value', 'uri', 'config'], // value may include "/direction" suffix+ format: function (o) {+ return (o.config != null) ?+ "extmap:%s %s %s":+ "extmap:%s %s";}- else if (obj.push in session && session[obj.push] != null) {- session[obj.push].forEach(function (el) {- sdp.push(makeLine(type, obj, el));- });+ },+ {+ //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32+ push: 'crypto',+ reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,+ names: ['id', 'suite', 'config', 'sessionConfig'],+ format: function (o) {+ return (o.sessionConfig != null) ?+ "crypto:%d %s %s %s":+ "crypto:%d %s %s";}- });- });-- // then for each media line, follow the innerOrder- session.media.forEach(function (mLine) {- sdp.push(makeLine('m', grammar.m[0], mLine));-- innerOrder.forEach(function (type) {- grammar[type].forEach(function (obj) {- if (obj.name in mLine && mLine[obj.name] != null) {- sdp.push(makeLine(type, obj, mLine));- }- else if (obj.push in mLine && mLine[obj.push] != null) {- mLine[obj.push].forEach(function (el) {- sdp.push(makeLine(type, obj, el));- });+ },+ { //a=setup:actpass+ name: 'setup',+ reg: /^setup:(\w*)/,+ format: "setup:%s"+ },+ { //a=mid:1+ name: 'mid',+ reg: /^mid:([^\s]*)/,+ format: "mid:%s"+ },+ { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a+ name: 'msid',+ reg: /^msid:(.*)/,+ format: "msid:%s"+ },+ { //a=ptime:20+ name: 'ptime',+ reg: /^ptime:(\d*)/,+ format: "ptime:%d"+ },+ { //a=maxptime:60+ name: 'maxptime',+ reg: /^maxptime:(\d*)/,+ format: "maxptime:%d"+ },+ { //a=sendrecv+ name: 'direction',+ reg: /^(sendrecv|recvonly|sendonly|inactive)/+ },+ { //a=ice-lite+ name: 'icelite',+ reg: /^(ice-lite)/+ },+ { //a=ice-ufrag:F7gI+ name: 'iceUfrag',+ reg: /^ice-ufrag:(\S*)/,+ format: "ice-ufrag:%s"+ },+ { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g+ name: 'icePwd',+ reg: /^ice-pwd:(\S*)/,+ format: "ice-pwd:%s"+ },+ { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33+ name: 'fingerprint',+ reg: /^fingerprint:(\S*) (\S*)/,+ names: ['type', 'hash'],+ format: "fingerprint:%s %s"+ },+ {+ //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host+ //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0+ //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0+ push:'candidates',+ reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,+ names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],+ format: function (o) {+ var str = "candidate:%s %d %s %d %s %d typ %s";+ // NB: candidate has two optional chunks, so %void middle one if it's missing+ str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";+ if (o.generation != null) {+ str += " generation %d";}- });- });- });-- return sdp.join('\r\n') + '\r\n';-};--},{"./grammar":89}],93:[function(require,module,exports){-var MediaStreamType = {- VIDEO_TYPE: "Video",-- AUDIO_TYPE: "Audio"-};-module.exports = MediaStreamType;-},{}],94:[function(require,module,exports){-var RTCBrowserType = {- RTC_BROWSER_CHROME: "rtc_browser.chrome",-- RTC_BROWSER_FIREFOX: "rtc_browser.firefox"-};--module.exports = RTCBrowserType;-},{}],95:[function(require,module,exports){-var RTCEvents = {- LASTN_CHANGED: "rtc.lastn_changed",- DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",- LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",- SIMULCAST_LAYER_CHANGED: "rtc.simulcast_layer_changed",- SIMULCAST_LAYER_CHANGING: "rtc.simulcast_layer_changing",- SIMULCAST_START: "rtc.simlcast_start",- SIMULCAST_STOP: "rtc.simlcast_stop",- AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed"-};--module.exports = RTCEvents;-},{}],96:[function(require,module,exports){-var Resolutions = {- "1080": {- width: 1920,- height: 1080,- order: 7+ return str;+ }},- "fullhd": {- width: 1920,- height: 1080,- order: 7+ { //a=end-of-candidates (keep after the candidates line for readability)+ name: 'endOfCandidates',+ reg: /^(end-of-candidates)/},- "720": {- width: 1280,- height: 720,- order: 6+ { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...+ name: 'remoteCandidates',+ reg: /^remote-candidates:(.*)/,+ format: "remote-candidates:%s"},- "hd": {- width: 1280,- height: 720,- order: 6+ { //a=ice-options:google-ice+ name: 'iceOptions',+ reg: /^ice-options:(\S*)/,+ format: "ice-options:%s"},- "960": {- width: 960,- height: 720,- order: 5+ { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1+ push: "ssrcs",+ reg: /^ssrc:(\d*) ([\w_]*):(.*)/,+ names: ['id', 'attribute', 'value'],+ format: "ssrc:%d %s:%s"},- "640": {- width: 640,- height: 480,- order: 4+ { //a=ssrc-group:FEC 1 2+ push: "ssrcGroups",+ reg: /^ssrc-group:(\w*) (.*)/,+ names: ['semantics', 'ssrcs'],+ format: "ssrc-group:%s %s"},- "vga": {- width: 640,- height: 480,- order: 4+ { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV+ name: "msidSemantic",+ reg: /^msid-semantic:\s?(\w*) (\S*)/,+ names: ['semantic', 'token'],+ format: "msid-semantic: %s %s" // space after ":" is not accidental},- "360": {- width: 640,- height: 360,- order: 3+ { //a=group:BUNDLE audio video+ push: 'groups',+ reg: /^group:(\w*) (.*)/,+ names: ['type', 'mids'],+ format: "group:%s %s"},- "320": {- width: 320,- height: 240,- order: 2+ { //a=rtcp-mux+ name: 'rtcpMux',+ reg: /^(rtcp-mux)/},- "180": {- width: 320,- height: 180,- order: 1- }-};-module.exports = Resolutions;-},{}],97:[function(require,module,exports){-var StreamEventTypes = {- EVENT_TYPE_LOCAL_CREATED: "stream.local_created",-- EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",-- EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",-- EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",-- EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended",-- EVENT_TYPE_REMOTE_CHANGED: "stream.changed"-};--module.exports = StreamEventTypes;-},{}],98:[function(require,module,exports){-var UIEvents = {- NICKNAME_CHANGED: "UI.nickname_changed",- SELECTED_ENDPOINT: "UI.selected_endpoint",- PINNED_ENDPOINT: "UI.pinned_endpoint"-};-module.exports = UIEvents;-},{}],99:[function(require,module,exports){-var AuthenticationEvents = {- /**- * Event callback arguments:- * function(authenticationEnabled, userIdentity)- * authenticationEnabled - indicates whether authentication has been enabled- * in this session- * userIdentity - if user has been logged in then it contains user name. If- * contains 'null' or 'undefined' then user is not logged in.- */- IDENTITY_UPDATED: "authentication.identity_updated"-};-module.exports = AuthenticationEvents;--},{}],100:[function(require,module,exports){-var CQEvents = {- LOCALSTATS_UPDATED: "cq.localstats_updated",- REMOTESTATS_UPDATED: "cq.remotestats_updated",- STOP: "cq.stop"+ { //a=rtcp-rsize+ name: 'rtcpRsize',+ reg: /^(rtcp-rsize)/+ },+ { // any a= that we don't understand is kepts verbatim on media.invalid+ push: 'invalid',+ names: ["value"]+ }+ ]};-module.exports = CQEvents;-},{}],101:[function(require,module,exports){-var DesktopSharingEventTypes = {- INIT: "ds.init",+// set sensible defaults to avoid polluting the grammar with boring details+Object.keys(grammar).forEach(function (key) {+ var objs = grammar[key];+ objs.forEach(function (obj) {+ if (!obj.reg) {+ obj.reg = /(.*)/;+ }+ if (!obj.format) {+ obj.format = "%s";+ }+ });+});- SWITCHING_DONE: "ds.switching_done",+},{}],91:[function(require,module,exports){+var parser = require('./parser');+var writer = require('./writer');- NEW_STREAM_CREATED: "ds.new_stream_created"-};+exports.write = writer;+exports.parse = parser.parse;+exports.parseFmtpConfig = parser.parseFmtpConfig;+exports.parsePayloads = parser.parsePayloads;+exports.parseRemoteCandidates = parser.parseRemoteCandidates;-module.exports = DesktopSharingEventTypes;-},{}],102:[function(require,module,exports){-var Events = {- DTMF_SUPPORT_CHANGED: "members.dtmf_support_changed"+},{"./parser":92,"./writer":93}],92:[function(require,module,exports){+var toIntIfInt = function (v) {+ return String(Number(v)) === v ? Number(v) : v;};-module.exports = Events;--},{}],103:[function(require,module,exports){-module.exports = {- getLanguages : function () {- var languages = [];- for(var lang in this)- {- if(typeof this[lang] === "string")- languages.push(this[lang]);- }- return languages;- },- EN: "en",- BG: "bg",- DE: "de",- TR: "tr"-}-},{}],104:[function(require,module,exports){-var XMPPEvents = {- CONNECTION_FAILED: "xmpp.connection.failed",- CONFERENCE_CREATED: "xmpp.conferenceCreated.jingle",- CALL_TERMINATED: "xmpp.callterminated.jingle",- CALL_INCOMING: "xmpp.callincoming.jingle",- DISPOSE_CONFERENCE: "xmpp.dispose_conference",- GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",- KICKED: "xmpp.kicked",- BRIDGE_DOWN: "xmpp.bridge_down",- USER_ID_CHANGED: "xmpp.user_id_changed",- STREAMS_CHANGED: "xmpp.streams_changed",- // We joined the MUC- MUC_JOINED: "xmpp.muc_joined",- // A member joined the MUC- MUC_MEMBER_JOINED: "xmpp.muc_member_joined",- // A member left the MUC- MUC_MEMBER_LEFT: "xmpp.muc_member_left",- MUC_ROLE_CHANGED: "xmpp.muc_role_changed",- MUC_DESTROYED: "xmpp.muc_destroyed",- DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",- REMOTE_STATS: "xmpp.remote_stats",- LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",- PRESENCE_STATUS: "xmpp.presence_status",- RESERVATION_ERROR: "xmpp.room_reservation_error",- SUBJECT_CHANGED: "xmpp.subject_changed",- MESSAGE_RECEIVED: "xmpp.message_received",- SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",- PASSWORD_REQUIRED: "xmpp.password_required",- AUTHENTICATION_REQUIRED: "xmpp.authentication_required",- CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",- ETHERPAD: "xmpp.etherpad",- DEVICE_AVAILABLE: "xmpp.device_available",- START_MUTED: "xmpp.start_muted"+var attachProperties = function (match, location, names, rawName) {+ if (rawName && !names) {+ location[rawName] = toIntIfInt(match[1]);+ }+ else {+ for (var i = 0; i < names.length; i += 1) {+ if (match[i+1] != null) {+ location[names[i]] = toIntIfInt(match[i+1]);+ }+ }+ }};-module.exports = XMPPEvents;-},{}],105:[function(require,module,exports){-// Copyright Joyent, Inc. and other Node contributors.-//-// Permission is hereby granted, free of charge, to any person obtaining a-// copy of this software and associated documentation files (the-// "Software"), to deal in the Software without restriction, including-// without limitation the rights to use, copy, modify, merge, publish,-// distribute, sublicense, and/or sell copies of the Software, and to permit-// persons to whom the Software is furnished to do so, subject to the-// following conditions:-//-// The above copyright notice and this permission notice shall be included-// in all copies or substantial portions of the Software.-//-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE-// USE OR OTHER DEALINGS IN THE SOFTWARE.--function EventEmitter() {- this._events = this._events || {};- this._maxListeners = this._maxListeners || undefined;-}-module.exports = EventEmitter;--// Backwards-compat with node 0.10.x-EventEmitter.EventEmitter = EventEmitter;-EventEmitter.prototype._events = undefined;-EventEmitter.prototype._maxListeners = undefined;+var parseReg = function (obj, location, content) {+ var needsBlank = obj.name && obj.names;+ if (obj.push && !location[obj.push]) {+ location[obj.push] = [];+ }+ else if (needsBlank && !location[obj.name]) {+ location[obj.name] = {};+ }+ var keyLocation = obj.push ?+ {} : // blank object that will be pushed+ needsBlank ? location[obj.name] : location; // otherwise, named location or root-// By default EventEmitters will print a warning if more than 10 listeners are-// added to it. This is a useful default which helps finding memory leaks.-EventEmitter.defaultMaxListeners = 10;+ attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);-// Obviously not all Emitters should be limited to 10. This function allows-// that to be increased. Set to zero for unlimited.-EventEmitter.prototype.setMaxListeners = function(n) {- if (!isNumber(n) || n < 0 || isNaN(n))- throw TypeError('n must be a positive number');- this._maxListeners = n;- return this;+ if (obj.push) {+ location[obj.push].push(keyLocation);+ }};-EventEmitter.prototype.emit = function(type) {- var er, handler, len, args, i, listeners;+var grammar = require('./grammar');+var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);- if (!this._events)- this._events = {};+exports.parse = function (sdp) {+ var session = {}+ , media = []+ , location = session; // points at where properties go under (one of the above)- // If there is no 'error' event listener then throw.- if (type === 'error') {- if (!this._events.error ||- (isObject(this._events.error) && !this._events.error.length)) {- er = arguments[1];- if (er instanceof Error) {- throw er; // Unhandled 'error' event- }- throw TypeError('Uncaught, unspecified "error" event.');+ // parse lines we understand+ sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {+ var type = l[0];+ var content = l.slice(2);+ if (type === 'm') {+ media.push({rtp: [], fmtp: []});+ location = media[media.length-1]; // point at latest media line}- }- handler = this._events[type];-- if (isUndefined(handler))- return false;-- if (isFunction(handler)) {- switch (arguments.length) {- // fast cases- case 1:- handler.call(this);- break;- case 2:- handler.call(this, arguments[1]);- break;- case 3:- handler.call(this, arguments[1], arguments[2]);- break;- // slower- default:- len = arguments.length;- args = new Array(len - 1);- for (i = 1; i < len; i++)- args[i - 1] = arguments[i];- handler.apply(this, args);+ for (var j = 0; j < (grammar[type] || []).length; j += 1) {+ var obj = grammar[type][j];+ if (obj.reg.test(content)) {+ return parseReg(obj, location, content);+ }}- } else if (isObject(handler)) {- len = arguments.length;- args = new Array(len - 1);- for (i = 1; i < len; i++)- args[i - 1] = arguments[i];-- listeners = handler.slice();- len = listeners.length;- for (i = 0; i < len; i++)- listeners[i].apply(this, args);- }+ });- return true;+ session.media = media; // link it up+ return session;};-EventEmitter.prototype.addListener = function(type, listener) {- var m;+var fmtpReducer = function (acc, expr) {+ var s = expr.split('=');+ if (s.length === 2) {+ acc[s[0]] = toIntIfInt(s[1]);+ }+ return acc;+};- if (!isFunction(listener))- throw TypeError('listener must be a function');+exports.parseFmtpConfig = function (str) {+ return str.split(';').reduce(fmtpReducer, {});+};- if (!this._events)- this._events = {};+exports.parsePayloads = function (str) {+ return str.split(' ').map(Number);+};- // To avoid recursion in the case that type === "newListener"! Before- // adding it to the listeners, first emit "newListener".- if (this._events.newListener)- this.emit('newListener', type,- isFunction(listener.listener) ?- listener.listener : listener);+exports.parseRemoteCandidates = function (str) {+ var candidates = [];+ var parts = str.split(' ').map(toIntIfInt);+ for (var i = 0; i < parts.length; i += 3) {+ candidates.push({+ component: parts[i],+ ip: parts[i + 1],+ port: parts[i + 2]+ });+ }+ return candidates;+};- if (!this._events[type])- // Optimize the case of one listener. Don't need the extra array object.- this._events[type] = listener;- else if (isObject(this._events[type]))- // If we've already got an array, just append.- this._events[type].push(listener);- else- // Adding the second element, need to change to array.- this._events[type] = [this._events[type], listener];+},{"./grammar":90}],93:[function(require,module,exports){+var grammar = require('./grammar');- // Check for listener leak- if (isObject(this._events[type]) && !this._events[type].warned) {- var m;- if (!isUndefined(this._maxListeners)) {- m = this._maxListeners;- } else {- m = EventEmitter.defaultMaxListeners;+// customized util.format - discards excess arguments and can void middle ones+var formatRegExp = /%[sdv%]/g;+var format = function (formatStr) {+ var i = 1;+ var args = arguments;+ var len = args.length;+ return formatStr.replace(formatRegExp, function (x) {+ if (i >= len) {+ return x; // missing argument+ }+ var arg = args[i];+ i += 1;+ switch (x) {+ case '%%':+ return '%';+ case '%s':+ return String(arg);+ case '%d':+ return Number(arg);+ case '%v':+ return '';}+ });+ // NB: we discard excess arguments - they are typically undefined from makeLine+};- if (m && m > 0 && this._events[type].length > m) {- this._events[type].warned = true;- console.error('(node) warning: possible EventEmitter memory ' +- 'leak detected. %d listeners added. ' +- 'Use emitter.setMaxListeners() to increase limit.',- this._events[type].length);- if (typeof console.trace === 'function') {- // not supported in IE 10- console.trace();+var makeLine = function (type, obj, location) {+ var str = obj.format instanceof Function ?+ (obj.format(obj.push ? location : location[obj.name])) :+ obj.format;++ var args = [type + '=' + str];+ if (obj.names) {+ for (var i = 0; i < obj.names.length; i += 1) {+ var n = obj.names[i];+ if (obj.name) {+ args.push(location[obj.name][n]);+ }+ else { // for mLine and push attributes+ args.push(location[obj.names[i]]);}}}-- return this;+ else {+ args.push(location[obj.name]);+ }+ return format.apply(null, args);};-EventEmitter.prototype.on = EventEmitter.prototype.addListener;+// RFC specified order+// TODO: extend this with all the rest+var defaultOuterOrder = [+ 'v', 'o', 's', 'i',+ 'u', 'e', 'p', 'c',+ 'b', 't', 'r', 'z', 'a'+];+var defaultInnerOrder = ['i', 'c', 'b', 'a'];-EventEmitter.prototype.once = function(type, listener) {- if (!isFunction(listener))- throw TypeError('listener must be a function');- var fired = false;+module.exports = function (session, opts) {+ opts = opts || {};+ // ensure certain properties exist+ if (session.version == null) {+ session.version = 0; // "v=0" must be there (only defined version atm)+ }+ if (session.name == null) {+ session.name = " "; // "s= " must be there if no meaningful name set+ }+ session.media.forEach(function (mLine) {+ if (mLine.payloads == null) {+ mLine.payloads = "";+ }+ });- function g() {- this.removeListener(type, g);+ var outerOrder = opts.outerOrder || defaultOuterOrder;+ var innerOrder = opts.innerOrder || defaultInnerOrder;+ var sdp = [];- if (!fired) {- fired = true;- listener.apply(this, arguments);- }- }+ // loop through outerOrder for matching properties on session+ outerOrder.forEach(function (type) {+ grammar[type].forEach(function (obj) {+ if (obj.name in session && session[obj.name] != null) {+ sdp.push(makeLine(type, obj, session));+ }+ else if (obj.push in session && session[obj.push] != null) {+ session[obj.push].forEach(function (el) {+ sdp.push(makeLine(type, obj, el));+ });+ }+ });+ });- g.listener = listener;- this.on(type, g);+ // then for each media line, follow the innerOrder+ session.media.forEach(function (mLine) {+ sdp.push(makeLine('m', grammar.m[0], mLine));- return this;-};+ innerOrder.forEach(function (type) {+ grammar[type].forEach(function (obj) {+ if (obj.name in mLine && mLine[obj.name] != null) {+ sdp.push(makeLine(type, obj, mLine));+ }+ else if (obj.push in mLine && mLine[obj.push] != null) {+ mLine[obj.push].forEach(function (el) {+ sdp.push(makeLine(type, obj, el));+ });+ }+ });+ });+ });-// emits a 'removeListener' event iff the listener was removed-EventEmitter.prototype.removeListener = function(type, listener) {- var list, position, length, i;+ return sdp.join('\r\n') + '\r\n';+};- if (!isFunction(listener))- throw TypeError('listener must be a function');+},{"./grammar":90}],94:[function(require,module,exports){+var MediaStreamType = {+ VIDEO_TYPE: "Video",- if (!this._events || !this._events[type])- return this;+ AUDIO_TYPE: "Audio"+};+module.exports = MediaStreamType;+},{}],95:[function(require,module,exports){+var RTCBrowserType = {+ RTC_BROWSER_CHROME: "rtc_browser.chrome",- list = this._events[type];- length = list.length;- position = -1;+ RTC_BROWSER_FIREFOX: "rtc_browser.firefox"+};- if (list === listener ||- (isFunction(list.listener) && list.listener === listener)) {- delete this._events[type];- if (this._events.removeListener)- this.emit('removeListener', type, listener);+module.exports = RTCBrowserType;+},{}],96:[function(require,module,exports){+var RTCEvents = {+ LASTN_CHANGED: "rtc.lastn_changed",+ DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",+ LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",+ SIMULCAST_LAYER_CHANGED: "rtc.simulcast_layer_changed",+ SIMULCAST_LAYER_CHANGING: "rtc.simulcast_layer_changing",+ SIMULCAST_START: "rtc.simlcast_start",+ SIMULCAST_STOP: "rtc.simlcast_stop",+ AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed"+};- } else if (isObject(list)) {- for (i = length; i-- > 0;) {- if (list[i] === listener ||- (list[i].listener && list[i].listener === listener)) {- position = i;- break;- }+module.exports = RTCEvents;+},{}],97:[function(require,module,exports){+var Resolutions = {+ "1080": {+ width: 1920,+ height: 1080,+ order: 7+ },+ "fullhd": {+ width: 1920,+ height: 1080,+ order: 7+ },+ "720": {+ width: 1280,+ height: 720,+ order: 6+ },+ "hd": {+ width: 1280,+ height: 720,+ order: 6+ },+ "960": {+ width: 960,+ height: 720,+ order: 5+ },+ "640": {+ width: 640,+ height: 480,+ order: 4+ },+ "vga": {+ width: 640,+ height: 480,+ order: 4+ },+ "360": {+ width: 640,+ height: 360,+ order: 3+ },+ "320": {+ width: 320,+ height: 240,+ order: 2+ },+ "180": {+ width: 320,+ height: 180,+ order: 1}+};+module.exports = Resolutions;+},{}],98:[function(require,module,exports){+var StreamEventTypes = {+ EVENT_TYPE_LOCAL_CREATED: "stream.local_created",++ EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",++ EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",- if (position < 0)- return this;+ EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",- if (list.length === 1) {- list.length = 0;- delete this._events[type];- } else {- list.splice(position, 1);- }+ EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended",- if (this._events.removeListener)- this.emit('removeListener', type, listener);- }+ EVENT_TYPE_REMOTE_CHANGED: "stream.changed"+};- return this;+module.exports = StreamEventTypes;+},{}],99:[function(require,module,exports){+var UIEvents = {+ NICKNAME_CHANGED: "UI.nickname_changed",+ SELECTED_ENDPOINT: "UI.selected_endpoint",+ PINNED_ENDPOINT: "UI.pinned_endpoint"+};+module.exports = UIEvents;+},{}],100:[function(require,module,exports){+var AuthenticationEvents = {+ /**+ * Event callback arguments:+ * function(authenticationEnabled, userIdentity)+ * authenticationEnabled - indicates whether authentication has been enabled+ * in this session+ * userIdentity - if user has been logged in then it contains user name. If+ * contains 'null' or 'undefined' then user is not logged in.+ */+ IDENTITY_UPDATED: "authentication.identity_updated"};+module.exports = AuthenticationEvents;-EventEmitter.prototype.removeAllListeners = function(type) {- var key, listeners;+},{}],101:[function(require,module,exports){+var CQEvents = {+ LOCALSTATS_UPDATED: "cq.localstats_updated",+ REMOTESTATS_UPDATED: "cq.remotestats_updated",+ STOP: "cq.stop"+};- if (!this._events)- return this;+module.exports = CQEvents;+},{}],102:[function(require,module,exports){+var DesktopSharingEventTypes = {+ INIT: "ds.init",- // not listening for removeListener, no need to emit- if (!this._events.removeListener) {- if (arguments.length === 0)- this._events = {};- else if (this._events[type])- delete this._events[type];- return this;- }+ SWITCHING_DONE: "ds.switching_done",- // emit removeListener for all listeners on all events- if (arguments.length === 0) {- for (key in this._events) {- if (key === 'removeListener') continue;- this.removeAllListeners(key);- }- this.removeAllListeners('removeListener');- this._events = {};- return this;- }+ NEW_STREAM_CREATED: "ds.new_stream_created"+};- listeners = this._events[type];+module.exports = DesktopSharingEventTypes;+},{}],103:[function(require,module,exports){+var Events = {+ DTMF_SUPPORT_CHANGED: "members.dtmf_support_changed"+};- if (isFunction(listeners)) {- this.removeListener(type, listeners);- } else {- // LIFO order- while (listeners.length)- this.removeListener(type, listeners[listeners.length - 1]);- }- delete this._events[type];+module.exports = Events;- return this;+},{}],104:[function(require,module,exports){+module.exports = {+ getLanguages : function () {+ var languages = [];+ for(var lang in this)+ {+ if(typeof this[lang] === "string")+ languages.push(this[lang]);+ }+ return languages;+ },+ EN: "en",+ BG: "bg",+ DE: "de",+ TR: "tr"+}+},{}],105:[function(require,module,exports){+var XMPPEvents = {+ CONNECTION_FAILED: "xmpp.connection.failed",+ CONFERENCE_CREATED: "xmpp.conferenceCreated.jingle",+ CALL_TERMINATED: "xmpp.callterminated.jingle",+ CALL_INCOMING: "xmpp.callincoming.jingle",+ DISPOSE_CONFERENCE: "xmpp.dispose_conference",+ GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",+ KICKED: "xmpp.kicked",+ BRIDGE_DOWN: "xmpp.bridge_down",+ USER_ID_CHANGED: "xmpp.user_id_changed",+ STREAMS_CHANGED: "xmpp.streams_changed",+ // We joined the MUC+ MUC_JOINED: "xmpp.muc_joined",+ // A member joined the MUC+ MUC_MEMBER_JOINED: "xmpp.muc_member_joined",+ // A member left the MUC+ MUC_MEMBER_LEFT: "xmpp.muc_member_left",+ MUC_ROLE_CHANGED: "xmpp.muc_role_changed",+ MUC_DESTROYED: "xmpp.muc_destroyed",+ DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",+ REMOTE_STATS: "xmpp.remote_stats",+ LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",+ PRESENCE_STATUS: "xmpp.presence_status",+ RESERVATION_ERROR: "xmpp.room_reservation_error",+ SUBJECT_CHANGED: "xmpp.subject_changed",+ MESSAGE_RECEIVED: "xmpp.message_received",+ SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",+ PASSWORD_REQUIRED: "xmpp.password_required",+ AUTHENTICATION_REQUIRED: "xmpp.authentication_required",+ CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",+ ETHERPAD: "xmpp.etherpad",+ DEVICE_AVAILABLE: "xmpp.device_available",+ START_MUTED: "xmpp.start_muted"};+module.exports = XMPPEvents;+},{}],106:[function(require,module,exports){+/* jshint -W117 */+/* application specific logic */-EventEmitter.prototype.listeners = function(type) {- var ret;- if (!this._events || !this._events[type])- ret = [];- else if (isFunction(this._events[type]))- ret = [this._events[type]];- else- ret = this._events[type].slice();- return ret;+var APP =+{+ init: function () {+ this.UI = require("./modules/UI/UI");+ this.API = require("./modules/API/API");+ this.connectionquality = require("./modules/connectionquality/connectionquality");+ this.statistics = require("./modules/statistics/statistics");+ this.RTC = require("./modules/RTC/RTC");+ this.simulcast = require("./modules/simulcast/simulcast");+ this.desktopsharing = require("./modules/desktopsharing/desktopsharing");+ this.xmpp = require("./modules/xmpp/xmpp");+ this.keyboardshortcut = require("./modules/keyboardshortcut/keyboardshortcut");+ this.translation = require("./modules/translation/translation");+ this.settings = require("./modules/settings/Settings");+ this.DTMF = require("./modules/DTMF/DTMF");+ this.members = require("./modules/members/MemberList");+ }};-EventEmitter.listenerCount = function(emitter, type) {- var ret;- if (!emitter._events || !emitter._events[type])- ret = 0;- else if (isFunction(emitter._events[type]))- ret = 1;- else- ret = emitter._events[type].length;- return ret;-};+function init() {-function isFunction(arg) {- return typeof arg === 'function';-}+ APP.RTC.start();+ APP.xmpp.start();+ APP.statistics.start();+ APP.connectionquality.init();-function isNumber(arg) {- return typeof arg === 'number';-}+ // Set default desktop sharing method+ APP.desktopsharing.init();-function isObject(arg) {- return typeof arg === 'object' && arg !== null;+ APP.keyboardshortcut.init();+ APP.members.start();}-function isUndefined(arg) {- return arg === void 0;-}-},{}],106:[function(require,module,exports){-// shim for using process in browser+$(document).ready(function () {-var process = module.exports = {};-var queue = [];-var draining = false;+ APP.init();-function drainQueue() {- if (draining) {- return;- }- draining = true;- var currentQueue;- var len = queue.length;- while(len) {- currentQueue = queue;- queue = [];- var i = -1;- while (++i < len) {- currentQueue[i]();- }- len = queue.length;- }- draining = false;-}-process.nextTick = function (fun) {- queue.push(fun);- if (!draining) {- setTimeout(drainQueue, 0);- }-};+ APP.translation.init();-process.title = 'browser';-process.browser = true;-process.env = {};-process.argv = [];-process.version = ''; // empty string to avoid regexp issues+ if(APP.API.isEnabled())+ APP.API.init();-function noop() {}+ APP.UI.start(init);-process.on = noop;-process.addListener = noop;-process.once = noop;-process.off = noop;-process.removeListener = noop;-process.removeAllListeners = noop;-process.emit = noop;+});-process.binding = function (name) {- throw new Error('process.binding is not supported');-};+$(window).bind('beforeunload', function () {+ if(APP.API.isEnabled())+ APP.API.dispose();+});++module.exports = APP;-// TODO(shtylman)-process.cwd = function () { return '/' };-process.chdir = function (dir) {- throw new Error('process.chdir is not supported');-};-process.umask = function() { return 0; };-},{}]},{},[1])(1)+},{"./modules/API/API":1,"./modules/DTMF/DTMF":2,"./modules/RTC/RTC":6,"./modules/UI/UI":8,"./modules/connectionquality/connectionquality":35,"./modules/desktopsharing/desktopsharing":36,"./modules/keyboardshortcut/keyboardshortcut":37,"./modules/members/MemberList":38,"./modules/settings/Settings":39,"./modules/simulcast/simulcast":44,"./modules/statistics/statistics":47,"./modules/translation/translation":48,"./modules/xmpp/xmpp":62}]},{},[106])(106)});\ No newline at end of file