text
stringlengths
2
1.05M
//# sourceMappingURL=EmployeeUpdate.dto.js.map
var assert = require('assert') var bufferutils = require('./bufferutils') var crypto = require('crypto') var enforceType = require('./types') var networks = require('./networks') var Address = require('./address') var HDNode = require('./hdnode') var TransactionBuilder = require('./transaction_builder') var Script = require('./script') function Wallet(seed, network) { console.warn('Wallet is deprecated and will be removed in 2.0.0, see #296') seed = seed || crypto.randomBytes(32) network = network || networks.bitcoin // Stored in a closure to make accidental serialization less likely var masterKey = HDNode.fromSeedBuffer(seed, network) // HD first-level child derivation method should be hardened // See https://bitcointalk.org/index.php?topic=405179.msg4415254#msg4415254 var accountZero = masterKey.deriveHardened(0) var externalAccount = accountZero.derive(0) var internalAccount = accountZero.derive(1) this.addresses = [] this.changeAddresses = [] this.network = network this.unspents = [] // FIXME: remove in 2.0.0 this.unspentMap = {} // FIXME: remove in 2.0.0 var me = this this.newMasterKey = function(seed) { console.warn('newMasterKey is deprecated, please make a new Wallet instance instead') seed = seed || crypto.randomBytes(32) masterKey = HDNode.fromSeedBuffer(seed, network) accountZero = masterKey.deriveHardened(0) externalAccount = accountZero.derive(0) internalAccount = accountZero.derive(1) me.addresses = [] me.changeAddresses = [] me.unspents = [] me.unspentMap = {} } this.getMasterKey = function() { return masterKey } this.getAccountZero = function() { return accountZero } this.getExternalAccount = function() { return externalAccount } this.getInternalAccount = function() { return internalAccount } } Wallet.prototype.createTransaction = function(to, value, options) { // FIXME: remove in 2.0.0 if (typeof options !== 'object') { if (options !== undefined) { console.warn('Non options object parameters are deprecated, use options object instead') options = { fixedFee: arguments[2], changeAddress: arguments[3] } } } options = options || {} assert(value > this.network.dustThreshold, value + ' must be above dust threshold (' + this.network.dustThreshold + ' Satoshis)') var changeAddress = options.changeAddress var fixedFee = options.fixedFee var minConf = options.minConf === undefined ? 0 : options.minConf // FIXME: change minConf:1 by default in 2.0.0 // filter by minConf, then pending and sort by descending value var unspents = this.unspents.filter(function(unspent) { return unspent.confirmations >= minConf }).filter(function(unspent) { return !unspent.pending }).sort(function(o1, o2) { return o2.value - o1.value }) var accum = 0 var addresses = [] var subTotal = value var txb = new TransactionBuilder() txb.addOutput(to, value) for (var i = 0; i < unspents.length; ++i) { var unspent = unspents[i] addresses.push(unspent.address) txb.addInput(unspent.txHash, unspent.index) var fee = fixedFee === undefined ? estimatePaddedFee(txb.buildIncomplete(), this.network) : fixedFee accum += unspent.value subTotal = value + fee if (accum >= subTotal) { var change = accum - subTotal if (change > this.network.dustThreshold) { txb.addOutput(changeAddress || this.getChangeAddress(), change) } break } } assert(accum >= subTotal, 'Not enough funds (incl. fee): ' + accum + ' < ' + subTotal) return this.signWith(txb, addresses).build() } // FIXME: remove in 2.0.0 Wallet.prototype.processPendingTx = function(tx){ this.__processTx(tx, true) } // FIXME: remove in 2.0.0 Wallet.prototype.processConfirmedTx = function(tx){ this.__processTx(tx, false) } // FIXME: remove in 2.0.0 Wallet.prototype.__processTx = function(tx, isPending) { console.warn('processTransaction is considered harmful, see issue #260 for more information') var txId = tx.getId() var txHash = tx.getHash() tx.outs.forEach(function(txOut, i) { var address try { address = Address.fromOutputScript(txOut.script, this.network).toString() } catch(e) { if (!(e.message.match(/has no matching Address/))) throw e } var myAddresses = this.addresses.concat(this.changeAddresses) if (myAddresses.indexOf(address) > -1) { var lookup = txId + ':' + i if (lookup in this.unspentMap) return // its unique, add it var unspent = { address: address, confirmations: 0, // no way to determine this without more information index: i, txHash: txHash, txId: txId, value: txOut.value, pending: isPending } this.unspentMap[lookup] = unspent this.unspents.push(unspent) } }, this) tx.ins.forEach(function(txIn, i) { // copy and convert to big-endian hex var txInId = bufferutils.reverse(txIn.hash).toString('hex') var lookup = txInId + ':' + txIn.index if (!(lookup in this.unspentMap)) return var unspent = this.unspentMap[lookup] if (isPending) { unspent.pending = true unspent.spent = true } else { delete this.unspentMap[lookup] this.unspents = this.unspents.filter(function(unspent2) { return unspent !== unspent2 }) } }, this) } Wallet.prototype.generateAddress = function() { var k = this.addresses.length var address = this.getExternalAccount().derive(k).getAddress() this.addresses.push(address.toString()) return this.getReceiveAddress() } Wallet.prototype.generateChangeAddress = function() { var k = this.changeAddresses.length var address = this.getInternalAccount().derive(k).getAddress() this.changeAddresses.push(address.toString()) return this.getChangeAddress() } Wallet.prototype.getAddress = function() { if (this.addresses.length === 0) { this.generateAddress() } return this.addresses[this.addresses.length - 1] } Wallet.prototype.getBalance = function(minConf) { minConf = minConf || 0 return this.unspents.filter(function(unspent) { return unspent.confirmations >= minConf // FIXME: remove spent filter in 2.0.0 }).filter(function(unspent) { return !unspent.spent }).reduce(function(accum, unspent) { return accum + unspent.value }, 0) } Wallet.prototype.getChangeAddress = function() { if (this.changeAddresses.length === 0) { this.generateChangeAddress() } return this.changeAddresses[this.changeAddresses.length - 1] } Wallet.prototype.getInternalPrivateKey = function(index) { return this.getInternalAccount().derive(index).privKey } Wallet.prototype.getPrivateKey = function(index) { return this.getExternalAccount().derive(index).privKey } Wallet.prototype.getPrivateKeyForAddress = function(address) { var index if ((index = this.addresses.indexOf(address)) > -1) { return this.getPrivateKey(index) } if ((index = this.changeAddresses.indexOf(address)) > -1) { return this.getInternalPrivateKey(index) } assert(false, 'Unknown address. Make sure the address is from the keychain and has been generated') } Wallet.prototype.getUnspentOutputs = function(minConf) { minConf = minConf || 0 return this.unspents.filter(function(unspent) { return unspent.confirmations >= minConf // FIXME: remove spent filter in 2.0.0 }).filter(function(unspent) { return !unspent.spent }).map(function(unspent) { return { address: unspent.address, confirmations: unspent.confirmations, index: unspent.index, txId: unspent.txId, value: unspent.value, // FIXME: remove in 2.0.0 hash: unspent.txId, pending: unspent.pending } }) } Wallet.prototype.setUnspentOutputs = function(unspents) { this.unspentMap = {} this.unspents = unspents.map(function(unspent) { // FIXME: remove unspent.hash in 2.0.0 var txId = unspent.txId || unspent.hash var index = unspent.index // FIXME: remove in 2.0.0 if (unspent.hash !== undefined) { console.warn('unspent.hash is deprecated, use unspent.txId instead') } // FIXME: remove in 2.0.0 if (index === undefined) { console.warn('unspent.outputIndex is deprecated, use unspent.index instead') index = unspent.outputIndex } enforceType('String', txId) enforceType('Number', index) enforceType('Number', unspent.value) assert.equal(txId.length, 64, 'Expected valid txId, got ' + txId) assert.doesNotThrow(function() { Address.fromBase58Check(unspent.address) }, 'Expected Base58 Address, got ' + unspent.address) assert(isFinite(index), 'Expected finite index, got ' + index) // FIXME: remove branch in 2.0.0 if (unspent.confirmations !== undefined) { enforceType('Number', unspent.confirmations) } var txHash = bufferutils.reverse(new Buffer(txId, 'hex')) unspent = { address: unspent.address, confirmations: unspent.confirmations || 0, index: index, txHash: txHash, txId: txId, value: unspent.value, // FIXME: remove in 2.0.0 pending: unspent.pending || false } // FIXME: remove in 2.0.0 this.unspentMap[txId + ':' + index] = unspent return unspent }, this) } Wallet.prototype.signWith = function(tx, addresses) { addresses.forEach(function(address, i) { var privKey = this.getPrivateKeyForAddress(address) tx.sign(i, privKey) }, this) return tx } function estimatePaddedFee(tx, network) { var tmpTx = tx.clone() tmpTx.addOutput(Script.EMPTY, network.dustSoftThreshold || 0) return network.estimateFee(tmpTx) } // FIXME: 1.0.0 shims, remove in 2.0.0 Wallet.prototype.getReceiveAddress = Wallet.prototype.getAddress Wallet.prototype.createTx = Wallet.prototype.createTransaction module.exports = Wallet
import { arrayEach } from '../../helpers/array'; import { warn } from '../../helpers/console'; /** * Class used to make all endpoint-related operations. * * @class Endpoints * @plugin ColumnSummary */ class Endpoints { constructor(plugin, settings) { /** * The main plugin instance. */ this.plugin = plugin; /** * Handsontable instance. * * @type {object} */ this.hot = this.plugin.hot; /** * Array of declared plugin endpoints (calculation destination points). * * @type {Array} * @default {Array} Empty array. */ this.endpoints = []; /** * The plugin settings, taken from Handsontable configuration. * * @type {object|Function} * @default null */ this.settings = settings; /** * Settings type. Can be either 'array' or 'function. * * @type {string} * @default {'array'} */ this.settingsType = 'array'; /** * The current endpoint (calculation destination point) in question. * * @type {object} * @default null */ this.currentEndpoint = null; /** * Array containing a list of changes to be applied. * * @private * @type {Array} * @default {[]} */ this.cellsToSetCache = []; } /** * Get a single endpoint object. * * @param {number} index Index of the endpoint. * @returns {object} */ getEndpoint(index) { if (this.settingsType === 'function') { return this.fillMissingEndpointData(this.settings)[index]; } return this.endpoints[index]; } /** * Get an array with all the endpoints. * * @returns {Array} */ getAllEndpoints() { if (this.settingsType === 'function') { return this.fillMissingEndpointData(this.settings); } return this.endpoints; } /** * Used to fill the blanks in the endpoint data provided by a settings function. * * @private * @param {Function} func Function provided in the HOT settings. * @returns {Array} An array of endpoints. */ fillMissingEndpointData(func) { return this.parseSettings(func.call(this)); } /** * Parse plugin's settings. * * @param {Array} settings The settings array. * @returns {object[]} */ parseSettings(settings) { const endpointsArray = []; let settingsArray = settings; if (!settingsArray && typeof this.settings === 'function') { this.settingsType = 'function'; return; } if (!settingsArray) { settingsArray = this.settings; } arrayEach(settingsArray, (val) => { const newEndpoint = {}; this.assignSetting(val, newEndpoint, 'ranges', [[0, this.hot.countRows() - 1]]); this.assignSetting(val, newEndpoint, 'reversedRowCoords', false); this.assignSetting(val, newEndpoint, 'destinationRow', new Error(` You must provide a destination row for the Column Summary plugin in order to work properly! `)); this.assignSetting(val, newEndpoint, 'destinationColumn', new Error(` You must provide a destination column for the Column Summary plugin in order to work properly! `)); this.assignSetting(val, newEndpoint, 'sourceColumn', val.destinationColumn); this.assignSetting(val, newEndpoint, 'type', 'sum'); this.assignSetting(val, newEndpoint, 'forceNumeric', false); this.assignSetting(val, newEndpoint, 'suppressDataTypeErrors', true); this.assignSetting(val, newEndpoint, 'suppressDataTypeErrors', true); this.assignSetting(val, newEndpoint, 'customFunction', null); this.assignSetting(val, newEndpoint, 'readOnly', true); this.assignSetting(val, newEndpoint, 'roundFloat', false); endpointsArray.push(newEndpoint); }); return endpointsArray; } /** * Setter for the internal setting objects. * * @param {object} settings Object with the settings. * @param {object} endpoint Contains information about the endpoint for the the calculation. * @param {string} name Settings name. * @param {object} defaultValue Default value for the settings. */ assignSetting(settings, endpoint, name, defaultValue) { if (name === 'ranges' && settings[name] === void 0) { endpoint[name] = defaultValue; return; } else if (name === 'ranges' && settings[name].length === 0) { return; } if (settings[name] === void 0) { if (defaultValue instanceof Error) { throw defaultValue; } endpoint[name] = defaultValue; } else { /* eslint-disable no-lonely-if */ if (name === 'destinationRow' && endpoint.reversedRowCoords) { endpoint[name] = this.hot.countRows() - settings[name] - 1; } else { endpoint[name] = settings[name]; } } } /** * Resets the endpoint setup before the structure alteration (like inserting or removing rows/columns). Used for settings provided as a function. * * @private * @param {string} action Type of the action performed. * @param {number} index Row/column index. * @param {number} number Number of rows/columns added/removed. */ resetSetupBeforeStructureAlteration(action, index, number) { if (this.settingsType !== 'function') { return; } const type = action.indexOf('row') > -1 ? 'row' : 'col'; const endpoints = this.getAllEndpoints(); arrayEach(endpoints, (val) => { if (type === 'row' && val.destinationRow >= index) { if (action === 'insert_row') { val.alterRowOffset = number; } else if (action === 'remove_row') { val.alterRowOffset = (-1) * number; } } if (type === 'col' && val.destinationColumn >= index) { if (action === 'insert_col') { val.alterColumnOffset = number; } else if (action === 'remove_col') { val.alterColumnOffset = (-1) * number; } } }); this.resetAllEndpoints(endpoints, false); } /** * AfterCreateRow/afterCreateRow/afterRemoveRow/afterRemoveCol hook callback. Reset and reenables the summary functionality * after changing the table structure. * * @private * @param {string} action Type of the action performed. * @param {number} index Row/column index. * @param {number} number Number of rows/columns added/removed. * @param {Array} [logicRows] Array of the logical indexes. * @param {string} [source] Source of change. * @param {boolean} [forceRefresh] `true` of the endpoints should refresh after completing the function. */ resetSetupAfterStructureAlteration(action, index, number, logicRows, source, forceRefresh = true) { if (this.settingsType === 'function') { // We need to run it on a next avaiable hook, because the TrimRows' `afterCreateRow` hook triggers after this one, // and it needs to be run to properly calculate the endpoint value. const beforeRenderCallback = () => { this.hot.removeHook('beforeRender', beforeRenderCallback); return this.refreshAllEndpoints(); }; this.hot.addHookOnce('beforeRender', beforeRenderCallback); return; } const type = action.indexOf('row') > -1 ? 'row' : 'col'; const multiplier = action.indexOf('remove') > -1 ? -1 : 1; const endpoints = this.getAllEndpoints(); const rowMoving = action.indexOf('move_row') === 0; const placeOfAlteration = index; arrayEach(endpoints, (val) => { if (type === 'row' && val.destinationRow >= placeOfAlteration) { val.alterRowOffset = multiplier * number; } if (type === 'col' && val.destinationColumn >= placeOfAlteration) { val.alterColumnOffset = multiplier * number; } }); this.resetAllEndpoints(endpoints, !rowMoving); if (rowMoving) { arrayEach(endpoints, (endpoint) => { this.extendEndpointRanges(endpoint, placeOfAlteration, logicRows[0], logicRows.length); this.recreatePhysicalRanges(endpoint); this.clearOffsetInformation(endpoint); }); } else { arrayEach(endpoints, (endpoint) => { this.shiftEndpointCoordinates(endpoint, placeOfAlteration); }); } if (forceRefresh) { this.refreshAllEndpoints(); } } /** * Clear the offset information from the endpoint object. * * @private * @param {object} endpoint And endpoint object. */ clearOffsetInformation(endpoint) { endpoint.alterRowOffset = void 0; endpoint.alterColumnOffset = void 0; } /** * Extend the row ranges for the provided endpoint. * * @private * @param {object} endpoint The endpoint object. * @param {number} placeOfAlteration Index of the row where the alteration takes place. * @param {number} previousPosition Previous endpoint result position. * @param {number} offset Offset generated by the alteration. */ extendEndpointRanges(endpoint, placeOfAlteration, previousPosition, offset) { arrayEach(endpoint.ranges, (range) => { // is a range, not a single row if (range[1]) { if (placeOfAlteration >= range[0] && placeOfAlteration <= range[1]) { if (previousPosition > range[1]) { range[1] += offset; } else if (previousPosition < range[0]) { range[0] -= offset; } } else if (previousPosition >= range[0] && previousPosition <= range[1]) { range[1] -= offset; if (placeOfAlteration <= range[0]) { range[0] += 1; range[1] += 1; } } } }); } /** * Recreate the physical ranges for the provided endpoint. Used (for example) when a row gets moved and extends an existing range. * * @private * @param {object} endpoint An endpoint object. */ recreatePhysicalRanges(endpoint) { const ranges = endpoint.ranges; const newRanges = []; const allIndexes = []; arrayEach(ranges, (range) => { const newRange = []; if (range[1]) { for (let i = range[0]; i <= range[1]; i++) { newRange.push(this.hot.toPhysicalRow(i)); } } else { newRange.push(this.hot.toPhysicalRow(range[0])); } allIndexes.push(newRange); }); arrayEach(allIndexes, (range) => { let newRange = []; arrayEach(range, (coord, index) => { if (index === 0) { newRange.push(coord); } else if (range[index] !== range[index - 1] + 1) { newRange.push(range[index - 1]); newRanges.push(newRange); newRange = []; newRange.push(coord); } if (index === range.length - 1) { newRange.push(coord); newRanges.push(newRange); } }); }); endpoint.ranges = newRanges; } /** * Shifts the endpoint coordinates by the defined offset. * * @private * @param {object} endpoint Endpoint object. * @param {number} offsetStartIndex Index of the performed change (if the change is located after the endpoint, nothing about the endpoint has to be changed. */ shiftEndpointCoordinates(endpoint, offsetStartIndex) { if (endpoint.alterRowOffset && endpoint.alterRowOffset !== 0) { endpoint.destinationRow += endpoint.alterRowOffset || 0; arrayEach(endpoint.ranges, (element) => { arrayEach(element, (subElement, j) => { if (subElement >= offsetStartIndex) { element[j] += endpoint.alterRowOffset || 0; } }); }); } else if (endpoint.alterColumnOffset && endpoint.alterColumnOffset !== 0) { endpoint.destinationColumn += endpoint.alterColumnOffset || 0; endpoint.sourceColumn += endpoint.alterColumnOffset || 0; } } /** * Resets (removes) the endpoints from the table. * * @param {Array} [endpoints] Array containing the endpoints. * @param {boolean} [useOffset=true] Use the cell offset value. */ resetAllEndpoints(endpoints = this.getAllEndpoints(), useOffset = true) { const anyEndpointOutOfRange = endpoints.some((endpoint) => { const alterRowOffset = endpoint.alterRowOffset || 0; const alterColOffset = endpoint.alterColumnOffset || 0; if (endpoint.destinationRow + alterRowOffset >= this.hot.countRows() || endpoint.destinationColumn + alterColOffset >= this.hot.countCols()) { return true; } return false; }); if (anyEndpointOutOfRange) { return; } this.cellsToSetCache = []; arrayEach(endpoints, (endpoint) => { this.resetEndpointValue(endpoint, useOffset); }); this.hot.setDataAtCell(this.cellsToSetCache, 'ColumnSummary.reset'); this.cellsToSetCache = []; } /** * Calculate and refresh all defined endpoints. */ refreshAllEndpoints() { this.cellsToSetCache = []; arrayEach(this.getAllEndpoints(), (value) => { this.currentEndpoint = value; this.plugin.calculate(value); this.setEndpointValue(value, 'init'); }); this.currentEndpoint = null; this.hot.setDataAtCell(this.cellsToSetCache, 'ColumnSummary.reset'); this.cellsToSetCache = []; } /** * Calculate and refresh endpoints only in the changed columns. * * @param {Array} changes Array of changes from the `afterChange` hook. */ refreshChangedEndpoints(changes) { const needToRefresh = []; this.cellsToSetCache = []; arrayEach(changes, (value, key, changesObj) => { // if nothing changed, dont update anything if (`${value[2] || ''}` === `${value[3]}`) { return; } arrayEach(this.getAllEndpoints(), (endpoint, j) => { if (this.hot.propToCol(changesObj[key][1]) === endpoint.sourceColumn && needToRefresh.indexOf(j) === -1) { needToRefresh.push(j); } }); }); arrayEach(needToRefresh, (value) => { this.refreshEndpoint(this.getEndpoint(value)); }); this.hot.setDataAtCell(this.cellsToSetCache, 'ColumnSummary.reset'); this.cellsToSetCache = []; } /** * Calculate and refresh a single endpoint. * * @param {object} endpoint Contains the endpoint information. */ refreshEndpoint(endpoint) { this.currentEndpoint = endpoint; this.plugin.calculate(endpoint); this.setEndpointValue(endpoint); this.currentEndpoint = null; } /** * Reset the endpoint value. * * @param {object} endpoint Contains the endpoint information. * @param {boolean} [useOffset=true] Use the cell offset value. */ resetEndpointValue(endpoint, useOffset = true) { const alterRowOffset = endpoint.alterRowOffset || 0; const alterColOffset = endpoint.alterColumnOffset || 0; const [visualRowIndex, visualColumnIndex] = [ this.hot.toVisualRow(endpoint.destinationRow), this.hot.toVisualColumn(endpoint.destinationColumn) ]; if (visualColumnIndex !== null && visualRowIndex !== null) { // Clear the meta on the "old" indexes const cellMeta = this.hot.getCellMeta(visualRowIndex, visualColumnIndex); cellMeta.readOnly = false; cellMeta.className = ''; } this.cellsToSetCache.push([ this.hot.toVisualRow(endpoint.destinationRow + (useOffset ? alterRowOffset : 0)), this.hot.toVisualColumn(endpoint.destinationColumn + (useOffset ? alterColOffset : 0)), '' ]); } /** * Set the endpoint value. * * @param {object} endpoint Contains the endpoint information. * @param {string} [source] Source of the call information. * @param {boolean} [render=false] `true` if it needs to render the table afterwards. */ setEndpointValue(endpoint, source, render = false) { // We'll need the reversed offset values, because cellMeta will be shifted AGAIN afterwards. const reverseRowOffset = (-1) * endpoint.alterRowOffset || 0; const reverseColOffset = (-1) * endpoint.alterColumnOffset || 0; const visualEndpointRowIndex = this.hot.toVisualRow(endpoint.destinationRow); if (endpoint.destinationRow >= this.hot.countRows() || endpoint.destinationColumn >= this.hot.countCols()) { this.throwOutOfBoundsWarning(); return; } const destinationVisualRow = this.hot.toVisualRow(endpoint.destinationRow + reverseRowOffset); if (destinationVisualRow !== null) { const cellMeta = this.hot.getCellMeta( destinationVisualRow, endpoint.destinationColumn + reverseColOffset ); if (source === 'init' || cellMeta.readOnly !== endpoint.readOnly) { cellMeta.readOnly = endpoint.readOnly; cellMeta.className = 'columnSummaryResult'; } } if (endpoint.roundFloat && !isNaN(endpoint.result)) { endpoint.result = endpoint.result.toFixed(endpoint.roundFloat); } if (render) { this.hot.setDataAtCell(visualEndpointRowIndex, endpoint.destinationColumn, endpoint.result, 'ColumnSummary.set'); } else { this.cellsToSetCache.push([visualEndpointRowIndex, endpoint.destinationColumn, endpoint.result]); } endpoint.alterRowOffset = void 0; endpoint.alterColumnOffset = void 0; } /** * Throw an error for the calculation range being out of boundaries. * * @private */ throwOutOfBoundsWarning() { warn('One of the Column Summary plugins\' destination points you provided is beyond the table boundaries!'); } } export default Endpoints;
import React from 'react' import { View, Text, Button } from 'react-native' // Composant pour l'écran de victoire export default ({ guesses, onReset }) => ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: "#1D1D1D" }}> <Text style={{ color: "#FFFFFF", fontSize: 50, marginBottom: 20 }}>Bravo 🎉</Text> <Text style={{ color: "#FFFFFF", fontSize: 20, textAlign: "center", marginBottom: 80 }}>Vous avez gagné en {guesses} tentatives !</Text> <View style={{ width: 200 }}> <Button onPress={onReset} title="Recommencer" color="#383636" accessibilityLabel="Recommencer" /> </View> </View> )
(function() { 'use strict'; angular .module('app.dashboard') .factory('dashboard', dashboard); /* @ngInject */ function dashboard(Restangular, apiEndPoints, utilities) { var dashboardAPI = Restangular.all(apiEndPoints.dashboard.main); var notificationAPI = Restangular.all(apiEndPoints.notification.main); return { getCompleteDashboardReport: getCompleteDashboardReport, refreshCurrentDollarRate: refreshCurrentDollarRate, searchQueryPageTop: searchQueryPageTop, getNotificationCount: getNotificationCount, getUnReadNotificationList: getUnReadNotificationList }; function getNotificationCount(){ return notificationAPI.customGET(apiEndPoints.notification.unreadCount); } function getUnReadNotificationList(markRead){ return notificationAPI.customGET(apiEndPoints.notification.unreadList, { mark_as_read: markRead }); } function getCompleteDashboardReport(){ return dashboardAPI.customGET('',{ }); } function searchQueryPageTop(queryObj){ return dashboardAPI.customGET(apiEndPoints.dashboard.searchPageTop, queryObj); } function refreshCurrentDollarRate(){ } } })();
/* * @package jsDAV * @subpackage DAVACL * @copyright Copyright(c) 2013 Mike de Boer. <info AT mikedeboer DOT nl> * @author Daniel Laxar * @license http://github.com/mikedeboer/jsDAV/blob/master/LICENSE MIT License */ "use strict"; var jsDAV_Auth_Backend_AbstractDigest = require("./abstractDigest"); /** * This is an authentication backend that uses a postgres database to manage passwords. */ var jsDAV_Auth_Backend_Postgre = module.exports = jsDAV_Auth_Backend_AbstractDigest.extend({ initialize: function (authBackend, tableName) { jsDAV_Auth_Backend_AbstractDigest.initialize.call(this); this.authBackend = authBackend; this.tableName = tableName || "users" }, /** * Returns a users' information * * @param {string} realm * @param {string} username * @return {string} */ getDigestHash: function (realm, username, cbdigest) { var queryText = this.authBackend.query( "SELECT * FROM " + this.tableName + " WHERE username=$1", [username], function(err, result) { if (err) return cbdigest(err); if (result.rows.length > 0) return cbdigest(null, result.rows[0].password); if (result.rows.length == 0) return cbdigest(null, undefined); cbdigest("Unexpected number of rows: " + result.rows.length); } ); } });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.UsuarioRole = void 0; var UsuarioRole; (function (UsuarioRole) { UsuarioRole[UsuarioRole["admin"] = 0] = "admin"; UsuarioRole[UsuarioRole["super"] = 1] = "super"; UsuarioRole[UsuarioRole["normal"] = 2] = "normal"; })(UsuarioRole = exports.UsuarioRole || (exports.UsuarioRole = {})); //# sourceMappingURL=usuario-role-enums.js.map
30 mtime=1556799613.542475917 24 SCHILY.fflags=extent
/** * A Sentiment document defines topic and sentiment metadata for a tweet. Tweets can have multiple sentiment * documents, as sentiment can come from different sources (i.e. AWS vs Watson) */ const mongoose = require('mongoose'); const Schema = mongoose.Schema; const SENTIMENT_SOURCES = { // Amazon's Comprehend comprehend: 'comprehend', // Watson NLU nlu: 'nlu', } const SENTIMENT_REGEX = '/^(' + Object.keys(SENTIMENT_SOURCES).join('|') + ')$/'; module.exports = new Schema({ source: { type: String, match: SENTIMENT_REGEX, }, // MongooseMap where keys are topics (hashtags) and values are relevance scores (Number) relevance: { type: Map, of: Number }, created: Date, });
/* eslint-disable global-require */ import babel from '@rollup/plugin-babel'; import commonjs from '@rollup/plugin-commonjs'; import typescript from 'rollup-plugin-typescript2'; import alias from '@rollup/plugin-alias'; import path from 'path'; import pkg from './package.json'; const projectRootDir = path.resolve(__dirname); export default [ { input: 'src/index.ts', output: [ { file: pkg.main, name: 'named', format: 'umd', }, { file: pkg.module, format: 'es', sourcemap: true, }, ], plugins: [ alias({ entries: [ { find: 'src', replacement: path.resolve(projectRootDir, 'src'), }, ], }), typescript({ typescript: require('typescript'), exclude: ['**/*.(spec|test|stories).ts+(|x)'], tsconfig: './tsconfig.json', }), babel({ exclude: 'node_modules/**', extensions: ['.ts', '.tsx'], babelHelpers: 'runtime', }), commonjs(), ], external: [ ...Object.keys(pkg.dependencies || {}), ...Object.keys(pkg.peerDependencies || {}), ], }, ];
import * as PIXI from 'pixi.js' import gameContainer from './container' import Star from './star' import Carrier from './carrier' import Waypoints from './waypoints' import RulerPoints from './rulerPoints' import Territories from './territories' import EventEmitter from 'events' import GameHelper from '../services/gameHelper' import AnimationService from './animation' class Map extends EventEmitter { // Represents the current game mode, these are as follows: // galaxy - Normal galaxy view // waypoints - Displays waypoints overlay for a given carrier mode = 'galaxy' constructor (app) { super() this.app = app this.container = new PIXI.Container() this.stars = [] this.carriers = [] this.zoomPercent = 0 } _setupContainers () { this.starContainer = new PIXI.Container() this.carrierContainer = new PIXI.Container() this.waypointContainer = new PIXI.Container() this.rulerPointContainer = new PIXI.Container() this.territoryContainer = new PIXI.Container() this.container.addChild(this.territoryContainer) this.container.addChild(this.rulerPointContainer) this.container.addChild(this.waypointContainer) this.container.addChild(this.starContainer) this.container.addChild(this.carrierContainer) } setup (game) { this.game = game // Cleanup events this.stars.forEach(s => s.removeAllListeners()) this.carriers.forEach(s => s.removeAllListeners()) this.container.removeChildren() this._setupContainers() // Reset the canvas this.stars = [] this.carriers = [] // Add stars for (let i = 0; i < game.galaxy.stars.length; i++) { this.setupStar(game, game.galaxy.stars[i]) } // Add carriers for (let i = 0; i < game.galaxy.carriers.length; i++) { this.setupCarrier(game, game.galaxy.carriers[i]) } // ----------- // Setup Waypoints if (this.waypoints) { this.waypoints.removeAllListeners() } this.waypoints = new Waypoints() this.waypoints.setup(game) this.waypoints.onWaypointCreatedHandler = this.waypoints.on('onWaypointCreated', this.onWaypointCreated.bind(this)) this.waypointContainer.addChild(this.waypoints.container) // ----------- // Setup Ruler Points if (this.rulerPoints) { this.rulerPoints.removeAllListeners() } this.rulerPoints = new RulerPoints() this.rulerPoints.setup(game) this.rulerPoints.onRulerPointCreatedHandler = this.rulerPoints.on('onRulerPointCreated', this.onRulerPointCreated.bind(this)) this.rulerPoints.onRulerPointsClearedHandler = this.rulerPoints.on('onRulerPointsCleared', this.onRulerPointsCleared.bind(this)) this.rulerPointContainer.addChild(this.rulerPoints.container) // ----------- // Setup Territories this.territories = new Territories() this.territories.setup(game) this.territoryContainer.addChild(this.territories.container) } setupStar (game, starData) { let star = this.stars.find(x => x.data._id === starData._id) if (!star) { star = new Star(this.app) this.stars.push(star) this.starContainer.addChild(star.container) star.on('onStarClicked', this.onStarClicked.bind(this)) star.on('onStarDoubleClicked', this.onStarDoubleClicked.bind(this)) star.on('onStarRightClicked', this.onStarRightClicked.bind(this)) } star.setup(starData, game.galaxy.players, game.galaxy.carriers, game.constants.distances.lightYear) return star } setupCarrier (game, carrierData) { let existing = this.carriers.find(x => x.data._id === carrierData._id) if (existing) { existing.off('onCarrierClicked', this.onCarrierClicked.bind(this)) existing.off('onCarrierDoubleClicked', this.onCarrierDoubleClicked.bind(this)) existing.off('onCarrierRightClicked', this.onCarrierRightClicked.bind(this)) existing.off('onCarrierMouseOver', this.onCarrierMouseOver.bind(this)) existing.off('onCarrierMouseOut', this.onCarrierMouseOut.bind(this)) this.carrierContainer.removeChild(existing.container) this.carriers.splice(this.carriers.indexOf(existing), 1) } let carrier = new Carrier() let player = GameHelper.getPlayerById(game, carrierData.ownedByPlayerId) carrier.setup(carrierData, this.stars, player, game.constants.distances.lightYear) this.carriers.push(carrier) this.carrierContainer.addChild(carrier.container) carrier.on('onCarrierClicked', this.onCarrierClicked.bind(this)) carrier.on('onCarrierDoubleClicked', this.onCarrierDoubleClicked.bind(this)) carrier.on('onCarrierRightClicked', this.onCarrierRightClicked.bind(this)) carrier.on('onCarrierMouseOver', this.onCarrierMouseOver.bind(this)) carrier.on('onCarrierMouseOut', this.onCarrierMouseOut.bind(this)) return carrier } draw () { this.drawStars() this.drawCarriers() if (this.mode === 'waypoints') { this.drawWaypoints() } else { this.clearWaypoints() } if (this.mode === 'ruler') { this.drawRulerPoints() } else { this.clearRulerPoints() } } reloadGame (game) { // Update all of the stars. for (let i = 0; i < game.galaxy.stars.length; i++) { let starData = game.galaxy.stars[i] let existing = this.stars.find(x => x.data._id === starData._id) existing.setup(starData, game.galaxy.players, game.galaxy.carriers, game.constants.distances.lightYear) existing.draw() } // Remove any carriers that have been destroyed and add new ones that have been built. for (let i = 0; i < game.galaxy.carriers.length; i++) { let carrierData = game.galaxy.carriers[i] let existing = this.carriers.find(x => x.data._id === carrierData._id) if (existing) { let player = GameHelper.getPlayerById(game, carrierData.ownedByPlayerId) existing.setup(carrierData, this.stars, player, game.constants.distances.lightYear) } else { existing = this.setupCarrier(game, carrierData) } existing.draw() } } setMode (mode, args) { this.mode = mode this.modeArgs = args if (this.mode !== 'galaxy') { this.unselectAllCarriers() this.unselectAllStars() } this.draw() } resetMode () { this.mode = 'galaxy' this.draw() } drawStars () { for (let i = 0; i < this.stars.length; i++) { let star = this.stars[i] this.drawStar(star) } } drawStar (star) { star.draw() } drawCarriers () { for (let i = 0; i < this.carriers.length; i++) { let carrier = this.carriers[i] this.drawCarrier(carrier) } } drawCarrier (carrier) { carrier.draw() } undrawCarrier (carrierData) { let existing = this.carriers.find(x => x.data._id === carrierData._id) if (existing) { existing.off('onCarrierClicked', this.onCarrierClicked.bind(this)) existing.off('onCarrierDoubleClicked', this.onCarrierDoubleClicked.bind(this)) existing.off('onCarrierRightClicked', this.onCarrierRightClicked.bind(this)) existing.off('onCarrierMouseOver', this.onCarrierMouseOver.bind(this)) existing.off('onCarrierMouseOut', this.onCarrierMouseOut.bind(this)) this.carrierContainer.removeChild(existing.container) this.carriers.splice(this.carriers.indexOf(existing), 1) } } drawWaypoints () { this.waypoints.draw(this.modeArgs) } clearWaypoints () { this.waypoints.clear() } drawRulerPoints () { this.rulerPoints.draw(this.modeArgs) } clearRulerPoints () { this.rulerPoints.setup(this.game) } drawTerritories () { if (this.territories) { this.territories.draw() } } clearTerritories () { if (this.territories) { this.territories.clear() } } panToPlayer (game, player) { // Find the home star the player owns. let homeStar = game.galaxy.stars.find(x => { return x._id === player.homeStarId }) if (!homeStar) { return } gameContainer.viewport.moveCenter(homeStar.location.x, homeStar.location.y) let zoomPercent = gameContainer.getViewportZoomPercentage() this.refreshZoom(zoomPercent) } panToUser (game) { let player = GameHelper.getUserPlayer(game) if (!player) { return } this.panToPlayer(game, player) } panToStar (star) { this.panToLocation(star.location) let zoomPercent = gameContainer.getViewportZoomPercentage() this.refreshZoom(zoomPercent) } panToLocation (location) { gameContainer.viewport.moveCenter(location.x, location.y) } clickStar (starId) { let star = this.stars.find(s => s.data._id === starId) star.onClicked() } clickCarrier (carrierId) { let carrier = this.carriers.find(s => s.data._id === carrierId) carrier.onClicked() } unselectAllStars () { this.stars .forEach(s => { s.isSelected = false s.drawActive(false) // Should be fine to pass in false for force }) } unselectAllCarriers () { this.carriers .forEach(c => { c.isSelected = false c.drawActive() }) } unselectAllStarsExcept (star) { this.stars .filter(s => s.isSelected || s.data._id === star.data._id) // Get only stars that are selected or the e star. .forEach(s => { // Set all other stars to unselected. if (s.data._id !== star.data._id) { s.isSelected = false } s.drawActive(false) // Should be fine to pass in false for the force param }) } unselectAllCarriersExcept (carrier) { this.carriers .filter(c => c.isSelected || c.data._id === carrier.data._id) // Get only stars that are selected or the e star. .forEach(c => { // Set all other carriers to unselected. if (c.data._id !== carrier.data._id) { c.isSelected = false } c.drawActive(false) // Should be fine to pass in false for the force param }) } onStarClicked (e) { // Clicking stars should only raise events to the UI if in galaxy mode. if (this.mode === 'galaxy') { let selectedStar = this.stars.find(x => x.data._id === e._id) selectedStar.isSelected = !selectedStar.isSelected this.unselectAllCarriers() this.unselectAllStarsExcept(selectedStar) } else if (this.mode === 'waypoints') { this.waypoints.onStarClicked(e) } else if (this.mode === 'ruler') { this.rulerPoints.onStarClicked(e) } AnimationService.drawSelectedCircle(this.app, this.container, e.location) } onStarDoubleClicked (e) { // Clicking stars should only raise events to the UI if in galaxy mode. if (this.mode === 'galaxy') { let selectedStar = this.stars.find(x => x.data._id === e._id) selectedStar.isSelected = true this.unselectAllCarriers() this.unselectAllStarsExcept(selectedStar) if (!this.tryMultiSelect(e.location)) { this.emit('onStarDoubleClicked', e) } } else if (this.mode === 'waypoints') { this.waypoints.onStarClicked(e) } else if (this.mode === 'ruler') { this.rulerPoints.onStarClicked(e) } AnimationService.drawSelectedCircle(this.app, this.container, e.location) } onStarRightClicked (e) { if (this.mode === 'galaxy') { this.emit('onStarRightClicked', e) } } onCarrierClicked (e) { // Clicking carriers should only raise events to the UI if in galaxy mode. if (this.mode === 'galaxy') { // If the carrier is in orbit, pass the click over to the star instead. if (e.orbiting) { let star = this.stars.find(x => x.data._id === e.orbiting) return this.onStarClicked(star.data) } let selectedCarrier = this.carriers.find(x => x.data._id === e._id) selectedCarrier.isSelected = !selectedCarrier.isSelected this.unselectAllStars() this.unselectAllCarriersExcept(selectedCarrier) } else if (this.mode === 'waypoints') { this.waypoints.onCarrierClicked(e) } else if (this.mode === 'ruler') { this.rulerPoints.onCarrierClicked(e) } AnimationService.drawSelectedCircle(this.app, this.container, e.location) } onCarrierDoubleClicked (e) { // Clicking carriers should only raise events to the UI if in galaxy mode. if (this.mode === 'galaxy') { // If the carrier is in orbit, pass the click over to the star instead. if (e.orbiting) { let star = this.stars.find(x => x.data._id === e.orbiting) return this.onStarDoubleClicked(star.data) } let selectedCarrier = this.carriers.find(x => x.data._id === e._id) selectedCarrier.isSelected = true this.unselectAllStars() this.unselectAllCarriersExcept(selectedCarrier) if (!this.tryMultiSelect(e.location)) { this.emit('onCarrierDoubleClicked', e) } } else if (this.mode === 'waypoints') { this.waypoints.onCarrierClicked(e) } else if (this.mode === 'ruler') { this.rulerPoints.onCarrierClicked(e) } AnimationService.drawSelectedCircle(this.app, this.container, e.location) } onCarrierRightClicked (e) { if (this.mode === 'galaxy') { this.emit('onCarrierRightClicked', e) } } onCarrierMouseOver (e) { // If the carrier is orbiting something then send the mouse over event // to the star. if (e.orbiting) { let star = this.stars.find(s => s.data._id === e.orbiting) star.onMouseOver() } } onCarrierMouseOut (e) { // If the carrier is orbiting something then send the mouse over event // to the star. if (e.orbiting) { let star = this.stars.find(s => s.data._id === e.orbiting) star.onMouseOut() } } onWaypointCreated (e) { this.emit('onWaypointCreated', e) } onRulerPointCreated (e) { this.emit('onRulerPointCreated', e) } onRulerPointsCleared (e) { this.emit('onRulerPointsCleared', e) } tryMultiSelect (location) { // See if there are any other objects close by, if so then // we want to allow the user to select which one they want as there might be // objects on the map that are on top of eachother or very close together. const distance = 10 let closeStars = this.stars .map(s => { return { type: 'star', distance: GameHelper.getDistanceBetweenLocations(location, s.data.location), data: s.data } }) .filter(s => s.distance <= distance) let closeCarriers = this.carriers .map(s => { return { type: 'carrier', distance: GameHelper.getDistanceBetweenLocations(location, s.data.location), data: s.data } }) .filter(s => s.distance <= distance) // Combine the arrays and order by closest first. let closeObjects = closeStars.concat(closeCarriers) .sort((a, b) => a.distance - b.distance) if (closeObjects.length > 1) { this.emit('onObjectsClicked', closeObjects) return true } return false } refreshZoom (zoomPercent) { this.zoomPercent = zoomPercent this.stars.forEach(s => s.refreshZoom(zoomPercent)) this.carriers.forEach(c => c.refreshZoom(zoomPercent)) if (this.zoomPercent > 100) { this.drawTerritories() } else { this.clearTerritories() } } } export default Map
(function() { 'use strict'; // RequireJS configuration. require.config({ paths: { 'jquery': 'vendor/jquery', 'jqueryui': 'vendor/jquery-ui', 'moxie': 'vendor/plupload/moxie', 'plupload': 'vendor/plupload/plupload.dev', 'pluploadui': 'vendor/plupload/jquery.ui.plupload/jquery.ui.plupload', 'cldr': 'vendor/cldr', 'globalize': 'vendor/globalize' }, shim: { 'vendor/jquery-cookie': { deps: ['jquery'] }, 'vendor/jquery.finderSelect': { deps: ['jquery'] }, 'vendor/jquery-placeholder': { deps: ['jquery'] }, 'vendor/sammy': { deps: ['jquery'] }, 'vendor/jqueryui': { deps: ['jquery'] }, 'vendor/jquery-dropdown': { deps: ['jquery'] }, 'vendor/jquery-scrollstop': { deps: ['jquery'] }, 'jqueryui': { deps: ['jquery'] }, 'plupload': { deps: ['jquery', 'moxie'], exports: 'plupload' }, 'pluploadui': { deps: ['jquery', 'plupload'], exports: 'pluploadui' } }, }); // Load dependencies. require(['jquery', 'vendor/knockout', 'vendor/sammy', 'vendor/loglevel', 'vendor/moment', 'config', 'storage', 'accounts', 'files', 'auth', 'models/search', 'util', 'localization', // Imports below don't need to be assigned to variables. 'jqueryui', 'vendor/jquery-dropdown', 'vendor/jquery-scrollstop', 'moxie', 'plupload', 'pluploadui', 'vendor/jquery.finderSelect', 'iexd-transport'], function($, ko, sammy, logger, moment, config, storage, AccountManager, FileManager, auth, Search, util, localization) { // Initialise and configure. logger.setLevel(config.logLevel); // Enable cors $.support.cors = true; var dropzoneLoaded = false; var filesQueue = []; var processingConfirm = false; var loadedDropConfig = false; // This can be generalized in the future with a config option var startView = (config.flavor === 'dropzone') ? 'dropzone' : 'accounts'; var service_names = { cq5 : 'Adobe CQ5', dropbox : 'Dropbox', gdrive : 'Google Drive', box : 'Box', evernote : 'Evernote', skydrive : 'OneDrive', sugarsync : 'SugarSync', sharefile : 'Citrix ShareFile', egnyte : 'Egnyte', s3 : 'Amazon S3', sharepoint: 'SharePoint Online', onedrivebiz: 'OneDrive for Business', smb: 'SMB', hubspot: 'Hubspot Files', salesforce: 'Salesforce Files', azure: 'Azure Storage', cmis : 'CMIS', alfresco : 'Alfresco', alfresco_cloud: 'Alfresco Cloud', jive : 'Jive', webdav: 'WebDAV', ftp: 'FTP', }, services = ko.observableArray(); for (var i = 0; i < config.services.length; i++) { var service = config.services[i]; if (service_names[service] !== undefined) { services.push({ id: service, name: service_names[service], logo: 'https://s3-us-west-2.amazonaws.com/static-assets.kloudless.com/webapp/sources/' + service + '.png' }); } } if (config.computer) { services.unshift({ id: 'computer', name: 'My Computer', logo: 'https://s3-us-west-2.amazonaws.com/static-assets.kloudless.com/webapp/sources/computer.png' }); } // Explorer declaration. var FileExplorer = function() { this.manager = new AccountManager(); this.fileManager = new FileManager(); this.id = (function() { var _id = storage.loadId(); if (!_id) { _id = Math.floor(Math.random() * Math.pow(10, 12)); storage.storeId(_id); } return _id; })(); this.exp_id = config.exp_id; // Track the last cancellation so Chooser responses received after // a cancellation are ignored. Saves are allowed to proceed due to // the new file already having been saved to the location. this.lastCancelTime = new Date(); var self = this; // View model setup. this.view_model = { flavor: ko.observable(config.flavor), // The current view: alternates between 'files', 'accounts', 'computer', etc. current: ko.observable(startView), // Save all files in FileManager to the selected directory save: function() { // Set loading to true explorer.view_model.loading(true); // Grab the current location var current = explorer.manager.active().filesystem().current(); var saves = []; // If you can save here if (current.can_upload_files) { var accountId = explorer.manager.active().filesystem().id; var authKey = explorer.manager.active().filesystem().key; var requestCountSuccess = 0; var requestCountError = 0; // Save Complete Callback var saveComplete = function(success) { if (success) { requestCountSuccess++; } else { requestCountError++; logger.warn('Error with ajax requests for save'); } // All requests are done if (requestCountSuccess + requestCountError == explorer.fileManager.files().length) { explorer.view_model.postMessage('success', saves); logger.debug('Successfully uploaded files: ', saves); } }; var choseOverwrite = false; var overwrite = false; for (var i = 0; i < explorer.fileManager.files().length; i++) { for (var k = 0; k < (current.children().length); k++) { if (current.children()[k].name == explorer.fileManager.files()[i].name) { overwrite = window.confirm( "Files already exist with the same names as the ones being uploaded." + " Click OK to overwrite existing files with the same name" + " or Cancel to proceed without overwriting."); choseOverwrite = true; break; } } if (choseOverwrite) break; } for (var i = 0; i < explorer.fileManager.files().length; i++) { var f = explorer.fileManager.files()[i]; var file_data = { url: f.url, parent_id: current.id, name: $('.kloudless-saver-name').val() || f.name }; logger.debug('file_data.name: ', file_data.name); (function(event_data) { explorer.view_model.postMessage('startFileUpload', event_data); var request = $.ajax({ url: config.getAccountUrl(accountId, 'storage', '/files/?overwrite=' + overwrite), type: 'POST', contentType: 'application/json', headers: { Authorization: authKey.scheme + ' ' + authKey.key }, data: JSON.stringify(file_data) }).done(function(data) { saves.push(data); event_data.metadata = data; explorer.view_model.postMessage('finishFileUpload', event_data); saveComplete(true); }).fail(function(xhr, status, err) { logger.warn('Error uploading file: ', status, err, xhr); saveComplete(false); }); })({name: file_data.name, url: file_data.url}); } } else { explorer.view_model.error('Files cannot be saved to this folder. Please choose again.'); explorer.view_model.loading(false); } }, // Select a file. confirm: function() { if (processingConfirm) return; // Set loading to true explorer.view_model.loading(true); // Clone the selections, removing the parent reference. var current = explorer.manager.active().filesystem().current(); var selections = []; var clones = []; var table = self.view_model.files.table; if (table) { var selectedElements = table.finderSelect('selected'); for (var i = 0; i < selectedElements.length; i++) { selections.push(ko.dataFor(selectedElements[i])); } } for (var i = 0; i < selections.length; i++) { var selection = selections[i]; var clone = {}; for (var attr in selection) { if (selection.hasOwnProperty(attr) && attr != 'parent_obs') { clone[attr] = selection[attr]; } } clones.push(clone); } selections = clones; // postMessage to indicate success. if (selections.length > 0) { logger.debug('Files selected! ', selections); explorer.view_model.postMessage('selected', selections); var accountId = explorer.manager.active().filesystem().id; var authKey = explorer.manager.active().filesystem().key; var lastCancelTime = explorer.lastCancelTime; var requestCountSuccess = 0; var requestCountError = 0; var requestCountStarted = 0; var maxRequestsInProgress = 4; var requestsToLaunch = []; var requestLauncherInterval = window.setInterval(function() { var requestsComplete = requestCountSuccess + requestCountError; var requestsInProgress = requestCountStarted - requestsComplete; while (requestsToLaunch.length > 0 && requestsInProgress < maxRequestsInProgress) { var callData = requestsToLaunch.shift(); callData.fn(callData.i); requestsInProgress = requestCountStarted - requestsComplete; } }, 200); // Selection Complete Callback var selectionComplete = function(success) { if (success) { requestCountSuccess++; } else { requestCountError++; logger.warn('Error with ajax requests for selection'); } if (explorer.lastCancelTime > lastCancelTime) { logger.info("A cancellation occurred prior to the operation " + "being completed. Ignoring response.") processingConfirm = false; window.clearInterval(requestLauncherInterval); return; } // All requests are done // TODO handle case if requestCountError != 0 if (requestCountSuccess + requestCountError == selections.length) { window.clearInterval(requestLauncherInterval); explorer.view_model.postMessage('success', selections); processingConfirm = false; } }; // Add the link at the last possible moment for error/async handling var createLink = function(selection_index) { var linkData = $.extend({}, config.link_options()); linkData.file_id = selections[selection_index].id; var request = $.ajax({ url: config.getAccountUrl(accountId, 'storage', '/links/'), type: 'POST', headers: { Authorization: authKey.scheme + ' ' + authKey.key }, contentType: 'application/json', data: JSON.stringify(linkData), }).done(function(data) { selections[selection_index]['link'] = data['url']; selectionComplete(true); }).fail(function(xhr, status, err) { logger.warn('Error creating link: ', status, err, xhr); selectionComplete(false); }); requestCountStarted += 1; }; var moveToDrop = function(selection_index) { var data = { account: 'upload_location' } if (config.upload_location_account()) { data['drop_account'] = config.upload_location_account() data['parent_id'] = config.upload_location_folder() } else if (config.upload_location_uri()) { data['drop_uri'] = config.upload_location_uri() } $.ajax({ url: config.getAccountUrl( accountId, 'storage', '/files/' + selections[selection_index].id + '/copy/?link=' + config.link + '&link_options=' + encodeURIComponent(JSON.stringify(config.link_options())) ), type: 'POST', contentType: 'application/json', headers: { Authorization: authKey.scheme + ' ' + authKey.key }, data: JSON.stringify(data), }).done(function(data) { selections[selection_index] = data; selectionComplete(true); }).fail(function() { selectionComplete(false); }); requestCountStarted += 1; } if (config.copy_to_upload_location) { // Move to upload location. for (var i=0; i<selections.length; i++) { requestsToLaunch.push({fn: moveToDrop, i: i}); } } else if (config.link) { for (var i=0; i < selections.length; i++) { processingConfirm = true; requestsToLaunch.push({fn: createLink, i: i}); } } else { explorer.view_model.postMessage('success', selections); } // assuming 'folders' or 'all' is part of what can be selected } else if (config.types.indexOf('all') != -1 || config.types.indexOf('folders') != -1) { // if no files are selected, return folder currently in // TODO: for now don't allow root folders for all sources later check // the can_upload_files attribute if (current.can_upload_files) { logger.debug('Folder selected! ', current); var clone = {}; for (var attr in current) { if (current.hasOwnProperty(attr) && attr != 'parent_obs') { clone[attr] = current[attr]; } } explorer.view_model.postMessage('success', [clone]); } else { explorer.view_model.error('This folder cannot be selected. Please choose again.'); explorer.view_model.loading(false); } } else { explorer.view_model.error('No files selected. Please select a file.'); explorer.view_model.loading(false); } }, // Quit the file explorer. cancel: function() { logger.debug('Quitting!'); explorer.lastCancelTime = new Date() // postMessage to indicate failure. explorer.view_model.postMessage('cancel'); }, postMessage: function(action, data) { var post_data = { exp_id: self.exp_id, type: 'explorer', action: action, }; if (data !== undefined) { if (['selected', 'success', 'addAccount'].indexOf(action) > -1 && (config.account_key || config.retrieve_token()) && config.user_data().trusted) { // Add in OAuth Token on success for files. var accountMap = {} ko.utils.arrayForEach(self.manager.accounts(), function(account) { accountMap[account.account] = account; }); // Separate variable for cases where it isn't an array, // to reuse code. var addKeyToData = data; var accountIdField = 'account'; if (action == 'addAccount') { addKeyToData = [data]; accountIdField = 'id'; } // Add OAuth Token ko.utils.arrayForEach(addKeyToData, function(d) { var account = accountMap[d[accountIdField]]; if (account !== undefined) { var keyIdent = 'account_key' if (config.retrieve_token()) d.bearer_token = {key: account.bearer_token} if (config.account_key) d.account_key = {key: account.account_key} } }); } post_data.data = data; } window.parent.postMessage(JSON.stringify(post_data), config.origin); }, sync: function(accounts, loadStorage) { // if loadStorage, remove local accounts and load from storage // if not loadStorage, store local accounts into storage logger.debug('syncing...'); // remove all old accounts if (loadStorage) { explorer.manager.accounts.removeAll(); } // add new accounts because data may have changed require(['models/account'], function(Account) { var i, local_data, active; for (i = 0; i < accounts.length; i++) { (function(local_data) { var created = new Account(local_data, function(acc) { // Don't allow duplicate accounts explorer.manager.removeAccount(acc.account); if (acc.connected()) { explorer.manager.accounts.push(acc); if (!active) { active = true; explorer.manager.active(explorer.manager.getByAccount(acc.account)); } if (!loadStorage) { storage.storeAccounts(config.app_id, explorer.manager.accounts(), config.services); } } // if no valid accounts from local storage are loaded if (explorer.manager.accounts().length === 0) { router.setLocation('#/accounts'); } else { router.setLocation('#/files'); } }, function(err, result) { explorer.view_model.loading(false); // if it errors on root folder metadata, we shouldn't add it if (err && err.message === 'failed to retrieve root folder') { logger.warn('failed to load account from localStorage'); explorer.manager.removeAccount(local_data.account); // store accounts storage.storeAccounts(config.app_id, explorer.manager.accounts(), config.services); // else if it errors on folder contents, we should show an error } else if (err) { logger.warn('failed to refresh filesystem', err); explorer.view_model.error('Error occurred. Please try again.'); } else { explorer.view_model.error(''); } // need to make sure on files view since we're loading asynchronously // from local storage if (first_account && explorer.view_model.current() == 'files') { router.setLocation('#/files'); first_account = false; } // need to make sure on accounts view since... ^^^ if (explorer.manager.accounts().length === 0) { router.setLocation('#/accounts'); } }); })(accounts[i]); } }); }, setLocation: function (path) { /* We override setLocation in the router, so this let's us bypass the hash actually changing. */ router.setLocation(path); }, // Request states. error: ko.observable(''), loading: ko.observable(true), localizedConfirmPopup: function(token, variables) { return confirm(localization.formatAndWrapMessage(token, variables)); }, logo_url: ko.observable(), // Accounts view model. accounts: { // List of all account objects. all: self.manager.accounts, // Current active service active: ko.pureComputed(function() { if (this.view_model.current() === 'computer') return 'computer'; return this.manager.active().service; }, self), logout: function() { explorer.manager.accounts.removeAll(); storage.removeAllAccounts(config.app_id); router.setLocation('#/accounts'); }, // Current active service name name: ko.pureComputed(function() { if (this.view_model.current() === 'computer') return 'My Computer'; return this.manager.active().account_name; }, self), // return friendly names by service friendly_name: function(service_name) { return localization.formatAndWrapMessage('servicenames/' + service_name); }, // Returns hash mapping a string service name to an array of account objects. by_service: ko.computed(function() { var accounts = this(); // gimmick to register observer with KO var output = {}; for (var i = 0; i < accounts.length; i++) { if (!(accounts[i].service in output)) { output[accounts[i].service] = []; } output[accounts[i].service].push(accounts[i]); } return output; }, self.manager.accounts), // Connect new account. connect: function(service) { // if clicking on computer, switch to computer view if (service == 'computer') { router.setLocation('#/computer'); return; } logger.debug('Account connection invoked for service: ' + service + '.'); explorer.manager.addAccount(service, { on_confirm_with_iexd: function() { explorer.view_model.addconfirm.serviceName = localization.formatAndWrapMessage('servicenames/' + service); explorer.view_model.addconfirm.serviceLogo = services().filter(function(s) { return s.id === service; })[0].logo; router.setLocation('#/addconfirm'); // position the iframe on the modal; // // note that we can't move the iframe in the DOM (e.g. to be a // child of some element in our template) because that will // force a reload, and we'll lose all existing state // --> http://stackoverflow.com/q/7434230/612279 setTimeout(function() { var button = $('#confirm-add-button'); var pos = button.offset(); $(auth.iframe).css({ top: pos.top + 'px', left: pos.left + 'px', width: button.outerWidth(), height: button.outerHeight() }).show(); }, 0); }, on_account_ready: function(account) { logger.debug('Redirecting to files view? ', first_account); // Don't allow duplicate accounts for (var i = 0; i < explorer.manager.accounts().length; i++) { var acc = explorer.manager.accounts()[i]; if (acc.account == account.account) { //Delete existing account to be overridden by new account explorer.manager.removeAccount(acc.account); } } explorer.manager.accounts.push(account); if (Object.keys(ko.toJS(explorer.manager.active)).length === 0) { explorer.manager.active(explorer.manager.getByAccount(account.account)); } // post message for account explorer.view_model.postMessage('addAccount', { id: account.account, name: account.account_name, service: account.service }); if (first_account) { explorer.view_model.loading(true); router.setLocation('#/files'); } else { router.setLocation('#/accounts'); } }, on_fs_ready: function(err, result) { if (err && error_message) { explorer.view_model.error(error_message); } else if (err) { explorer.view_model.error(err.message); } else { explorer.view_model.error(''); } if (first_account) { explorer.view_model.loading(false); first_account = false; } // store accounts storage.storeAccounts(config.app_id, explorer.manager.accounts(), config.services); } }); }, computer: function() { return config.computer && explorer.view_model.flavor() == 'chooser'; }, account_management: config.account_management, }, // addconfirm view model addconfirm: {}, // Files view model. files: { all: self.fileManager.files, // Compute breadcrumbs. breadcrumbs: ko.computed(function() { var self = this(); // gimmick to register observer with KO if (Object.keys(self).length === 0) { // check to make sure an active account is set return null; } return self.filesystem().path(); }, self.manager.active), // Return active service service: ko.computed(function() { var self = this(); return self.service; }, self.manager.active), service_friendly: ko.computed(function() { var self = this(); var name = self.service; return localization.formatAndWrapMessage('servicenames/' + name); }, self.manager.active), // Compute current working directory. cwd: ko.computed(function() { var self = this(); if (Object.keys(self).length === 0) { return null; } logger.debug('Recomputing cwd...'); return self.filesystem().cwd(); }, self.manager.active), // Relative navigation. navigate: function(file) { logger.debug('Navigating to file: ', file); var target = file; var parent = self.manager.active().filesystem().PARENT_FLAG; if (typeof file == 'string' && file == parent) { target = parent; } self.view_model.loading(true); self.manager.active().filesystem().navigate(target, function(err, result) { logger.debug('Navigation result: ', err, result); self.view_model.loading(false); if (err && error_message) { return self.view_model.error(error_message); } else if (err) { return self.view_model.error(err.message); } self.view_model.error(''); }); }, // Breadcrumb navigation. up: function(count) { logger.debug('Going up ' + count + ' directories.'); self.view_model.loading(true); self.manager.active().filesystem().up(count, function(err, result) { self.view_model.loading(false); if (err && error_message) { return self.view_model.error(error_message); } else if (err) { return self.view_model.error(err.message); } self.view_model.error(''); }); }, mkdir: function() { self.view_model.loading(true); var name = $('.new-folder-name').val(); logger.debug('New folder name', name); self.manager.active().filesystem().mkdir(name, function(err, result) { // update first entry if (err && error_message) { self.view_model.error(error_message); } else if (err) { self.view_model.error(err.message); } else { self.view_model.error(''); var dir = self.manager.active().filesystem().updatedir(result); if (dir) { self.view_model.files.navigate(dir); } } self.view_model.loading(false); }); }, newdir: function() { if (self.manager.active().filesystem().current().can_create_folders) { self.manager.active().filesystem().newdir(); } else { self.view_model.error('Sorry! Folders cannot be created in this directory'); } }, rmdir: function() { self.manager.active().filesystem().rmdir(); }, refresh: function() { logger.debug('Refreshing current directory'); self.view_model.loading(true); self.manager.active().filesystem().refresh(true, function(err, result) { self.view_model.loading(false); if (err && error_message) { return self.view_model.error(error_message); } else if (err) { return self.view_model.error(err.message); } self.view_model.error(''); }); }, sort: function(option) { self.manager.active().filesystem().sort(option); }, searchQuery: ko.observable(""), search: function() { (function(query) { if (query === "") { self.view_model.files.refresh(); return; } self.view_model.loading(true); var currentFs = explorer.manager.active().filesystem(); var s = new Search(currentFs.id, currentFs.key, query); s.search(function() { var fs = self.manager.active().filesystem(); fs.display(fs.filterChildren(s.results.objects)); self.view_model.loading(false); }, function() { self.view_model.error("The search request was not successful."); self.view_model.loading(false); }); })(self.view_model.files.searchQuery()); }, allow_newdir: config.create_folder, // Placeholder for finderSelect'd jQuery object. table: null, }, // Computer view model. computer: { }, // List of supported services. Used to render things on the accounts page. services: services, // List of friendly names service_names: service_names }; config.user_data.subscribe(function(userData) { self.view_model.logo_url(userData.logo_url); }); var setLocale = function (locale) { localization.setCurrentLocale(locale); }; // update the locale when the config changes config.locale.subscribe(setLocale); // load the default locale setLocale(config.locale()); this.view_model.files.searchQuery.extend({ rateLimit: { timeout: 250, method: "notifyWhenChangesStop" } }); this.view_model.files.searchQuery.subscribe(this.view_model.files.search, this); ko.applyBindings(this.view_model); }; // Switch views between 'accounts', 'files', and 'computer'. FileExplorer.prototype.switchViewTo = function(to) { var explorer = this; explorer.view_model.current(to); // When view is changed, the old view template is unloaded. if (to !== 'dropzone') { dropzoneLoaded = false; } if (to === 'dropzone') { var dz = $('#dropzone'); dz.on('click', function() { explorer.view_model.postMessage('dropzoneClicked'); }); // Make sure to only load the dropzone once if (!dropzoneLoaded) { var dropzone = new mOxie.FileDrop({ drop_zone: dz.get(0) }); // Because templates are re-rendered on view change, don't add // dropped files to the computer view uploader immediately. // Instead, add it to a queue that will be processed after // the router switches to the computer view. dropzone.ondrop = function(event) { explorer.view_model.postMessage('drop'); filesQueue.push(dropzone.files); router.setLocation('#/computer'); }; dropzone.init(); dropzoneLoaded = true; } } if (to !== 'addconfirm') { $(auth.iframe).hide(); } if ($("#search-query").is(":visible")) $("#search-back-button").trigger("click"); if ($('.accountsbutton')) $('.accountsbutton').dropdown('hide'); // Initialise jQuery dropdown plugin. if (to == 'files' || to == 'computer') { $('.accountsbutton').dropdown('attach', ['#account-dropdown']); // Since we're not using foundation, add click handler to 'x' $('.close').off('click'); $('.close').on('click', function(e) { // clear the error explorer.view_model.error(''); e.preventDefault(); e.stopPropagation(); }); } // Initialise infinite scroll if (to == 'files') { $("#fs-scroller").off("scrollstop"); $("#fs-scroller").on("scrollstop", function(e) { var scrolled = $(this).scrollTop(); var tableHeight = $(this).outerHeight(); var contentHeight = $("#fs-view-body").outerHeight(); // load more if ((scrolled + tableHeight) >= contentHeight) { explorer.view_model.loading(true); explorer.manager.active().filesystem().getPage(function() { explorer.view_model.loading(false); }); } }); //Search jquery actions $(".search").off('click'); $("#search-enable-button, #search-back-button").on('click', function() { $(".refresh-button, #search-back-button").toggle(); var duration = 150; if ($("#search-query").is(":visible")) { $("#search-enable-button").removeClass('search-active'); explorer.view_model.files.refresh(); //Slide along with search query $("#search-enable-button").animate({ left: "+=360" }, duration); $("#search-enable-button").animate({ left: "-=360" }, 0); $("#search-query").toggle('slide', { direction: "right" }, duration, function() { $(".breadcrumbs, .new-folder-button").toggle(); }); $("#search-query").val(""); } else{ $("#search-enable-button").addClass('search-active'); $(".new-folder-button, .breadcrumbs").toggle(); $("#search-enable-button").animate({ left: "+=360" }, 0); $("#search-enable-button").animate({ left: "-=360" }, duration); $("#search-query").toggle('slide', { direction: "right" }, duration); $("#search-query").focus() .off("keyup") .on("keyup", function(e) { if (e.keyCode == 27) { // Escape key $("#search-back-button").click(); e.stopPropagation(); } }); } }); } if (to == 'computer') { initializePlUpload(); } }; function initializePlUpload() { $(function() { var selections = []; var filtered_types = []; // if not default 'all' or 'files', add the mimetypes if ((config.types.indexOf('all') == -1 && config.types.indexOf('files') == -1) || (config.types.length != 1)) { filtered_types.push({ title: "Uploadable files", extensions: config.types.join(",") }); } var upload_url = (config.upload_location_uri() || (config.base_url + '/drop/' + config.app_id)) function formatFileObject(file) { /** * Format a file info dict to be emitted to the API. * * Returns a subset of the info (rather than returning a * Pluploadfile object) to avoid exposing internals that may * change. */ return { id: file.id, name: file.name, size: file.size, mime_type: file.type }; } // Default cancel button action. $('#cancel-button').click(function() { explorer.view_model.cancel(); }); $('#uploader').plupload({ // Required url: upload_url, // browse_button: "uploader", // Filters filters : (function() { var filters = { max_file_size: '50000mb', prevent_duplicates: false, // unique_names instead. mime_types: filtered_types }; // Don't set to 0, because it forces 0 files to be selected. // Happens even though the default is supposed to be 0. if (!config.multiselect) filters['max_file_count'] = 1; return filters; })(), // Multipart / Chunking multipart: false, multipart_params: {}, chunk_size: config.chunk_size, max_retries: 2, // Parallelize max_upload_slots: 6, // Misc // See http://www.plupload.com/docs/Frequently-Asked-Questions#when-to-use-chunking-and-when-not // for omitting flash when chunking is possible. runtimes : 'html5', // Rename files by clicking on their titles rename: true, // Unique file names // This is set to false because we use the file ID // to identify the file instead. unique_names: false, // Sort files sortable: true, // Enable ability to drag'n'drop files onto the widget (currently only HTML5 supports that) dragdrop: true, browse_button: 'custom-add', container: 'custom-add-container', // Views to activate views: { list: true, thumbs: false, // Hide thumbs active: 'list', // 'thumbs' is another possible view. }, init: { PostInit: function() { var uploader = this; // Add drag & dropped files for (i = 0; i < filesQueue.length; i++) { uploader.addFile(filesQueue[i]); } filesQueue = []; // enable the browse button $('#uploader_browse').removeAttr('disabled'); // Add pause/resume upload handler $('#upload-button').click(function() { if ($(this).text() == 'Upload') { $(this).text('Pause'); uploader.start(); explorer.view_model.loading(true); } else if ($(this).text() == 'Pause') { $(this).text('Resume'); uploader.stop(); explorer.view_model.loading(false); } else if ($(this).text() == 'Resume') { $(this).text('Pause'); uploader.start(); explorer.view_model.loading(true); } }); // Add confirmation when closing tabs during uploading process $(window).bind('beforeunload', function() { // Add confirmation if not IE or IE 11 only. if (util.isIE == false || util.ieVersion == 11) { if (uploader.total.queued > 0) { var msg = ('Are you sure you want to close this tab? You have an' + ' upload in progress.'); return msg; } } }); // Add abort upload handler $('#cancel-button').off(); $('#cancel-button').on('click', function() { var msg = ('Are you sure you want to cancel? You have an' + ' upload in progress.'); if (uploader.total.queued > 0) { uploader.stop(); if (confirm(msg)) { $('#upload-button').text('Upload'); var file_ids_to_abort = uploader.files.filter(function(f) { return $.inArray(f.status, [plupload.QUEUED, plupload.UPLOADING]) > -1; }).map(function(f) { return f.id; }); uploader.splice(); explorer.view_model.cancel(); // Abort asynchronously. window.setTimeout(function() { $.each(file_ids_to_abort, function(index, id) { var headers = {"X-Explorer-Id": explorer.id}; if (config.upload_location_account() && config.upload_location_folder()) { // A specific Upload Location is being used. headers['X-Drop-Account'] = config.upload_location_account(); headers['X-Drop-Folder'] = config.upload_location_folder(); } // Add a query parameter. var parser = document.createElement('a'); parser.href = upload_url parser.search += "file_id=" + id $.ajax({ url: parser.href, type: 'DELETE', headers: headers, }); }); }, 0); } else { uploader.start(); } } else { explorer.view_model.cancel(); } }); }, BeforeUpload: function(up, file) { /** * Called just before a file begins to upload. Called once * per file being uploaded. */ up.settings.multipart_params = up.settings.multipart_params || {}; up.settings.multipart_params['file_id'] = file.id; up.settings.multipart_params['file_size'] = file.size; if (config.link) { up.settings.multipart_params['link'] = true; up.settings.multipart_params['link_options'] = JSON.stringify(config.link_options()); } up.settings.headers = up.settings.headers || {}; // Not using up.id because it changes with every plUpload(). up.settings.headers["X-Explorer-Id"] = explorer.id; if (config.upload_location_account() && config.upload_location_folder()) { // A specific Upload Location is being used. up.settings.headers['X-Drop-Account'] = config.upload_location_account(); up.settings.headers['X-Drop-Folder'] = config.upload_location_folder(); } explorer.view_model.error(''); explorer.view_model.postMessage('startFileUpload', formatFileObject(file)); }, FileUploaded: function(up, file, info) { /** * Called just after a file has been successfully uploaded to * Kloudless. Called once per file being uploaded. */ if (info.status == 200 || info.status == 201) { var responseData = JSON.parse(info.response); if (Object.keys(responseData).length > 5) { selections.push(responseData); } var data = formatFileObject(file); data.metadata = responseData; explorer.view_model.postMessage('finishFileUpload', data); } }, Error: function(up, args) { // file extension error if (args.code == plupload.FILE_EXTENSION_ERROR) { var filter_msg = 'Please upload files of the following types: '; filter_msg += config.types.join(", ") + '.'; explorer.view_model.error(filter_msg); } else if (args.code == plupload.HTTP_ERROR) { logger.error("Error uploading file '" + args.file.name + "': " + args.response); if (config.uploads_pause_on_error()) { explorer.view_model.error( "Uploading has been paused due to errors. Resume to retry.") // Reset the % loaded for the file in the UI // plupload only resets file.loaded in handleError(), // so we need to fix file.percent. args.file.percent = Math.ceil(args.file.loaded / args.file.size * 100); args.file.status = plupload.UPLOADING; up.trigger('UploadFile', args.file); setTimeout(function() { // Update the UI after re-queueing the file to allow the file to be // deleted from the queue if needed. args.file.status = plupload.QUEUED; up.trigger('UploadFile', args.file); }, 50); $('#upload-button').click(); // Pause the upload. } else { up.removeFile(args.file); up.stop(); up.start(); } } }, UploadComplete: function(files) { $('#upload-button').text('Upload'); explorer.view_model.postMessage('success', selections); selections = []; this.splice(); } } }); }); } FileExplorer.prototype.cleanUp = function() { // File Explorer will close. Clean up. var self = this; processingConfirm = false; if ($("#search-query").is(":visible")) $("#search-back-button").click(); self.view_model.loading(false); self.view_model.error(''); if (self.view_model.files.table) { self.view_model.files.table.finderSelect('unHighlightAll'); } self.fileManager.files.removeAll(); // Saver }; ko.bindingHandlers.finderSelect = { init: function(element, valueAccessor) { var selector = $(element).finderSelect({ children: 'tr[data-type="file"]', enableClickDrag: config.multiselect, enableShiftClick: config.multiselect, enableCtrlClick: config.multiselect, enableSelectAll: config.multiselect, }); var files = ko.unwrap(valueAccessor()); files.table = selector; }, update: function(element) { $(element).finderSelect('update'); } }; // Explorer initialisation. var explorer = new FileExplorer(); // TODO: we can display err.message if the new error handling is deployed // for now use default error message var error_message = "Error! Please try again or contact support."; // Router. var first_account = true; var router = sammy(function() { var self = this; // Override setLocation to disable history modifications. this.disable_push_state = true; this.setLocation = function (path) { self.runRoute('get', path); } /* * Routes */ // Switch to the accounts page. this.get('#/accounts', function() { logger.debug('Accounts page requested.'); explorer.switchViewTo('accounts'); }); // Reconnect an erroneously disconnected account. // WARNING: THIS HAS NOT YET BEEN IMPLEMENTED. this.get('#/account/reconnect/:id', function() { logger.debug('Account reconnection invoked for id: ' + this.params.id + '.'); }); // Disconnect an account. this.get('#/account/disconnect/:id', function() { logger.debug('Account disconnection invoked for id: ' + this.params.id + '.'); // Find account var accounts = explorer.manager.accounts(); var account_data = {}; for (var i = 0; i < accounts.length; i++) { if (accounts[i].account == this.params.id) { account_data = accounts[i]; break; } } if (Object.keys(account_data).length === 0) { logger.warn('Account failed to remove'); alert('Error occurred. Please try again!'); return; } var request = $.ajax({ url: config.getAccountUrl(account_data.account), type: 'DELETE', headers: { Authorization: account_data.key.scheme + ' ' + account_data.key.key } }).done(function(data) { explorer.manager.removeAccount(account_data.account); // post message for account explorer.view_model.postMessage('deleteAccount', account_data.account); // store accounts storage.storeAccounts(config.app_id, explorer.manager.accounts(), config.services); }).fail(function(xhr, status, err) { logger.warn('Account failed to remove'); alert('Error occurred. Please try again!'); }).always(function() { request = null; }); }); // Switch to the files page. this.get('#/files', function() { logger.debug('File view requested.'); explorer.switchViewTo('files'); }); // Switch to the files view of a particular account. // TODO: test. this.get('#/files/:account', function() { logger.debug('Switching to files of account: ' + this.params.account + '.'); explorer.switchViewTo('files'); explorer.manager.active(explorer.manager.getByAccount(this.params.account)); }); // Switch to the computer view this.get('#/computer', function() { logger.debug('Switching to computer view'); explorer.switchViewTo('computer'); }); // Switch to the dropzone view this.get('#/dropzone', function() { explorer.switchViewTo('dropzone'); }); // Confirm add account button this.get('#/addconfirm', function() { explorer.switchViewTo('addconfirm'); }); /* * Additional initialization steps. */ // Default to the accounts page if no accounts in local storage // storage.removeAllAccounts(config.app_id); var accounts = storage.loadAccounts(config.app_id, config.services); logger.debug(accounts); if (accounts.length === 0) { this.get('#/', function(ctx) { router.setLocation('#/accounts'); }); } else { // Load from local storage or configuration this.get('#/', function(ctx) { explorer.view_model.sync(accounts, true); }); } }); // Expose hooks for debugging. if (config.debug) { window.explorer = explorer; window.ko = ko; window.router = router; } /* * Message Event listener, dispatch and handlers. * TODO: Move to separate module? */ // Initialise to '#/' route. window.addEventListener('message', function(message) { logger.debug('Explorer hears message: ', message.data); if (message.origin !== config.origin) { return; } var contents = JSON.parse(message.data); // TODO: future config options if (contents.action == 'INIT') { dataMessageHandler(contents.data) if (startView && startView !== 'accounts') { router.run('#/' + startView); } else { router.run('#/'); } } else if (contents.action == 'DATA') { dataMessageHandler(contents.data); } else if (contents.action == 'CLOSING') { explorer.cleanUp(); } }); function dataMessageHandler(data) { // Used to initialize the explorer with data and config options. // Can also be used to update config options. /* * NOTE: This code is bad practice. config.flavor should be an observable * that is subscribed to by any methods wanting to be notified of a change. * TODO: Change this. */ if (!data) { logger.error("dataMessageHandler: No data found to configure with.") return } // Differentiate between saver and chooser // Check the flavor on init call if (data.flavor) { // refresh and go back to accounts if going from saver to chooser // or vice versa if (config.flavor !== data.flavor) { logger.debug('SWITCHING FLAVORS'); router.setLocation('#/accounts'); } config.flavor = data.flavor; explorer.view_model.flavor(config.flavor); } if (data.flavor == 'saver') { // Add files to fileManager if (data.files && data.files.length > 0) { // first clear all files. explorer.fileManager.files.removeAll(); for (var i = 0; i < data.files.length; i++) { var file = data.files[i]; explorer.fileManager.add(file.url, file.name); } } // Remove computer if (config.computer && services()[0].id == 'computer') { services.shift(); } } else if (data.flavor == 'chooser') { // Add computer if (config.computer && services()[0].id != 'computer') { services.unshift({ id: 'computer', name: 'My Computer', logo: 'https://s3-us-west-2.amazonaws.com/static-assets.kloudless.com/webapp/sources/computer.png' }); } // Default to computer view if account management is disabled and no // tokens are provided. if (config.computer && !config.account_management() && !(data.options && data.options.tokens && data.options.tokens.length > 0)) { router.setLocation('#/computer'); } } else if (data.flavor == 'dropzone') { router.setLocation('#/dropzone'); } // Primary way of updating config options if (data.options) { config.update(data.options); } // Call sync if frame has already been initialized and there are differences // between storage and current accounts if (explorer.manager.accounts().length !== 0) { var accounts = storage.loadAccounts(config.app_id, config.services); var account_ids = {}; var local_accounts = explorer.manager.accounts(); var i, different = false; for (i = 0; i < accounts.length; i++) { var account = accounts[i]; account_ids[account.account] = true; } for (i = 0; i < local_accounts.length; i++) { var local_account = local_accounts[i]; if (! local_account.account in account_ids) { different = true; break; } } // logger.debug(different || accounts.length != local_accounts.length); if (different || accounts.length != local_accounts.length) { // Call asynchronously to give other options some time to load. window.setTimeout(function () { explorer.view_model.sync(accounts, true); }, 0); } } /* * Options */ // account key and token data if (data.options && data.options.keys) { config.api_version = 'v0'; window.setTimeout(function () { explorer.view_model.sync( data.options.keys.map(function (k) { return {key: k, scheme: 'AccountKey'}; }), true); }, 0); } if (data.options && data.options.tokens) { window.setTimeout(function () { explorer.view_model.sync( data.options.tokens.map(function (k) { return {key: k, scheme: 'Bearer'}; }), true); }, 0); } if (config.computer && !loadedDropConfig && !config.upload_location_uri()) { // Looking up chunk size. Since the drop location doesn't really // change we look it up based on that. The /drop end point for the // API returns the chunk size for that drop location. $.ajax({ method: 'GET', url: config.base_url + '/drop/' + config.app_id, beforeSend: function(xhr) { if (config.upload_location_account()) { xhr.setRequestHeader('X-Drop-Account', config.upload_location_account()); xhr.setRequestHeader('X-Drop-Folder', config.upload_location_folder()); } }, }).done(function(drop_information) { config.chunk_size = drop_information.chunk_size; loadedDropConfig = true; }).fail(function() { // Disable computer if no drop location is set. if (config.computer && services()[0].id == 'computer') { services.shift(); } config.computer = false; }); } } // This signal is placed last and indicates all the JS has loaded // and events can be received. explorer.view_model.postMessage('load'); }); })();
/* eslint no-console: 0 */ import path from 'path'; import express from 'express'; import webpack from 'webpack'; import webpackMiddleware from 'webpack-dev-middleware'; import webpackHotMiddleware from 'webpack-hot-middleware'; import config from './webpack.config.js'; const isProduction = process.env.NODE_ENV === 'production'; const port = isProduction ? process.env.PORT : 3000; const app = express(); const indexHtml = path.join(__dirname, 'dist/index.html'); if (!isProduction) { const compiler = webpack(config); const middleware = webpackMiddleware(compiler, { publicPath: config.output.publicPath, contentBase: 'src', stats: { colors: true, hash: false, timings: true, chunks: false, chunkModules: false, modules: false, }, }); app.use(middleware); app.use(webpackHotMiddleware(compiler)); app.get('*', function response(req, res) { res.write(middleware.fileSystem.readFileSync(indexHtml)); res.end(); }); } else { app.use(express.static(__dirname + '/dist')); app.get('*', function response(req, res) { res.sendFile(indexHtml); }); } app.listen(port, '127.0.0.1', function onStart(err) { if (err) { console.log(err); } console.info('==> Listening on port %s. Open up http://127.0.0.1:%s/ in your browser.', port, port); });
const express = require('express'); const app = express(); app.use(require('./usuario')); app.use(require('./login')); app.use(require('./categoria')); app.use(require('./producto')); app.use(require('./upload')); app.use(require('./imagenes')); module.exports = app;
(window.webpackJsonp=window.webpackJsonp||[]).push([[214],{278:function(e,t,n){"use strict";n.r(t),n.d(t,"frontMatter",(function(){return s})),n.d(t,"metadata",(function(){return o})),n.d(t,"rightToc",(function(){return c})),n.d(t,"default",(function(){return d}));var a=n(3),i=n(7),r=(n(0),n(447)),s={id:"openid-connect-social-sign-in-oauth2",title:"Social Sign In with OpenID Connect and OAuth2"},o={unversionedId:"self-service/flows/user-login-user-registration/openid-connect-social-sign-in-oauth2",id:"version-v0.3/self-service/flows/user-login-user-registration/openid-connect-social-sign-in-oauth2",isDocsHomePage:!1,title:"Social Sign In with OpenID Connect and OAuth2",description:"Please read the",source:"@site/versioned_docs/version-v0.3/self-service/flows/user-login-user-registration/openid-connect-social-sign-in-oauth2.mdx",slug:"/self-service/flows/user-login-user-registration/openid-connect-social-sign-in-oauth2",permalink:"/kratos/docs/v0.3/self-service/flows/user-login-user-registration/openid-connect-social-sign-in-oauth2",editUrl:"https://github.com/ory/kratos/edit/master/docs/versioned_docs/version-v0.3/self-service/flows/user-login-user-registration/openid-connect-social-sign-in-oauth2.mdx",version:"v0.3",lastUpdatedBy:"aeneasr",lastUpdatedAt:1600065426,sidebar:"version-v0.3/docs",previous:{title:"Username or Email and Password",permalink:"/kratos/docs/v0.3/self-service/flows/user-login-user-registration/username-email-password"},next:{title:"User Settings",permalink:"/kratos/docs/v0.3/self-service/flows/user-settings"}},c=[{value:"Registration",id:"registration",children:[]},{value:"Login",id:"login",children:[]},{value:"Security and Defenses",id:"security-and-defenses",children:[{value:"Account Enumeration",id:"account-enumeration",children:[]}]}],l={rightToc:c};function d(e){var t=e.components,n=Object(i.a)(e,["components"]);return Object(r.b)("wrapper",Object(a.a)({},l,n,{components:t,mdxType:"MDXLayout"}),Object(r.b)("div",{className:"admonition admonition-tip alert alert--success"},Object(r.b)("div",Object(a.a)({parentName:"div"},{className:"admonition-heading"}),Object(r.b)("h5",{parentName:"div"},Object(r.b)("span",Object(a.a)({parentName:"h5"},{className:"admonition-icon"}),Object(r.b)("svg",Object(a.a)({parentName:"span"},{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"16",viewBox:"0 0 12 16"}),Object(r.b)("path",Object(a.a)({parentName:"svg"},{fillRule:"evenodd",d:"M6.5 0C3.48 0 1 2.19 1 5c0 .92.55 2.25 1 3 1.34 2.25 1.78 2.78 2 4v1h5v-1c.22-1.22.66-1.75 2-4 .45-.75 1-2.08 1-3 0-2.81-2.48-5-5.5-5zm3.64 7.48c-.25.44-.47.8-.67 1.11-.86 1.41-1.25 2.06-1.45 3.23-.02.05-.02.11-.02.17H5c0-.06 0-.13-.02-.17-.2-1.17-.59-1.83-1.45-3.23-.2-.31-.42-.67-.67-1.11C2.44 6.78 2 5.65 2 5c0-2.2 2.02-4 4.5-4 1.22 0 2.36.42 3.22 1.19C10.55 2.94 11 3.94 11 5c0 .66-.44 1.78-.86 2.48zM4 14h5c-.23 1.14-1.3 2-2.5 2s-2.27-.86-2.5-2z"})))),"Before you start")),Object(r.b)("div",Object(a.a)({parentName:"div"},{className:"admonition-content"}),Object(r.b)("p",{parentName:"div"},"Please read the\n",Object(r.b)("a",Object(a.a)({parentName:"p"},{href:"/kratos/docs/v0.3/concepts/credentials/openid-connect-oidc-oauth2"}),"OpenID Connect / OAuth2 Credentials Documentation"),"\nand ",Object(r.b)("a",Object(a.a)({parentName:"p"},{href:"/kratos/docs/v0.3/self-service/flows/user-login-user-registration"}),"identity Login and Registration Documentation")," first."))),Object(r.b)("p",null,"The Social Sign In Strategy enables you to use"),Object(r.b)("ul",null,Object(r.b)("li",{parentName:"ul"},Object(r.b)("a",Object(a.a)({parentName:"li"},{href:"http://github.com/"}),"GitHub"),";"),Object(r.b)("li",{parentName:"ul"},Object(r.b)("a",Object(a.a)({parentName:"li"},{href:"https://developer.apple.com/sign-in-with-apple/"}),"Apple"),";"),Object(r.b)("li",{parentName:"ul"},Object(r.b)("a",Object(a.a)({parentName:"li"},{href:"https://developers.google.com/identity/sign-in/web/sign-in"}),"Google"),";"),Object(r.b)("li",{parentName:"ul"},Object(r.b)("a",Object(a.a)({parentName:"li"},{href:"https://developers.facebook.com/docs/facebook-login/"}),"Facebook"),";"),Object(r.b)("li",{parentName:"ul"},Object(r.b)("a",Object(a.a)({parentName:"li"},{href:"https://www.ory.sh/hydra"}),"ORY Hydra"),";"),Object(r.b)("li",{parentName:"ul"},Object(r.b)("a",Object(a.a)({parentName:"li"},{href:"https://www.keycloak.org"}),"Keycloak"),";"),Object(r.b)("li",{parentName:"ul"},"and every other OpenID Connect Certified Provider")),Object(r.b)("p",null,"as the Identity Provider. It implements several flows, specifically\n",Object(r.b)("a",Object(a.a)({parentName:"p"},{href:"/kratos/docs/v0.3/self-service/flows/user-login-user-registration"}),"identity Login and identity Registration"),"\nand ",Object(r.b)("a",Object(a.a)({parentName:"p"},{href:"/kratos/docs/v0.3/self-service/flows/user-settings"}),"identity Settings"),"."),Object(r.b)("p",null,"Because OAuth2 and OpenID Connect (OIDC) require the identity to interact with a browser,\nthis strategy does not work with API-only flows. You cannot log in or sign up a identity\nusing this strategy"),Object(r.b)("ul",null,Object(r.b)("li",{parentName:"ul"},"with REST API or AJAX requests only;"),Object(r.b)("li",{parentName:"ul"},"without a browser.")),Object(r.b)("p",null,'This document summarizes exemplary request payloads for performing "Sign in with ..." flows\nusing the identity login and registration flow with the ',Object(r.b)("inlineCode",{parentName:"p"},"oidc")," strategy."),Object(r.b)("p",null,"ORY Kratos automatically converts registration to login flows and vice versa. A user\nthat's already signed up with his/her Google account will be logged in even if you\ninitiate a registration request."),Object(r.b)("div",{className:"admonition admonition-info alert alert--info"},Object(r.b)("div",Object(a.a)({parentName:"div"},{className:"admonition-heading"}),Object(r.b)("h5",{parentName:"div"},Object(r.b)("span",Object(a.a)({parentName:"h5"},{className:"admonition-icon"}),Object(r.b)("svg",Object(a.a)({parentName:"span"},{xmlns:"http://www.w3.org/2000/svg",width:"14",height:"16",viewBox:"0 0 14 16"}),Object(r.b)("path",Object(a.a)({parentName:"svg"},{fillRule:"evenodd",d:"M7 2.3c3.14 0 5.7 2.56 5.7 5.7s-2.56 5.7-5.7 5.7A5.71 5.71 0 0 1 1.3 8c0-3.14 2.56-5.7 5.7-5.7zM7 1C3.14 1 0 4.14 0 8s3.14 7 7 7 7-3.14 7-7-3.14-7-7-7zm1 3H6v5h2V4zm0 6H6v2h2v-2z"})))),"info")),Object(r.b)("div",Object(a.a)({parentName:"div"},{className:"admonition-content"}),Object(r.b)("p",{parentName:"div"},'It is very important to add the "session" hook to the after oidc registration\nhooks. Otherwise your users need to use the login flow again to be able to get a\nsession.'),Object(r.b)("pre",{parentName:"div"},Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-yaml",metastring:'title="path/to/my/kratos/config.yml"',title:'"path/to/my/kratos/config.yml"'}),"# $ kratos -c path/to/my/kratos/config.yml serve\nselfservice:\n registration:\n after:\n oidc:\n hooks:\n - hook: session\n")))),Object(r.b)("p",null,"Here we use a configuration with 3 providers:"),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-yaml",metastring:'title="path/to/my/kratos/config.yml"',title:'"path/to/my/kratos/config.yml"'}),"selfservice:\n strategies:\n oidc:\n enabled: true\n config:\n providers:\n - id: hydra\n # provider, client_id, issuer_url, scope, ...\n - id: google\n # provider, client_id, issuer_url, scope, ...\n - id: github\n # provider, client_id, issuer_url, scope, ...\n")),Object(r.b)("h2",{id:"registration"},"Registration"),Object(r.b)("p",null,"Redirecting the browser to the ",Object(r.b)("a",Object(a.a)({parentName:"p"},{href:"/kratos/docs/v0.3/self-service/flows/user-login-user-registration#user-login-and-user-registration-process-sequence"}),"Self-Service Login and Registration Endpoint"),"\ninitiates the flow. If the ",Object(r.b)("inlineCode",{parentName:"p"},"oidc")," strategy is enabled and at least one provider is configued,\nthe Registration Request Response Payload will include an ",Object(r.b)("inlineCode",{parentName:"p"},"oidc")," method. The method contains different providers,\nbased on your OpenID Connect Provider configuration:"),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-json5",metastring:'title="$ curl http://<kratos-admin>/self-service/browser/flows/requests/registration?request=54a9f113-3a7b-4cb8-a553-f072aa4e1622"',title:'"$',curl:!0,"http://<kratos-admin>/self-service/browser/flows/requests/registration?request":'54a9f113-3a7b-4cb8-a553-f072aa4e1622"'}),'{\n "id": "54a9f113-3a7b-4cb8-a553-f072aa4e1622",\n "expires_at": "2020-05-15T11:04:09.342537Z",\n "issued_at": "2020-05-15T10:04:09.342537Z",\n "request_url": "http://127.0.0.1:4433/self-service/browser/flows/registration",\n "methods": {\n "oidc": {\n "method": "oidc",\n "config": {\n "action": "http://127.0.0.1:4455/.ory/kratos/public/self-service/browser/flows/strategies/oidc/auth/54a9f113-3a7b-4cb8-a553-f072aa4e1622",\n "method": "POST",\n "fields": [\n {\n "name": "csrf_token",\n "type": "hidden",\n "required": true,\n "value": "J9blMEwxnz6cL7rgcpu1vthggR13RH+7YMS77GBPn9yo7FqPNc9tTsvCQhu7Cu8AAREWXZF2FiaPia26SfrPBA=="\n },\n {\n "name": "provider",\n "type": "submit",\n "value": "hydra"\n },\n {\n "name": "provider",\n "type": "submit",\n "value": "google"\n },\n {\n "name": "provider",\n "type": "submit",\n "value": "github"\n }\n ]\n }\n },\n "password": {\n "method": "password",\n "config": {\n "action": "http://127.0.0.1:4455/.ory/kratos/public/self-service/browser/flows/registration/strategies/password?request=54a9f113-3a7b-4cb8-a553-f072aa4e1622",\n "method": "POST",\n "fields": [\n {\n "name": "csrf_token",\n "type": "hidden",\n "required": true,\n "value": "J9blMEwxnz6cL7rgcpu1vthggR13RH+7YMS77GBPn9yo7FqPNc9tTsvCQhu7Cu8AAREWXZF2FiaPia26SfrPBA=="\n },\n {\n "name": "password",\n "type": "password",\n "required": true\n },\n {\n "name": "traits.email",\n "type": "email"\n },\n {\n "name": "traits.website",\n "type": "url"\n }\n ]\n }\n }\n }\n}\n')),Object(r.b)("p",null,"The next step depends on your Identity Traits JSON Schema and your JsonNet code. We're using the following\nin this example:"),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-jsonnet",metastring:'title="path/to/identity.traits.json.schema',title:'"path/to/identity.traits.json.schema'}),'{\n "$id": "https://schemas.ory.sh/presets/kratos/quickstart/email-password/identity.schema.json",\n "$schema": "http://json-schema.org/draft-07/schema#",\n "title": "Person",\n "type": "object",\n "properties": {\n "email": {\n "type": "string",\n "format": "email",\n "title": "E-Mail",\n "minLength": 3,\n "ory.sh/kratos": {\n "credentials": {\n "password": {\n "identifier": true\n }\n }\n }\n },\n "website": {\n "type": "string",\n "format": "uri",\n "minLength": 10\n }\n },\n "required": [\n "email",\n "website"\n ],\n "additionalProperties": false\n}\n')),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-jsonnet",metastring:'title="path/to/google.jsonnet',title:'"path/to/google.jsonnet'}),"local claims = std.extVar('claims');\n\nif std.length(claims.sub) == 0 then\n error 'claim sub not set'\nelse\n {\n identity: {\n traits: {\n email: claims.sub,\n [if \"website\" in claims then \"website\" else null]: claims.website,\n },\n },\n }\n")),Object(r.b)("p",null,"This implies that the identity has a required attributes ",Object(r.b)("inlineCode",{parentName:"p"},"email")," and ",Object(r.b)("inlineCode",{parentName:"p"},"website"),". When singing in using Google,\nwe take the ",Object(r.b)("inlineCode",{parentName:"p"},"sub")," and ",Object(r.b)("inlineCode",{parentName:"p"},"website")," claim are used to hydrate these fields. If they're missing or invalid (because e.g. not an\nemail, the user\nreturns to the registration form with additional fields that need to be filled out. Please note that these claims\nare just examples, Google doesn't actually use email addresses in ",Object(r.b)("inlineCode",{parentName:"p"},"sub")," fields and also does not include the ",Object(r.b)("inlineCode",{parentName:"p"},"website"),"\nclaim:"),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-json5",metastring:'title="$ curl http://<kratos-admin>/self-service/browser/flows/requests/registration?request=54a9f113-3a7b-4cb8-a553-f072aa4e1622"',title:'"$',curl:!0,"http://<kratos-admin>/self-service/browser/flows/requests/registration?request":'54a9f113-3a7b-4cb8-a553-f072aa4e1622"'}),'{\n "id": "54a9f113-3a7b-4cb8-a553-f072aa4e1622",\n // ...\n "active": "oidc", // <-- this is now set\n "methods": {\n "oidc": {\n "method": "oidc",\n "config": {\n "action": "http://127.0.0.1:4455/.ory/kratos/public/self-service/browser/flows/strategies/oidc/auth/54a9f113-3a7b-4cb8-a553-f072aa4e1622",\n "method": "POST",\n // Errors can be included here, for example:\n // "errors": [\n // {\n // "message": "Authentication failed because no id_token was returned. Please accept the \\"openid\\" permission and try again."\n // }\n // ]\n "fields": [\n {\n "name": "csrf_token",\n "type": "hidden",\n "required": true,\n "value": "A84oYSplXqtJTkhSipZc/2+tFXCN2gzWAfhmoK049FKM9JfeU5us2x6jsKlDBwZBttyCMGvoZUvutXD2hI2kig=="\n },\n {\n "name": "traits.email",\n "type": "text",\n "value": "superuser@ory.sh"\n },\n {\n "name": "traits.website",\n "type": "",\n "errors": [\n {\n "message": "missing properties: \\"website\\"" // <-- because "website" was not set, the user has to fill it out manually.\n }\n ]\n },\n {\n "name": "provider",\n "type": "submit",\n "value": "google"\n }\n ]\n }\n },\n }\n}\n')),Object(r.b)("h2",{id:"login"},"Login"),Object(r.b)("p",null,"Redirecting the browser to the ",Object(r.b)("a",Object(a.a)({parentName:"p"},{href:"/kratos/docs/v0.3/self-service/flows/user-login-user-registration#user-login-and-user-registration-process-sequence"}),"Self-Service Login and Registration Endpoint"),"\ninitiates the flow. If the ",Object(r.b)("inlineCode",{parentName:"p"},"oidc")," strategy is enabled and at least one provider is configued,\nthe Login Request Response Payload will include an ",Object(r.b)("inlineCode",{parentName:"p"},"oidc")," method. The method contains different providers,\nbased on your OpenID Connect Provider configuration:"),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-json5",metastring:'title="$ curl http://<kratos-admin>/self-service/browser/flows/requests/login?request=a1c78949-1436-44bd-93ae-a57836be01c7"',title:'"$',curl:!0,"http://<kratos-admin>/self-service/browser/flows/requests/login?request":'a1c78949-1436-44bd-93ae-a57836be01c7"'}),'{\n "id": "a1c78949-1436-44bd-93ae-a57836be01c7",\n "expires_at": "2020-05-15T10:49:58.770828Z",\n "issued_at": "2020-05-15T09:49:58.770829Z",\n "request_url": "http://127.0.0.1:4433/self-service/browser/flows/login",\n "methods": {\n // password: ...\n "oidc": {\n "method": "oidc",\n "config": {\n "action": "http://127.0.0.1:4455/.ory/kratos/public/self-service/browser/flows/strategies/oidc/auth/a1c78949-1436-44bd-93ae-a57836be01c7",\n "method": "POST",\n "fields": [\n {\n "name": "csrf_token",\n "type": "hidden",\n "required": true,\n "value": "/Q85ogDm+Hv7D+ca7DUXYBRqmkTdMiIzXrZxt8IXgFHd7rkc8+U1WoWNmScDfJ8/cEju/hUIko5N48GR3rMfag=="\n },\n {\n "name": "provider",\n "type": "submit",\n "value": "hydra"\n },\n {\n "name": "provider",\n "type": "submit",\n "value": "google"\n },\n {\n "name": "provider",\n "type": "submit",\n "value": "github"\n }\n ]\n }\n }\n },\n "forced": false\n}\n')),Object(r.b)("p",null,"The only form validation error that can happen during this flow is that the ID Token is missing\nbecause the user did not authorize the ",Object(r.b)("inlineCode",{parentName:"p"},"openid")," grant (does not apply for ",Object(r.b)("inlineCode",{parentName:"p"},"provider: github"),"):"),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-json5",metastring:'title="$ curl http://<kratos-admin>/self-service/browser/flows/requests/login?request=a1c78949-1436-44bd-93ae-a57836be01c7"',title:'"$',curl:!0,"http://<kratos-admin>/self-service/browser/flows/requests/login?request":'a1c78949-1436-44bd-93ae-a57836be01c7"'}),'{\n "id": "a1c78949-1436-44bd-93ae-a57836be01c7",\n // expires_at, ...\n "active": "oidc", // <- this is now set!\n "methods": {\n // password: ...\n "oidc": {\n "method": "oidc",\n "config": {\n "action": "http://127.0.0.1:4455/.ory/kratos/public/self-service/browser/flows/strategies/oidc/auth/a1c78949-1436-44bd-93ae-a57836be01c7",\n "method": "POST",\n "errors": [\n {\n "message": "Authentication failed because no id_token was returned. Please accept the \\"openid\\" permission and try again."\n }\n ],\n "fields": [\n {\n "name": "csrf_token",\n "type": "hidden",\n "required": true,\n "value": "viM0pQKXUIthwPklREm/86pdIg3d8CWJOzGOiHtrCW4xGYsae2mi+zYtAd6N2OVNcyy1TTvCTBTUfJjeUt5Ztg=="\n },\n {\n "name": "provider",\n "type": "submit",\n "value": "hydra"\n },\n {\n "name": "provider",\n "type": "submit",\n "value": "google"\n },\n {\n "name": "provider",\n "type": "submit",\n "value": "github"\n }\n ]\n }\n }\n },\n "forced": false\n}\n')),Object(r.b)("p",null,"The flow completes otherwise."),Object(r.b)("h2",{id:"security-and-defenses"},"Security and Defenses"),Object(r.b)("h3",{id:"account-enumeration"},"Account Enumeration"),Object(r.b)("p",null,"Scenario: In some cases you might want to use the email address returned by e.g.\nthe GitHub profile to be added to your identity's account. You might also want to use\nit as an email + password identifier so that the identity is able to log in\nwith a password as well. An attacker is able to exploit that by creating a social\nprofile on another site (e.g. Google) and use the victims email address to set it up\n(this only works when the victim does not yet have an account with that email at Google).\nThe attacker can then use that \"spoofed\" social profile to try and sign up with your ORY Kratos\ninstallation. Because the victim's email address is already known to ORY Kratos, the\nattacker might be able to observe the behavior (e.g. seeing an error page) and come\nto the conclusion that the victim already has an account at the website."),Object(r.b)("p",null,"Mitigation: This attack surface is rather small and requires a lot of effort, including\nforging an e.g. Google profile, and can fail at several stages. To completely mitigate\nany chance of that happening, only accept email addresses that are marked as verified\nin your Jsonnet code:"),Object(r.b)("pre",null,Object(r.b)("code",Object(a.a)({parentName:"pre"},{className:"language-json",metastring:'title="contrib/quickstart/kratos/email-password/oidc.github.jsonnet"',title:'"contrib/quickstart/kratos/email-password/oidc.github.jsonnet"'}),'local claims = {\n email_verified: false\n} + std.extVar(\'claims\');\n\n{\n identity: {\n traits: {\n // Allowing unverified email addresses enables account\n // enumeration attacks, especially if the value is used for\n // e.g. verification or as a password login identifier.\n //\n // Therefore we only return the email if it (a) exists and (b) is marked verified\n // by GitHub.\n [if "email_primary" in claims && claims.email_verified then "email" else null]: claims.email_primary,\n },\n },\n}\n')))}d.isMDXComponent=!0},447:function(e,t,n){"use strict";n.d(t,"a",(function(){return u})),n.d(t,"b",(function(){return m}));var a=n(0),i=n.n(a);function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function s(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,a)}return n}function o(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?s(Object(n),!0).forEach((function(t){r(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):s(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function c(e,t){if(null==e)return{};var n,a,i=function(e,t){if(null==e)return{};var n,a,i={},r=Object.keys(e);for(a=0;a<r.length;a++)n=r[a],t.indexOf(n)>=0||(i[n]=e[n]);return i}(e,t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);for(a=0;a<r.length;a++)n=r[a],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}var l=i.a.createContext({}),d=function(e){var t=i.a.useContext(l),n=t;return e&&(n="function"==typeof e?e(t):o(o({},t),e)),n},u=function(e){var t=d(e.components);return i.a.createElement(l.Provider,{value:t},e.children)},b={inlineCode:"code",wrapper:function(e){var t=e.children;return i.a.createElement(i.a.Fragment,{},t)}},p=i.a.forwardRef((function(e,t){var n=e.components,a=e.mdxType,r=e.originalType,s=e.parentName,l=c(e,["components","mdxType","originalType","parentName"]),u=d(n),p=a,m=u["".concat(s,".").concat(p)]||u[p]||b[p]||r;return n?i.a.createElement(m,o(o({ref:t},l),{},{components:n})):i.a.createElement(m,o({ref:t},l))}));function m(e,t){var n=arguments,a=t&&t.mdxType;if("string"==typeof e||a){var r=n.length,s=new Array(r);s[0]=p;var o={};for(var c in t)hasOwnProperty.call(t,c)&&(o[c]=t[c]);o.originalType=e,o.mdxType="string"==typeof e?e:a,s[1]=o;for(var l=2;l<r;l++)s[l]=n[l];return i.a.createElement.apply(null,s)}return i.a.createElement.apply(null,n)}p.displayName="MDXCreateElement"}}]);
/** * Tools * Cassius - https://github.com/sirDonovan/Cassius * * This file contains functions that are useful globally. * * @license MIT license */ 'use strict'; class Tools { constructor() { this.data = {}; } loadData() { this.data.pokedex = require('./data/pokedex.js').BattlePokedex; this.data.moves = require('./data/moves.js').BattleMovedex; this.data.items = require('./data/items.js').BattleItems; this.data.abilities = require('./data/abilities.js').BattleAbilities; this.data.learnsets = require('./data/learnsets.js').BattleLearnsets; this.data.locations = require('./data/locations.js').BattleLocations; this.data.characters = require('./data/characters.js').BattleCharacters; this.data.battle = require('./data/formats-data.js').BattleFormatsData; this.data.typeChart = require('./data/effect.js').BattleEffectiveness; this.data.convertType = require('./data/effect.js').convertType; } toId(text) { if (!text) return ''; if (text.id) text = text.id; let type = typeof text; if (type !== 'string') { if (type === 'number') { text = '' + text; } else { return ''; } } return text.toLowerCase().replace(/[^a-z0-9]/g, ''); } toName(text) { if (!text) return ''; if (text.name) text = text.name; let type = typeof text; if (type !== 'string') { if (type === 'number') { text = '' + text; } else { return ''; } } if (Config.groups && text.charAt(0) in Config.groups) text = text.substr(1); return text.trim(); } toString(text) { if (!text) return ''; let type = typeof text; if (type === 'string') return text; if (type === 'number') return '' + text; return JSON.stringify(text); } normalizeMessage(text) { text = this.toString(text); if (!text) return ''; text = text.trim(); if (text.length > 300) { if (text.substr(text.length - 2, 2) === "__") { text = text.substr(0, 295) + "__..."; } else { text = text.substr(0, 297) + "..."; } } return text; } random(limit) { if (!limit) limit = 2; return Math.floor(Math.random() * limit); } shuffle(array) { let currentIndex = array.length, temporaryValue, randomIndex; while (0 !== currentIndex) { randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; } sample(array, amount) { if (!(array instanceof Array)) return; let len = array.length; if (!len) return; if (len === 1 || !amount || amount === 1) return array.slice()[Math.floor(Math.random() * len)]; if (amount > len) { amount = len; } else if (amount < 0) { amount = 0; } return this.shuffle(array).splice(0, amount); } generation(num) { let generations = [151, 251, 386, 493, 649, 721, 802]; let i, len = generations.length; for (i = 0; i < len; i++) { if (generations[i] >= num) { break; } } return i + 1; } effectiveness(move, mon) { move = this.toId(move); mon = this.toId(mon); let moveType; if (move.substr(0, 12) === 'hiddenpower') { moveType = move.substr(12, move.length - 14); } else { let realMove = this.data.moves[move]; moveType = this.toId(realMove.type); } let realMon = this.data.pokedex[mon]; //console.log(moveType); let curEffect = 1; for (let i = 0; i < realMon.types.length; i++) { let realType = this.toId(realMon.types[i]); curEffect *= this.data.typeChart[this.data.convertType[moveType]][this.data.convertType[realType]]; } return curEffect; } getSuffix(num) { num = num % 100; if (num >= 10 && num <= 19) { return "th"; } else if (num % 10 === 1) { return "st"; } else if (num % 10 === 2) { return "nd"; } else if (num % 10 === 3) { return "rd"; } else { return "th"; } } isPort(mon1, mon2) { for (let i = 2; i < Math.min(mon1.length, mon2.length, 5); i++) { if (mon1.slice(mon1.length - i) === mon2.slice(0, i)) { return (mon1.slice(0, mon1.length - i) + mon2); } } return false; } } let tools = new Tools(); tools.loadData(); module.exports = tools;
/* AngularJS v1.3.11 (c) 2010-2014 Google, Inc. http://angularjs.org License: MIT */ (function(n,h,p){'use strict';function E(a){var d=[];s(d,h.noop).chars(a);return d.join("")}function g(a){var d={};a=a.split(",");var c;for(c=0;c<a.length;c++)d[a[c]]=!0;return d}function F(a,d){function c(a,b,c,l){b=h.lowercase(b);if(t[b])for(;f.last()&&u[f.last()];)e("",f.last());v[b]&&f.last()==b&&e("",b);(l=w[b]||!!l)||f.push(b);var m={};c.replace(G,function(a,b,d,c,e){m[b]=r(d||c||e||"")});d.start&&d.start(b,m,l)}function e(a,b){var c=0,e;if(b=h.lowercase(b))for(c=f.length-1;0<=c&&f[c]!=b;c--); if(0<=c){for(e=f.length-1;e>=c;e--)d.end&&d.end(f[e]);f.length=c}}"string"!==typeof a&&(a=null===a||"undefined"===typeof a?"":""+a);var b,k,f=[],m=a,l;for(f.last=function(){return f[f.length-1]};a;){l="";k=!0;if(f.last()&&x[f.last()])a=a.replace(new RegExp("(.*)<\\s*\\/\\s*"+f.last()+"[^>]*>","i"),function(a,b){b=b.replace(H,"$1").replace(I,"$1");d.chars&&d.chars(r(b));return""}),e("",f.last());else{if(0===a.indexOf("\x3c!--"))b=a.indexOf("--",4),0<=b&&a.lastIndexOf("--\x3e",b)===b&&(d.comment&&d.comment(a.substring(4, b)),a=a.substring(b+3),k=!1);else if(y.test(a)){if(b=a.match(y))a=a.replace(b[0],""),k=!1}else if(J.test(a)){if(b=a.match(z))a=a.substring(b[0].length),b[0].replace(z,e),k=!1}else K.test(a)&&((b=a.match(A))?(b[4]&&(a=a.substring(b[0].length),b[0].replace(A,c)),k=!1):(l+="<",a=a.substring(1)));k&&(b=a.indexOf("<"),l+=0>b?a:a.substring(0,b),a=0>b?"":a.substring(b),d.chars&&d.chars(r(l)))}if(a==m)throw L("badparse",a);m=a}e()}function r(a){if(!a)return"";var d=M.exec(a);a=d[1];var c=d[3];if(d=d[2])q.innerHTML= d.replace(/</g,"&lt;"),d="textContent"in q?q.textContent:q.innerText;return a+d+c}function B(a){return a.replace(/&/g,"&amp;").replace(N,function(a){var c=a.charCodeAt(0);a=a.charCodeAt(1);return"&#"+(1024*(c-55296)+(a-56320)+65536)+";"}).replace(O,function(a){return"&#"+a.charCodeAt(0)+";"}).replace(/</g,"&lt;").replace(/>/g,"&gt;")}function s(a,d){var c=!1,e=h.bind(a,a.push);return{start:function(a,k,f){a=h.lowercase(a);!c&&x[a]&&(c=a);c||!0!==C[a]||(e("<"),e(a),h.forEach(k,function(c,f){var k= h.lowercase(f),g="img"===a&&"src"===k||"background"===k;!0!==P[k]||!0===D[k]&&!d(c,g)||(e(" "),e(f),e('="'),e(B(c)),e('"'))}),e(f?"/>":">"))},end:function(a){a=h.lowercase(a);c||!0!==C[a]||(e("</"),e(a),e(">"));a==c&&(c=!1)},chars:function(a){c||e(B(a))}}}var L=h.$$minErr("$sanitize"),A=/^<((?:[a-zA-Z])[\w:-]*)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*(>?)/,z=/^<\/\s*([\w:-]+)[^>]*>/,G=/([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g,K=/^</, J=/^<\//,H=/\x3c!--(.*?)--\x3e/g,y=/<!DOCTYPE([^>]*?)>/i,I=/<!\[CDATA\[(.*?)]]\x3e/g,N=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,O=/([^\#-~| |!])/g,w=g("area,br,col,hr,img,wbr");n=g("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr");p=g("rp,rt");var v=h.extend({},p,n),t=h.extend({},n,g("address,article,aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,script,section,table,ul")),u=h.extend({},p,g("a,abbr,acronym,b,bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s,samp,small,span,strike,strong,sub,sup,time,tt,u,var")); n=g("animate,animateColor,animateMotion,animateTransform,circle,defs,desc,ellipse,font-face,font-face-name,font-face-src,g,glyph,hkern,image,linearGradient,line,marker,metadata,missing-glyph,mpath,path,polygon,polyline,radialGradient,rect,set,stop,svg,switch,text,title,tspan,use");var x=g("script,style"),C=h.extend({},w,t,u,v,n),D=g("background,cite,href,longdesc,src,usemap,xlink:href");n=g("abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,scope,scrolling,shape,size,span,start,summary,target,title,type,valign,value,vspace,width"); p=g("accent-height,accumulate,additive,alphabetic,arabic-form,ascent,attributeName,attributeType,baseProfile,bbox,begin,by,calcMode,cap-height,class,color,color-rendering,content,cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,font-size,font-stretch,font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,gradientUnits,hanging,height,horiz-adv-x,horiz-origin-x,ideographic,k,keyPoints,keySplines,keyTimes,lang,marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mathematical,max,min,offset,opacity,orient,origin,overline-position,overline-thickness,panose-1,path,pathLength,points,preserveAspectRatio,r,refX,refY,repeatCount,repeatDur,requiredExtensions,requiredFeatures,restart,rotate,rx,ry,slope,stemh,stemv,stop-color,stop-opacity,strikethrough-position,strikethrough-thickness,stroke,stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,stroke-width,systemLanguage,target,text-anchor,to,transform,type,u1,u2,underline-position,underline-thickness,unicode,unicode-range,units-per-em,values,version,viewBox,visibility,width,widths,x,x-height,x1,x2,xlink:actuate,xlink:arcrole,xlink:role,xlink:show,xlink:title,xlink:type,xml:base,xml:lang,xml:space,xmlns,xmlns:xlink,y,y1,y2,zoomAndPan"); var P=h.extend({},D,p,n),q=document.createElement("pre"),M=/^(\s*)([\s\S]*?)(\s*)$/;h.module("ngSanitize",[]).provider("$sanitize",function(){this.$get=["$$sanitizeUri",function(a){return function(d){var c=[];F(d,s(c,function(c,b){return!/^unsafe/.test(a(c,b))}));return c.join("")}}]});h.module("ngSanitize").filter("linky",["$sanitize",function(a){var d=/((ftp|https?):\/\/|(www\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"\u201d\u2019]/,c=/^mailto:/;return function(e,b){function k(a){a&&g.push(E(a))} function f(a,c){g.push("<a ");h.isDefined(b)&&g.push('target="',b,'" ');g.push('href="',a.replace(/"/g,"&quot;"),'">');k(c);g.push("</a>")}if(!e)return e;for(var m,l=e,g=[],n,p;m=l.match(d);)n=m[0],m[2]||m[4]||(n=(m[3]?"http://":"mailto:")+n),p=m.index,k(l.substr(0,p)),f(n,m[0].replace(c,"")),l=l.substring(p+m[0].length);k(l);return a(g.join(""))}}])})(window,window.angular); //# sourceMappingURL=angular-sanitize.min.js.map
// Generated automatically by nearley, version 2.13.0 // http://github.com/Hardmath123/nearley (function () { function id(x) { return x[0]; } const join = sep => arr => arr.join(sep); const map = fn => arr => arr.map(fn); const nth = pos => arr => arr[pos]; const head = arr => arr[0]; const pipe = (...fns) => x => fns.reduce((x, f) => f(x), x); const filter = fn => arr => arr.filter(fn); const predR = regex => x => regex.test(x); const notnull = x => x != null; const log = x => console.info(x) || x; const toInt = x => x | 0; const _true = () => true; const _false = () => false; const nothing = d => null; const compact = filter(notnull); const oBind = base => ext => Object.assign({}, base, ext); const option = oBind({ type: 'option' }); const push = arr => x => arr.push(x) && arr; var grammar = { Lexer: undefined, ParserRules: [{ "name": "PROGRAM$ebnf$1", "symbols": [] }, { "name": "PROGRAM$ebnf$1$subexpression$1", "symbols": ["ln", "LINE"], "postprocess": nth(1) }, { "name": "PROGRAM$ebnf$1", "symbols": ["PROGRAM$ebnf$1", "PROGRAM$ebnf$1$subexpression$1"], "postprocess": function arrpush(d) { return d[0].concat([d[1]]); } }, { "name": "PROGRAM", "symbols": ["LINE", "PROGRAM$ebnf$1"], "postprocess": ([a, b]) => [a, ...b] }, { "name": "LINE$string$1", "symbols": [{ "literal": ":" }, { "literal": ":" }], "postprocess": function joiner(d) { return d.join(''); } }, { "name": "LINE", "symbols": ["NAME", "DECLARATION", "_", "LINE$string$1", "_", "TYPE", "__"], "postprocess": ([name, { path, defaults },,,, [coerceTo]]) => ({ type: 'declaration', name, body: { path: path || name, defaults }, coerceTo }) }, { "name": "NAME", "symbols": ["WORD"], "postprocess": id }, { "name": "DECLARATION$ebnf$1$subexpression$1", "symbols": ["_", { "literal": "=" }, "_", "WORD"], "postprocess": nth(3) }, { "name": "DECLARATION$ebnf$1", "symbols": ["DECLARATION$ebnf$1$subexpression$1"], "postprocess": id }, { "name": "DECLARATION$ebnf$1", "symbols": [], "postprocess": function (d) { return null; } }, { "name": "DECLARATION$ebnf$2", "symbols": [] }, { "name": "DECLARATION$ebnf$2", "symbols": ["DECLARATION$ebnf$2", "DEFAULT"], "postprocess": function arrpush(d) { return d[0].concat([d[1]]); } }, { "name": "DECLARATION", "symbols": ["DECLARATION$ebnf$1", "DECLARATION$ebnf$2"], "postprocess": ([path, defaults]) => ({ path, defaults }) }, { "name": "DEFAULT", "symbols": ["_", { "literal": "|" }, "_", "VALUE"], "postprocess": pipe(log, nth(3), ([val]) => option({ val })) }, { "name": "VALUE", "symbols": ["BOOL"] }, { "name": "VALUE", "symbols": ["NUM"] }, { "name": "VALUE", "symbols": ["STR"] }, { "name": "VALUE", "symbols": ["EXPRESSION"] }, { "name": "OPERATOR$string$1", "symbols": [{ "literal": "f" }, { "literal": "i" }, { "literal": "l" }, { "literal": "e" }], "postprocess": function joiner(d) { return d.join(''); } }, { "name": "OPERATOR", "symbols": ["OPERATOR$string$1"], "postprocess": id }, { "name": "EXPRESSION$subexpression$1", "symbols": ["STR"] }, { "name": "EXPRESSION$subexpression$1", "symbols": ["WORD"] }, { "name": "EXPRESSION", "symbols": ["OPERATOR", "_", "EXPRESSION$subexpression$1"], "postprocess": ([operator, _, args]) => ({ type: 'expression', operator, args }) }, { "name": "BOOL", "symbols": [/[Yy]/, /[eE]/, /[sS]/], "postprocess": _true }, { "name": "BOOL", "symbols": [/[nN]/, /[oO]/], "postprocess": _false }, { "name": "BOOL$string$1", "symbols": [{ "literal": "t" }, { "literal": "r" }, { "literal": "u" }, { "literal": "e" }], "postprocess": function joiner(d) { return d.join(''); } }, { "name": "BOOL", "symbols": ["BOOL$string$1"], "postprocess": _true }, { "name": "BOOL$string$2", "symbols": [{ "literal": "f" }, { "literal": "a" }, { "literal": "l" }, { "literal": "s" }, { "literal": "e" }], "postprocess": function joiner(d) { return d.join(''); } }, { "name": "BOOL", "symbols": ["BOOL$string$2"], "postprocess": _false }, { "name": "WORD$ebnf$1", "symbols": [/[a-zA-Z_]/] }, { "name": "WORD$ebnf$1", "symbols": ["WORD$ebnf$1", /[a-zA-Z_]/], "postprocess": function arrpush(d) { return d[0].concat([d[1]]); } }, { "name": "WORD", "symbols": ["WORD$ebnf$1"], "postprocess": pipe(map(join('')), head) }, { "name": "NUM$ebnf$1", "symbols": [/[0-9_]/] }, { "name": "NUM$ebnf$1", "symbols": ["NUM$ebnf$1", /[0-9_]/], "postprocess": function arrpush(d) { return d[0].concat([d[1]]); } }, { "name": "NUM", "symbols": ["NUM$ebnf$1", "UNIT"], "postprocess": pipe(head, filter(predR(/[^_]/)), join(''), toInt) }, { "name": "STR$ebnf$1", "symbols": [] }, { "name": "STR$ebnf$1", "symbols": ["STR$ebnf$1", /[^']/], "postprocess": function arrpush(d) { return d[0].concat([d[1]]); } }, { "name": "STR", "symbols": [{ "literal": "'" }, "STR$ebnf$1", { "literal": "'" }], "postprocess": pipe(nth(1), join('')) }, { "name": "UNIT$ebnf$1", "symbols": [] }, { "name": "UNIT$ebnf$1", "symbols": ["UNIT$ebnf$1", /[a-z]/], "postprocess": function arrpush(d) { return d[0].concat([d[1]]); } }, { "name": "UNIT", "symbols": ["UNIT$ebnf$1"] }, { "name": "TYPE$string$1", "symbols": [{ "literal": "I" }, { "literal": "n" }, { "literal": "t" }], "postprocess": function joiner(d) { return d.join(''); } }, { "name": "TYPE", "symbols": ["TYPE$string$1"] }, { "name": "TYPE$string$2", "symbols": [{ "literal": "B" }, { "literal": "o" }, { "literal": "o" }, { "literal": "l" }, { "literal": "e" }, { "literal": "a" }, { "literal": "n" }], "postprocess": function joiner(d) { return d.join(''); } }, { "name": "TYPE", "symbols": ["TYPE$string$2"] }, { "name": "TYPE$string$3", "symbols": [{ "literal": "S" }, { "literal": "t" }, { "literal": "r" }, { "literal": "i" }, { "literal": "n" }, { "literal": "g" }], "postprocess": function joiner(d) { return d.join(''); } }, { "name": "TYPE", "symbols": ["TYPE$string$3"] }, { "name": "TYPE$string$4", "symbols": [{ "literal": "J" }, { "literal": "S" }, { "literal": "O" }, { "literal": "N" }], "postprocess": function joiner(d) { return d.join(''); } }, { "name": "TYPE", "symbols": ["TYPE$string$4"] }, { "name": "_$ebnf$1", "symbols": [/[ ]/] }, { "name": "_$ebnf$1", "symbols": ["_$ebnf$1", /[ ]/], "postprocess": function arrpush(d) { return d[0].concat([d[1]]); } }, { "name": "_", "symbols": ["_$ebnf$1"], "postprocess": nothing }, { "name": "__$ebnf$1", "symbols": [] }, { "name": "__$ebnf$1", "symbols": ["__$ebnf$1", /[\s]/], "postprocess": function arrpush(d) { return d[0].concat([d[1]]); } }, { "name": "__", "symbols": ["__$ebnf$1"], "postprocess": nothing }, { "name": "ln$ebnf$1", "symbols": [{ "literal": "\r" }], "postprocess": id }, { "name": "ln$ebnf$1", "symbols": [], "postprocess": function (d) { return null; } }, { "name": "ln", "symbols": ["ln$ebnf$1", { "literal": "\n" }], "postprocess": nothing }], ParserStart: "PROGRAM" }; if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') { module.exports = grammar; } else { window.grammar = grammar; } })();
module.exports = { devServer: { disableHostCheck: true, }, // output built static files to Laravel's public dir. outputDir: '../../../public/assets/admin', publicPath: process.env.NODE_ENV === 'production' ? '/assets/admin/' : '', // modify the location of the generated HTML file. // make sure to do this only in production. indexPath: process.env.NODE_ENV === 'production' ? '../../../resources/views/admin.blade.php' : 'index.html', transpileDependencies: ['vuetify'], pluginOptions: { i18n: { locale: 'en', fallbackLocale: 'en', localeDir: 'locales', enableInSFC: false, }, }, }
'use strict'; /* globals support: false */ describe('injector', function() { var providers; var injector; var providerInjector; var controllerProvider; beforeEach(module(function($provide, $injector, $controllerProvider) { providers = function(name, factory, annotations) { $provide.factory(name, extend(factory, annotations || {})); }; providerInjector = $injector; controllerProvider = $controllerProvider; })); beforeEach(inject(function($injector) { injector = $injector; })); it("should return same instance from calling provider", function() { var instance = {}, original = instance; providers('instance', function() { return instance; }); expect(injector.get('instance')).toEqual(instance); instance = 'deleted'; expect(injector.get('instance')).toEqual(original); }); it('should inject providers', function() { providers('a', function() {return 'Mi';}); providers('b', function(mi) {return mi + 'sko';}, {$inject:['a']}); expect(injector.get('b')).toEqual('Misko'); }); it('should check its modulesToLoad argument', function() { expect(function() { angular.injector('test'); }) .toThrowMinErr('ng', 'areq'); }); it('should resolve dependency graph and instantiate all services just once', function() { var log = []; // s1 // / | \ // / s2 \ // / / | \ \ // /s3 < s4 > s5 // // // s6 providers('s1', function() { log.push('s1'); return {}; }, {$inject: ['s2', 's5', 's6']}); providers('s2', function() { log.push('s2'); return {}; }, {$inject: ['s3', 's4', 's5']}); providers('s3', function() { log.push('s3'); return {}; }, {$inject: ['s6']}); providers('s4', function() { log.push('s4'); return {}; }, {$inject: ['s3', 's5']}); providers('s5', function() { log.push('s5'); return {}; }); providers('s6', function() { log.push('s6'); return {}; }); injector.get('s1'); expect(log).toEqual(['s6', 's3', 's5', 's4', 's2', 's1']); }); it('should allow query names', function() { providers('abc', function() { return ''; }); expect(injector.has('abc')).toBe(true); expect(injector.has('xyz')).toBe(false); expect(injector.has('$injector')).toBe(true); }); it('should provide useful message if no provider', function() { expect(function() { injector.get('idontexist'); }).toThrowMinErr("$injector", "unpr", "Unknown provider: idontexistProvider <- idontexist"); }); it('should provide the caller name if given', function() { expect(function() { injector.get('idontexist', 'callerName'); }).toThrowMinErr("$injector", "unpr", "Unknown provider: idontexistProvider <- idontexist <- callerName"); }); it('should provide the caller name for controllers', function() { controllerProvider.register('myCtrl', function(idontexist) {}); var $controller = injector.get('$controller'); expect(function() { $controller('myCtrl', {$scope: {}}); }).toThrowMinErr("$injector", "unpr", "Unknown provider: idontexistProvider <- idontexist <- myCtrl"); }); it('should not corrupt the cache when an object fails to get instantiated', function() { expect(function() { injector.get('idontexist'); }).toThrowMinErr("$injector", "unpr", "Unknown provider: idontexistProvider <- idontexist"); expect(function() { injector.get('idontexist'); }).toThrowMinErr("$injector", "unpr", "Unknown provider: idontexistProvider <- idontexist"); }); it('should provide path to the missing provider', function() { providers('a', function(idontexist) {return 1;}); providers('b', function(a) {return 2;}); expect(function() { injector.get('b'); }).toThrowMinErr("$injector", "unpr", "Unknown provider: idontexistProvider <- idontexist <- a <- b"); }); it('should create a new $injector for the run phase', inject(function($injector) { expect($injector).not.toBe(providerInjector); })); it('should have an false strictDi property', inject(function($injector) { expect($injector.strictDi).toBe(false); })); describe('invoke', function() { var args; beforeEach(function() { args = null; providers('a', function() {return 1;}); providers('b', function() {return 2;}); }); function fn(a, b, c, d) { /* jshint -W040 */ args = [this, a, b, c, d]; return a + b + c + d; } it('should call function', function() { fn.$inject = ['a', 'b', 'c', 'd']; injector.invoke(fn, {name:"this"}, {c:3, d:4}); expect(args).toEqual([{name:'this'}, 1, 2, 3, 4]); }); it('should treat array as annotations', function() { injector.invoke(['a', 'b', 'c', 'd', fn], {name:"this"}, {c:3, d:4}); expect(args).toEqual([{name:'this'}, 1, 2, 3, 4]); }); it('should invoke the passed-in fn with all of the dependencies as arguments', function() { providers('c', function() {return 3;}); providers('d', function() {return 4;}); expect(injector.invoke(['a', 'b', 'c', 'd', fn])).toEqual(10); }); it('should fail with errors if not function or array', function() { expect(function() { injector.invoke({}); }).toThrowMinErr("ng", "areq", "Argument 'fn' is not a function, got Object"); expect(function() { injector.invoke(['a', 123], {}); }).toThrowMinErr("ng", "areq", "Argument 'fn' is not a function, got number"); }); }); describe('annotation', function() { /* global annotate: false */ it('should return $inject', function() { function fn() {} fn.$inject = ['a']; expect(annotate(fn)).toBe(fn.$inject); expect(annotate(function() {})).toEqual([]); expect(annotate(function() {})).toEqual([]); // jscs:disable disallowSpacesInAnonymousFunctionExpression expect(annotate(function () {})).toEqual([]); expect(annotate(function /* */ () {})).toEqual([]); // jscs:enable disallowSpacesInAnonymousFunctionExpression }); it('should create $inject', function() { var extraParans = angular.noop; // jscs:disable disallowSpacesInFunctionDeclaration // keep the multi-line to make sure we can handle it function $f_n0 /* */( $a, // x, <-- looks like an arg but it is a comment b_, /* z, <-- looks like an arg but it is a multi-line comment function(a, b) {} */ _c, /* {some type} */ d) { extraParans();} // jscs:enable disallowSpacesInFunctionDeclaration expect(annotate($f_n0)).toEqual(['$a', 'b_', '_c', 'd']); expect($f_n0.$inject).toEqual(['$a', 'b_', '_c', 'd']); }); it('should strip leading and trailing underscores from arg name during inference', function() { function beforeEachFn(_foo_) { /* foo = _foo_ */ } expect(annotate(beforeEachFn)).toEqual(['foo']); }); it('should not strip service names with a single underscore', function() { function beforeEachFn(_) { /* _ = _ */ } expect(annotate(beforeEachFn)).toEqual(['_']); }); it('should handle no arg functions', function() { function $f_n0() {} expect(annotate($f_n0)).toEqual([]); expect($f_n0.$inject).toEqual([]); }); it('should handle no arg functions with spaces in the arguments list', function() { function fn() {} expect(annotate(fn)).toEqual([]); expect(fn.$inject).toEqual([]); }); it('should handle args with both $ and _', function() { function $f_n0($a_) {} expect(annotate($f_n0)).toEqual(['$a_']); expect($f_n0.$inject).toEqual(['$a_']); }); it('should handle functions with overridden toString', function() { function fn(a) {} fn.toString = function() { return 'fn'; }; expect(annotate(fn)).toEqual(['a']); expect(fn.$inject).toEqual(['a']); }); it('should throw on non function arg', function() { expect(function() { annotate({}); }).toThrow(); }); describe('es6', function() { /*jshint -W061 */ if (support.ES6Function) { // The functions are generated using `eval` as just having the ES6 syntax can break some browsers. it('should be possible to annotate functions that are declared using ES6 syntax', function() { expect(annotate(eval('({ fn(x) { return; } })').fn)).toEqual(['x']); }); } if (support.fatArrow) { it('should create $inject for arrow functions', function() { expect(annotate(eval('(a, b) => a'))).toEqual(['a', 'b']); }); } if (support.fatArrow) { it('should create $inject for arrow functions with no parenthesis', function() { expect(annotate(eval('a => a'))).toEqual(['a']); }); } if (support.fatArrow) { it('should take args before first arrow', function() { expect(annotate(eval('a => b => b'))).toEqual(['a']); }); } if (support.classes) { it('should be possible to instantiate ES6 classes', function() { providers('a', function() { return 'a-value'; }); var Clazz = eval('(class { constructor(a) { this.a = a; } aVal() { return this.a; } })'); var instance = injector.instantiate(Clazz); expect(instance).toEqual(new Clazz('a-value')); expect(instance.aVal()).toEqual('a-value'); }); } /*jshint +W061 */ }); it('should publish annotate API', function() { expect(angular.mock.$$annotate).toBe(annotate); spyOn(angular.mock, '$$annotate').and.callThrough(); function fn() {} injector.annotate(fn); expect(angular.mock.$$annotate).toHaveBeenCalledWith(fn); }); }); it('should have $injector', function() { var $injector = createInjector(); expect($injector.get('$injector')).toBe($injector); }); it('should define module', function() { var log = ''; var injector = createInjector([function($provide) { $provide.value('value', 'value;'); $provide.factory('fn', valueFn('function;')); $provide.provider('service', function() { this.$get = valueFn('service;'); }); }, function(valueProvider, fnProvider, serviceProvider) { log += valueProvider.$get() + fnProvider.$get() + serviceProvider.$get(); }]).invoke(function(value, fn, service) { log += '->' + value + fn + service; }); expect(log).toEqual('value;function;service;->value;function;service;'); }); describe('module', function() { it('should provide $injector even when no module is requested', function() { var $provide, $injector = createInjector([ angular.extend(function(p) { $provide = p; }, {$inject: ['$provide']}) ]); expect($injector.get('$injector')).toBe($injector); }); it('should load multiple function modules and infer inject them', function() { var a = 'junk'; var $injector = createInjector([ function() { a = 'A'; // reset to prove we ran }, function($provide) { $provide.value('a', a); }, angular.extend(function(p, serviceA) { p.value('b', serviceA.$get() + 'B'); }, {$inject:['$provide', 'aProvider']}), ['$provide', 'bProvider', function(p, serviceB) { p.value('c', serviceB.$get() + 'C'); }] ]); expect($injector.get('a')).toEqual('A'); expect($injector.get('b')).toEqual('AB'); expect($injector.get('c')).toEqual('ABC'); }); it('should run symbolic modules', function() { angularModule('myModule', []).value('a', 'abc'); var $injector = createInjector(['myModule']); expect($injector.get('a')).toEqual('abc'); }); it('should error on invalid module name', function() { expect(function() { createInjector(['IDontExist'], {}); }).toThrowMinErr('$injector', 'modulerr', /\[\$injector:nomod\] Module 'IDontExist' is not available! You either misspelled the module name or forgot to load it/); }); it('should load dependant modules only once', function() { var log = ''; angular.module('a', [], function() { log += 'a'; }); angular.module('b', ['a'], function() { log += 'b'; }); angular.module('c', ['a', 'b'], function() { log += 'c'; }); createInjector(['c', 'c']); expect(log).toEqual('abc'); }); it('should load different instances of dependent functions', function() { function generateValueModule(name, value) { return function($provide) { $provide.value(name, value); }; } var injector = createInjector([generateValueModule('name1', 'value1'), generateValueModule('name2', 'value2')]); expect(injector.get('name2')).toBe('value2'); }); it('should load same instance of dependent function only once', function() { var count = 0; function valueModule($provide) { count++; $provide.value('name', 'value'); } var injector = createInjector([valueModule, valueModule]); expect(injector.get('name')).toBe('value'); expect(count).toBe(1); }); it('should execute runBlocks after injector creation', function() { var log = ''; angular.module('a', [], function() { log += 'a'; }).run(function() { log += 'A'; }); angular.module('b', ['a'], function() { log += 'b'; }).run(function() { log += 'B'; }); createInjector([ 'b', valueFn(function() { log += 'C'; }), [valueFn(function() { log += 'D'; })] ]); expect(log).toEqual('abABCD'); }); it('should execute own config blocks after all own providers are invoked', function() { var log = ''; angular.module('a', ['b']) .config(function($aProvider) { log += 'aConfig;'; }) .provider('$a', function() { log += '$aProvider;'; this.$get = function() {}; }); angular.module('b', []) .config(function($bProvider) { log += 'bConfig;'; }) .provider('$b', function() { log += '$bProvider;'; this.$get = function() {}; }); createInjector(['a']); expect(log).toBe('$bProvider;bConfig;$aProvider;aConfig;'); }); describe('$provide', function() { it('should throw an exception if we try to register a service called "hasOwnProperty"', function() { createInjector([function($provide) { expect(function() { $provide.provider('hasOwnProperty', function() { }); }).toThrowMinErr('ng', 'badname'); }]); }); it('should throw an exception if we try to register a constant called "hasOwnProperty"', function() { createInjector([function($provide) { expect(function() { $provide.constant('hasOwnProperty', {}); }).toThrowMinErr('ng', 'badname'); }]); }); describe('constant', function() { it('should create configuration injectable constants', function() { var log = []; createInjector([ function($provide) { $provide.constant('abc', 123); $provide.constant({a: 'A', b:'B'}); return function(a) { log.push(a); }; }, function(abc) { log.push(abc); return function(b) { log.push(b); }; } ]).get('abc'); expect(log).toEqual([123, 'A', 'B']); }); }); describe('value', function() { it('should configure $provide values', function() { expect(createInjector([function($provide) { $provide.value('value', 'abc'); }]).get('value')).toEqual('abc'); }); it('should configure a set of values', function() { expect(createInjector([function($provide) { $provide.value({value: Array}); }]).get('value')).toEqual(Array); }); }); describe('factory', function() { it('should configure $provide factory function', function() { expect(createInjector([function($provide) { $provide.factory('value', valueFn('abc')); }]).get('value')).toEqual('abc'); }); it('should configure a set of factories', function() { expect(createInjector([function($provide) { $provide.factory({value: Array}); }]).get('value')).toEqual([]); }); }); describe('service', function() { it('should register a class', function() { var Type = function(value) { this.value = value; }; var instance = createInjector([function($provide) { $provide.value('value', 123); $provide.service('foo', Type); }]).get('foo'); expect(instance instanceof Type).toBe(true); expect(instance.value).toBe(123); }); it('should register a set of classes', function() { var Type = function() {}; var injector = createInjector([function($provide) { $provide.service({ foo: Type, bar: Type }); }]); expect(injector.get('foo') instanceof Type).toBe(true); expect(injector.get('bar') instanceof Type).toBe(true); }); }); describe('provider', function() { it('should configure $provide provider object', function() { expect(createInjector([function($provide) { $provide.provider('value', { $get: valueFn('abc') }); }]).get('value')).toEqual('abc'); }); it('should configure $provide provider type', function() { function Type() {} Type.prototype.$get = function() { expect(this instanceof Type).toBe(true); return 'abc'; }; expect(createInjector([function($provide) { $provide.provider('value', Type); }]).get('value')).toEqual('abc'); }); it('should configure $provide using an array', function() { function Type(PREFIX) { this.prefix = PREFIX; } Type.prototype.$get = function() { return this.prefix + 'def'; }; expect(createInjector([function($provide) { $provide.constant('PREFIX', 'abc'); $provide.provider('value', ['PREFIX', Type]); }]).get('value')).toEqual('abcdef'); }); it('should configure a set of providers', function() { expect(createInjector([function($provide) { $provide.provider({value: valueFn({$get:Array})}); }]).get('value')).toEqual([]); }); }); describe('decorator', function() { var log, injector; beforeEach(function() { log = []; }); it('should be called with the original instance', function() { injector = createInjector([function($provide) { $provide.value('myService', function(val) { log.push('myService:' + val); return 'origReturn'; }); $provide.decorator('myService', function($delegate) { return function(val) { log.push('myDecoratedService:' + val); var origVal = $delegate('decInput'); return 'dec+' + origVal; }; }); }]); var out = injector.get('myService')('input'); log.push(out); expect(log.join('; ')). toBe('myDecoratedService:input; myService:decInput; dec+origReturn'); }); it('should allow multiple decorators to be applied to a service', function() { injector = createInjector([function($provide) { $provide.value('myService', function(val) { log.push('myService:' + val); return 'origReturn'; }); $provide.decorator('myService', function($delegate) { return function(val) { log.push('myDecoratedService1:' + val); var origVal = $delegate('decInput1'); return 'dec1+' + origVal; }; }); $provide.decorator('myService', function($delegate) { return function(val) { log.push('myDecoratedService2:' + val); var origVal = $delegate('decInput2'); return 'dec2+' + origVal; }; }); }]); var out = injector.get('myService')('input'); log.push(out); expect(log).toEqual(['myDecoratedService2:input', 'myDecoratedService1:decInput2', 'myService:decInput1', 'dec2+dec1+origReturn']); }); it('should decorate services with dependencies', function() { injector = createInjector([function($provide) { $provide.value('dep1', 'dependency1'); $provide.factory('myService', ['dep1', function(dep1) { return function(val) { log.push('myService:' + val + ',' + dep1); return 'origReturn'; }; }]); $provide.decorator('myService', function($delegate) { return function(val) { log.push('myDecoratedService:' + val); var origVal = $delegate('decInput'); return 'dec+' + origVal; }; }); }]); var out = injector.get('myService')('input'); log.push(out); expect(log.join('; ')). toBe('myDecoratedService:input; myService:decInput,dependency1; dec+origReturn'); }); it('should allow for decorators to be injectable', function() { injector = createInjector([function($provide) { $provide.value('dep1', 'dependency1'); $provide.factory('myService', function() { return function(val) { log.push('myService:' + val); return 'origReturn'; }; }); $provide.decorator('myService', function($delegate, dep1) { return function(val) { log.push('myDecoratedService:' + val + ',' + dep1); var origVal = $delegate('decInput'); return 'dec+' + origVal; }; }); }]); var out = injector.get('myService')('input'); log.push(out); expect(log.join('; ')). toBe('myDecoratedService:input,dependency1; myService:decInput; dec+origReturn'); }); it('should allow for decorators to $injector', function() { injector = createInjector(['ng', function($provide) { $provide.decorator('$injector', function($delegate) { return extend({}, $delegate, {get: function(val) { if (val === 'key') { return 'value'; } return $delegate.get(val); }}); }); }]); expect(injector.get('key')).toBe('value'); expect(injector.get('$http')).not.toBeUndefined(); }); }); }); describe('error handling', function() { it('should handle wrong argument type', function() { expect(function() { createInjector([ {} ], {}); }).toThrowMinErr('$injector', 'modulerr', /Failed to instantiate module \{\} due to:\n.*\[ng:areq\] Argument 'module' is not a function, got Object/); }); it('should handle exceptions', function() { expect(function() { createInjector([function() { throw 'MyError'; }], {}); }).toThrowMinErr('$injector', 'modulerr', /Failed to instantiate module .+ due to:\n.*MyError/); }); it('should decorate the missing service error with module name', function() { angular.module('TestModule', [], function(xyzzy) {}); expect(function() { createInjector(['TestModule']); }).toThrowMinErr( '$injector', 'modulerr', /Failed to instantiate module TestModule due to:\n.*\[\$injector:unpr] Unknown provider: xyzzy/ ); }); it('should decorate the missing service error with module function', function() { function myModule(xyzzy) {} expect(function() { createInjector([myModule]); }).toThrowMinErr( '$injector', 'modulerr', /Failed to instantiate module function myModule\(xyzzy\) due to:\n.*\[\$injector:unpr] Unknown provider: xyzzy/ ); }); it('should decorate the missing service error with module array function', function() { function myModule(xyzzy) {} expect(function() { createInjector([['xyzzy', myModule]]); }).toThrowMinErr( '$injector', 'modulerr', /Failed to instantiate module function myModule\(xyzzy\) due to:\n.*\[\$injector:unpr] Unknown provider: xyzzy/ ); }); it('should throw error when trying to inject oneself', function() { expect(function() { createInjector([function($provide) { $provide.factory('service', function(service) {}); return function(service) {}; }]); }).toThrowMinErr('$injector', 'cdep', 'Circular dependency found: service <- service'); }); it('should throw error when trying to inject circular dependency', function() { expect(function() { createInjector([function($provide) { $provide.factory('a', function(b) {}); $provide.factory('b', function(a) {}); return function(a) {}; }]); }).toThrowMinErr('$injector', 'cdep', 'Circular dependency found: a <- b <- a'); }); }); }); describe('retrieval', function() { var instance = {name:'angular'}; var Instance = function() { this.name = 'angular'; }; function createInjectorWithValue(instanceName, instance) { return createInjector([['$provide', function(provide) { provide.value(instanceName, instance); }]]); } function createInjectorWithFactory(serviceName, serviceDef) { return createInjector([['$provide', function(provide) { provide.factory(serviceName, serviceDef); }]]); } it('should retrieve by name', function() { var $injector = createInjectorWithValue('instance', instance); var retrievedInstance = $injector.get('instance'); expect(retrievedInstance).toBe(instance); }); it('should cache instance', function() { var $injector = createInjectorWithFactory('instance', function() { return new Instance(); }); var instance = $injector.get('instance'); expect($injector.get('instance')).toBe(instance); expect($injector.get('instance')).toBe(instance); }); it('should call functions and infer arguments', function() { var $injector = createInjectorWithValue('instance', instance); expect($injector.invoke(function(instance) { return instance; })).toBe(instance); }); }); describe('method invoking', function() { var $injector; beforeEach(function() { $injector = createInjector([function($provide) { $provide.value('book', 'moby'); $provide.value('author', 'melville'); }]); }); it('should invoke method', function() { expect($injector.invoke(function(book, author) { return author + ':' + book; })).toEqual('melville:moby'); expect($injector.invoke(function(book, author) { expect(this).toEqual($injector); return author + ':' + book; }, $injector)).toEqual('melville:moby'); }); it('should invoke method with locals', function() { expect($injector.invoke(function(book, author) { return author + ':' + book; })).toEqual('melville:moby'); expect($injector.invoke( function(book, author, chapter) { expect(this).toEqual($injector); return author + ':' + book + '-' + chapter; }, $injector, {author:'m', chapter:'ch1'})).toEqual('m:moby-ch1'); }); it('should invoke method which is annotated', function() { expect($injector.invoke(extend(function(b, a) { return a + ':' + b; }, {$inject:['book', 'author']}))).toEqual('melville:moby'); expect($injector.invoke(extend(function(b, a) { expect(this).toEqual($injector); return a + ':' + b; }, {$inject:['book', 'author']}), $injector)).toEqual('melville:moby'); }); it('should invoke method which is an array of annotation', function() { expect($injector.invoke(function(book, author) { return author + ':' + book; })).toEqual('melville:moby'); expect($injector.invoke(function(book, author) { expect(this).toEqual($injector); return author + ':' + book; }, $injector)).toEqual('melville:moby'); }); it('should throw usefull error on wrong argument type]', function() { expect(function() { $injector.invoke({}); }).toThrowMinErr("ng", "areq", "Argument 'fn' is not a function, got Object"); }); }); describe('service instantiation', function() { var $injector; beforeEach(function() { $injector = createInjector([function($provide) { $provide.value('book', 'moby'); $provide.value('author', 'melville'); }]); }); function Type(book, author) { this.book = book; this.author = author; } Type.prototype.title = function() { return this.author + ': ' + this.book; }; it('should instantiate object and preserve constructor property and be instanceof', function() { var t = $injector.instantiate(Type); expect(t.book).toEqual('moby'); expect(t.author).toEqual('melville'); expect(t.title()).toEqual('melville: moby'); expect(t instanceof Type).toBe(true); }); it('should instantiate object and preserve constructor property and be instanceof ' + 'with the array annotated type', function() { var t = $injector.instantiate(['book', 'author', Type]); expect(t.book).toEqual('moby'); expect(t.author).toEqual('melville'); expect(t.title()).toEqual('melville: moby'); expect(t instanceof Type).toBe(true); }); it('should allow constructor to return different object', function() { var obj = {}; var Class = function() { return obj; }; expect($injector.instantiate(Class)).toBe(obj); }); it('should allow constructor to return a function', function() { var fn = function() {}; var Class = function() { return fn; }; expect($injector.instantiate(Class)).toBe(fn); }); it('should handle constructor exception', function() { expect(function() { $injector.instantiate(function() { throw 'MyError'; }); }).toThrow('MyError'); }); it('should return instance if constructor returns non-object value', function() { var A = function() { return 10; }; var B = function() { return 'some-string'; }; var C = function() { return undefined; }; expect($injector.instantiate(A) instanceof A).toBe(true); expect($injector.instantiate(B) instanceof B).toBe(true); expect($injector.instantiate(C) instanceof C).toBe(true); }); }); describe('protection modes', function() { it('should prevent provider lookup in app', function() { var $injector = createInjector([function($provide) { $provide.value('name', 'angular'); }]); expect(function() { $injector.get('nameProvider'); }).toThrowMinErr("$injector", "unpr", "Unknown provider: nameProviderProvider <- nameProvider"); }); it('should prevent provider configuration in app', function() { var $injector = createInjector([]); expect(function() { $injector.get('$provide').value('a', 'b'); }).toThrowMinErr("$injector", "unpr", "Unknown provider: $provideProvider <- $provide"); }); it('should prevent instance lookup in module', function() { function instanceLookupInModule(name) { throw new Error('FAIL'); } expect(function() { createInjector([function($provide) { $provide.value('name', 'angular'); }, instanceLookupInModule]); }).toThrowError(/\[\$injector:unpr] Unknown provider: name/); }); }); }); describe('strict-di injector', function() { beforeEach(inject.strictDi(true)); describe('with ngMock', function() { it('should not throw when calling mock.module() with "magic" annotations', function() { expect(function() { module(function($provide, $httpProvider, $compileProvider) { // Don't throw! }); }).not.toThrow(); }); it('should not throw when calling mock.inject() with "magic" annotations', function() { expect(function() { inject(function($rootScope, $compile, $http) { // Don't throw! }); }).not.toThrow(); }); }); it('should throw if magic annotation is used by service', function() { module(function($provide) { $provide.service({ '$test': function() { return this; }, '$test2': function($test) { return this; } }); }); inject(function($injector) { expect(function() { $injector.invoke(function($test2) {}); }).toThrowMinErr('$injector', 'strictdi'); }); }); it('should throw if magic annotation is used by provider', function() { module(function($provide) { $provide.provider({ '$test': function() { this.$get = function($rootScope) { return $rootScope; }; } }); }); inject(function($injector) { expect(function() { $injector.invoke(['$test', function($test) {}]); }).toThrowMinErr('$injector', 'strictdi'); }); }); it('should throw if magic annotation is used by factory', function() { module(function($provide) { $provide.factory({ '$test': function($rootScope) { return function() {}; } }); }); inject(function($injector) { expect(function() { $injector.invoke(['$test', function(test) {}]); }).toThrowMinErr('$injector', 'strictdi'); }); }); it('should throw if factory does not return a value', function() { module(function($provide) { $provide.factory('$test', function() {}); }); expect(function() { inject(function($test) {}); }).toThrowMinErr('$injector', 'undef'); }); it('should always use provider as `this` when invoking a factory', function() { var called = false; function factoryFn() { called = true; // jshint -W040 expect(typeof this.$get).toBe('function'); return this; // jshint +W040 } module(function($provide) { $provide.factory('$test', factoryFn); }); inject(function($test) {}); expect(called).toBe(true); }); it('should set strictDi property to true on the injector instance', inject(function($injector) { expect($injector.strictDi).toBe(true); })); });
import React, { useState } from 'react'; import Section from 'components/Section'; import FeedbackOptions from 'components/FeedbackOptions'; import Statistics from 'components/Statistics'; import Notification from 'components/Notification'; import { Title, Wrapper } from 'styles'; function App() { const [good, setGood] = useState(0); const [neutral, setNeutral] = useState(0); const [bad, setBad] = useState(0); const feedbacks = { good, neutral, bad }; const total = Object.values(feedbacks).reduce((acc, value) => acc + value, 0); const positivePercentage = Number.parseInt((good / total) * 100); const handleClick = feedback => { switch (feedback) { case 'good': setGood(prevValue => prevValue + 1); break; case 'neutral': setNeutral(prevValue => prevValue + 1); break; case 'bad': setBad(prevValue => prevValue + 1); break; default: return; } }; return ( <div> <Title>Welcome to cafe Expresso!</Title> <Wrapper> <Section title="Please leave feedback"> <FeedbackOptions options={feedbacks} onLeaveFeedback={handleClick} /> </Section> <Section title="Statistics"> {total ? ( <Statistics good={good} neutral={neutral} bad={bad} total={total} positivePercentage={positivePercentage} /> ) : ( <Notification message="There is no feedback" /> )} </Section> </Wrapper> </div> ); } export default App;
export { default as Etherium } from './GeneralEtherium'; export { default as Bitcoin } from './GeneralBitcoin'; export { default as Volume } from './GeneralVolume'; export { default as TotalPrice } from './GeneralTotalPrice';
import Vue from 'vue' import App from './App.vue' import router from './router' import { createStore } from './store' import * as filters from './filters' import './plugins' import { parse } from '../util' import { isChrome, initEnv } from './env' import SharedData, { init as initSharedData, destroy as destroySharedData } from 'src/shared-data' import { init as initStorage } from 'src/storage' import VuexResolve from './views/vuex/resolve' // register filters for (const key in filters) { Vue.filter(key, filters[key]) } // UI let panelShown = !isChrome let pendingAction = null const chromeTheme = isChrome ? chrome.devtools.panels.themeName : undefined const isBeta = process.env.RELEASE_CHANNEL === 'beta' // Capture and log devtool errors when running as actual extension // so that we can debug it by inspecting the background page. // We do want the errors to be thrown in the dev shell though. if (isChrome) { Vue.config.errorHandler = (e, vm) => { bridge.send('ERROR', { message: e.message, stack: e.stack, component: vm.$options.name || vm.$options._componentTag || 'anonymous' }) } chrome.runtime.onMessage.addListener(request => { if (request === 'vue-panel-shown') { onPanelShown() } else if (request === 'vue-panel-hidden') { onPanelHidden() } else if (request === 'vue-get-context-menu-target') { getContextMenuInstance() } }) } Vue.options.renderError = (h, e) => { return h('pre', { style: { backgroundColor: 'red', color: 'white', fontSize: '12px', padding: '10px' } }, e.stack) } let app = null /** * Create the main devtools app. Expects to be called with a shell interface * which implements a connect method. * * @param {Object} shell * - connect(bridge => {}) * - onReload(reloadFn) */ export function initDevTools (shell) { initStorage().then(() => { initApp(shell) shell.onReload(() => { if (app) { app.$destroy() } bridge.removeAllListeners() initApp(shell) }) }) } /** * Connect then init the app. We need to reconnect on every reload, because a * new backend will be injected. * * @param {Object} shell */ function initApp (shell) { shell.connect(bridge => { window.bridge = bridge if (Vue.prototype.hasOwnProperty('$shared')) { destroySharedData() } else { Object.defineProperty(Vue.prototype, '$shared', { get: () => SharedData }) } initSharedData({ bridge, Vue, persist: true }) if (SharedData.logDetected) { bridge.send('log-detected-vue') } const store = createStore() bridge.once('ready', version => { store.commit( 'SHOW_MESSAGE', 'Ready. Detected Vue ' + version + '.' ) bridge.send('events:toggle-recording', store.state.events.enabled) if (isChrome) { chrome.runtime.sendMessage('vue-panel-load') } }) bridge.once('proxy-fail', () => { store.commit( 'SHOW_MESSAGE', 'Proxy injection failed.' ) }) bridge.on('flush', payload => { store.commit('components/FLUSH', parse(payload)) }) bridge.on('instance-details', details => { store.commit('components/RECEIVE_INSTANCE_DETAILS', parse(details)) }) bridge.on('toggle-instance', payload => { store.commit('components/TOGGLE_INSTANCE', parse(payload)) }) bridge.on('vuex:init', () => { store.commit('vuex/INIT') }) bridge.on('vuex:mutation', payload => { store.commit('vuex/RECEIVE_MUTATION', payload) }) bridge.on('vuex:inspected-state', ({ index, snapshot }) => { store.commit('vuex/RECEIVE_STATE', { index, snapshot }) if (index === -1) { store.commit('vuex/UPDATE_BASE_STATE', snapshot) } else if (store.getters['vuex/absoluteInspectedIndex'] === index) { store.commit('vuex/UPDATE_INSPECTED_STATE', snapshot) } if (VuexResolve.travel) { VuexResolve.travel(snapshot) } requestAnimationFrame(() => { SharedData.snapshotLoading = false }) }) bridge.on('event:triggered', payload => { store.commit('events/RECEIVE_EVENT', parse(payload)) if (router.currentRoute.name !== 'events') { store.commit('events/INCREASE_NEW_EVENT_COUNT') } }) bridge.on('router:init', payload => { store.commit('router/INIT', parse(payload)) }) bridge.on('router:changed', payload => { store.commit('router/CHANGED', parse(payload)) }) bridge.on('routes:init', payload => { store.commit('routes/INIT', parse(payload)) }) bridge.on('routes:changed', payload => { store.commit('routes/CHANGED', parse(payload)) }) bridge.on('events:reset', () => { store.commit('events/RESET') }) bridge.on('inspect-instance', id => { ensurePaneShown(() => { bridge.send('select-instance', id) router.push({ name: 'components' }) const instance = store.state.components.instancesMap[id] instance && store.dispatch('components/toggleInstance', { instance, expanded: true, parent: true }) }) }) bridge.on('perf:add-metric', data => { store.commit('perf/ADD_METRIC', data) }) bridge.on('perf:upsert-metric', ({ type, data }) => { store.commit('perf/UPSERT_METRIC', { type, data }) }) initEnv(Vue) app = new Vue({ extends: App, router, store, data: { isBeta }, watch: { '$shared.theme': { handler (value) { if (value === 'dark' || value === 'high-contrast' || (value === 'auto' && chromeTheme === 'dark')) { document.body.classList.add('vue-ui-dark-mode') } else { document.body.classList.remove('vue-ui-dark-mode') } if (value === 'high-contrast') { document.body.classList.add('vue-ui-high-contrast') } else { document.body.classList.remove('vue-ui-high-contrast') } }, immediate: true } } }).$mount('#app') }) } function getContextMenuInstance () { bridge.send('get-context-menu-target') } // Pane visibility management function ensurePaneShown (cb) { if (panelShown) { cb() } else { pendingAction = cb } } function onPanelShown () { panelShown = true if (pendingAction) { pendingAction() pendingAction = null } } function onPanelHidden () { panelShown = false }
import moment from 'moment'; /** * validSubmission checks whether a submission is valid - sets a validity obj props to check results * @param {Object} item - the new incoming item * @param {Array} validSelections array of valid selections e.g. 0,1 in our case * @return {Object} returns object containing validity info */ export default function validSubmission(item, validSelections) { const isSelectionValid = num => validSelections.indexOf(num) !== -1; const isPriceValid = num => num >= 0 && !isNaN(num) && typeof num === 'number'; const newInputValidity = { itemType: isSelectionValid(item.itemType), userType: isSelectionValid(item.userType), price: isPriceValid(item.price), endDate: moment(item.endDate).isValid() } newInputValidity.isValid = Object.values(newInputValidity).indexOf(false) === -1; return newInputValidity; }
$(document).ready(() => { let editor = new TinyEditor() editor.init() })
require('./bootstrap'); import Vue from 'vue/dist/vue.min.js'; // install Vue.component('alert-table', require('./components/AlertTable').default); const app = new Vue({ el: '#header', });
export default { title: "Aphrodite" }
export { default } from './AdditionInfo';
import { assert } from 'chai'; import * as RA from '../src'; describe('lengthEq', function() { context( 'given the length of a list is equal to the supplied length', function() { specify('should return true', function() { assert.isTrue(RA.lengthEq(3, [1, 2, 3])); assert.isFalse(RA.lengthEq(3, [1, 2, 3, 4])); assert.isFalse(RA.lengthEq(3, [1, 2])); assert.isTrue(RA.lengthEq(0, [])); }); } ); context( 'given the length of a string is equal to the supplied length', function() { specify('should return true', function() { assert.isTrue(RA.lengthEq(3, 'abc')); assert.isFalse(RA.lengthEq(3, 'abcd')); assert.isFalse(RA.lengthEq(3, 'ab')); assert.isTrue(RA.lengthEq(0, '')); }); } ); context("given a value doesn't have a length property", function() { specify('should return true', function() { assert.isFalse(RA.lengthEq(1, NaN)); assert.isFalse(RA.lengthEq(1, undefined)); assert.isFalse(RA.lengthEq(1, null)); assert.isFalse(RA.lengthEq(1, {})); assert.isFalse(RA.lengthEq(1, true)); assert.isFalse(RA.lengthEq(1, false)); assert.isFalse(RA.lengthEq(1, 5)); }); }); it('should be curried', function() { assert.isTrue(RA.lengthEq(2, [1, 2])); assert.isTrue(RA.lengthEq(2)([1, 2])); }); });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var React = require("react"); var VerticalDivider_classNames_1 = require("./VerticalDivider.classNames"); var Styling_1 = require("../../Styling"); exports.VerticalDivider = function (props) { var theme = Styling_1.getTheme(); var classNames = props.getClassNames ? props.getClassNames(theme) : VerticalDivider_classNames_1.getDividerClassNames(theme); return (React.createElement("span", { className: classNames.wrapper }, React.createElement("span", { className: classNames.divider }))); }; //# sourceMappingURL=VerticalDivider.js.map
import path from 'path'; import { runEmit } from './helpers/run'; const FIXTURES_DIR = path.join(__dirname, 'fixtures'); describe('context option', () => { it('should work when "from" is a file', (done) => { runEmit({ expectedAssetKeys: ['directoryfile.txt'], patterns: [ { from: 'directoryfile.txt', context: 'directory', }, ], }) .then(done) .catch(done); }); it('should work when "from" is a file and "context" with special characters', (done) => { runEmit({ expectedAssetKeys: ['directoryfile.txt'], patterns: [ { from: 'directoryfile.txt', context: '[special?directory]', }, ], }) .then(done) .catch(done); }); it('should work when "from" is a directory', (done) => { runEmit({ expectedAssetKeys: ['deep-nested/deepnested.txt', 'nestedfile.txt'], patterns: [ { from: 'nested', context: 'directory', }, ], }) .then(done) .catch(done); }); it('should work when "from" is a directory and "to" is a new directory', (done) => { runEmit({ expectedAssetKeys: [ 'newdirectory/deep-nested/deepnested.txt', 'newdirectory/nestedfile.txt', ], patterns: [ { context: 'directory', from: 'nested', to: 'newdirectory', }, ], }) .then(done) .catch(done); }); it('should work when "from" is a directory and "context" with special characters', (done) => { runEmit({ expectedAssetKeys: [ 'directoryfile.txt', '(special-*file).txt', 'nested/nestedfile.txt', ], patterns: [ { // Todo strange behavour when you use `FIXTURES_DIR`, need investigate for next major release from: '.', context: '[special?directory]', }, ], }) .then(done) .catch(done); }); it('should work when "from" is a glob', (done) => { runEmit({ expectedAssetKeys: [ 'nested/deep-nested/deepnested.txt', 'nested/nestedfile.txt', ], patterns: [ { from: 'nested/**/*', context: 'directory', }, ], }) .then(done) .catch(done); }); it('should work when "from" is a glob and "to" is a directory', (done) => { runEmit({ expectedAssetKeys: [ 'nested/directoryfile.txt', 'nested/nested/deep-nested/deepnested.txt', 'nested/nested/nestedfile.txt', ], patterns: [ { context: 'directory', from: '**/*', to: 'nested', }, ], }) .then(done) .catch(done); }); it('should work when "from" is a glob and "to" is a directory and "content" is an absolute path', (done) => { runEmit({ expectedAssetKeys: [ 'nested/directoryfile.txt', 'nested/nested/deep-nested/deepnested.txt', 'nested/nested/nestedfile.txt', ], patterns: [ { context: path.join(FIXTURES_DIR, 'directory'), from: '**/*', to: 'nested', }, ], }) .then(done) .catch(done); }); it('should work when "from" is a glob and "context" with special characters', (done) => { runEmit({ expectedAssetKeys: [ 'directoryfile.txt', '(special-*file).txt', 'nested/nestedfile.txt', ], patterns: [ { from: '**/*', context: '[special?directory]', }, ], }) .then(done) .catch(done); }); it('should work when "from" is a glob and "context" with special characters #2', (done) => { runEmit({ expectedAssetKeys: ['(special-*file).txt'], patterns: [ { from: '(special-*file).txt', context: '[special?directory]', }, ], }) .then(done) .catch(done); }); it('should work when "from" is a file and "context" is an absolute path', (done) => { runEmit({ expectedAssetKeys: ['directoryfile.txt'], patterns: [ { from: 'directoryfile.txt', context: path.join(FIXTURES_DIR, 'directory'), }, ], }) .then(done) .catch(done); }); it('should override webpack config context with an absolute path', (done) => { runEmit({ expectedAssetKeys: [ 'newdirectory/deep-nested/deepnested.txt', 'newdirectory/nestedfile.txt', ], options: { context: path.join(FIXTURES_DIR, 'directory'), }, patterns: [ { from: 'nested', to: 'newdirectory', }, ], }) .then(done) .catch(done); }); it('should override webpack config context with a relative path', (done) => { runEmit({ expectedAssetKeys: [ 'newdirectory/deep-nested/deepnested.txt', 'newdirectory/nestedfile.txt', ], options: { context: 'directory', }, patterns: [ { from: 'nested', to: 'newdirectory', }, ], }) .then(done) .catch(done); }); it('should override global context on pattern context with a relative path', (done) => { runEmit({ expectedAssetKeys: [ 'newdirectory/deep-nested/deepnested.txt', 'newdirectory/nestedfile.txt', ], options: { context: 'directory', }, patterns: [ { context: 'nested', from: '.', to: 'newdirectory', }, ], }) .then(done) .catch(done); }); it('overrides webpack config context with an absolute path', (done) => { runEmit({ expectedAssetKeys: [ 'newdirectory/file.txt', 'newdirectory/nesteddir/deepnesteddir/deepnesteddir.txt', 'newdirectory/nesteddir/nestedfile.txt', ], options: { context: path.join(FIXTURES_DIR, 'dir (86)'), }, patterns: [ { from: '**/*', to: 'newdirectory', }, ], }) .then(done) .catch(done); }); });
var Content = function() { var root = $('.main'); var element = function(selector) { return root.find(selector); }; var focus = Focus(); var scroll = { mainbar: 0, sidebar: 0, save : function() { scroll.mainbar = $('.mainbar').scrollTop(); scroll.sidebar = $('.sidebar').scrollTop(); }, restore: function() { if($('.mainbar')[0]) $('.mainbar')[0].scrollTop = scroll.mainbar; if($('.sidebar')[0]) $('.sidebar')[0].scrollTop = scroll.sidebar; } }; var on = function() { // make sure everything is nice and clean first off(); // setup the breadcrumb mobile version element('.breadcrumb').breadcrumb(); // setup the sidebar toggle element('.sidebar').sidebar(); // register all keyboard shortcuts within the main container root.shortcuts(); app.delay.start('message', function() { element('.message-is-notice').trigger('click'); }, 3000); element('.message a, .message').on('click', function(e) { element('.mainbar .field-with-error').removeClass('field-with-error'); element('.message').remove(); app.delay.stop('message'); return false; }); // hook up the main form Form('.main .form', { submit: function() { scroll.save(); }, redirect: function(response) { if($.type(response) == 'object' && response.url) { open(response.url); } else { replace(response.content); } } }); // recall the focus and caret position focus.on('.mainbar .form'); }; // clean all registered events and remove generated elements var off = function() { // stop all delays app.delay.stop(); // stop caret recording focus.off(); // remove all shortcuts $(document).unbind('keydown.shortcuts'); // remove window resizing events $(window).off('resize'); }; var open = function(url, state) { app.load(url, 'content', function(response) { // handle redirects if(response.url) { open(response.url); } else { replace(response.content, url); } }); }; var replace = function(content, url) { // close all context menus $(document).trigger('click.contextmenu'); // close all modals app.modal.close(); root.html(content); // change the history if(url) { if(window.location.href != url) { focus.forget(); try { path = url.replace(window.location.origin, ''); window.history.pushState({path: path}, document.title, path); } catch(e) { window.location.href = url; } } } // switch on all events for the mainbar on(); // restore the previous scroll position scroll.restore(); }; var reload = function() { scroll.save(); open(document.location); }; var shortcuts = function() { root.shortcuts(); }; var form = function() { return $('.main .form'); }; var setup = function() { $(window).on('popstate', function(e) { open(document.location); }); on(); }; return { root : root, element: element, on: on, off: off, open: open, replace: replace, reload: reload, shortcuts: shortcuts, form: form, focus: focus, setup: setup, scroll: scroll }; };
__NUXT_JSONP__("/12/22", (function(a,b,c,d,e,f,g,h){return {data:[{metaTitle:b,metaDesc:c,verseId:22,surahId:12,currentSurah:{number:"12",name:"يوسف",name_latin:d,number_of_ayah:"111",text:{"1":"الۤرٰ ۗ تِلْكَ اٰيٰتُ الْكِتٰبِ الْمُبِيْنِۗ ","2":"اِنَّآ اَنْزَلْنٰهُ قُرْاٰنًا عَرَبِيًّا لَّعَلَّكُمْ تَعْقِلُوْنَ","3":"نَحْنُ نَقُصُّ عَلَيْكَ اَحْسَنَ الْقَصَصِ بِمَآ اَوْحَيْنَآ اِلَيْكَ هٰذَا الْقُرْاٰنَۖ وَاِنْ كُنْتَ مِنْ قَبْلِهٖ لَمِنَ الْغٰفِلِيْنَ","4":"اِذْ قَالَ يُوْسُفُ لِاَبِيْهِ يٰٓاَبَتِ اِنِّيْ رَاَيْتُ اَحَدَ عَشَرَ كَوْكَبًا وَّالشَّمْسَ وَالْقَمَرَ رَاَيْتُهُمْ لِيْ سٰجِدِيْنَ","5":"قَالَ يٰبُنَيَّ لَا تَقْصُصْ رُءْيَاكَ عَلٰٓى اِخْوَتِكَ فَيَكِيْدُوْا لَكَ كَيْدًا ۗاِنَّ الشَّيْطٰنَ لِلْاِنْسَانِ عَدُوٌّ مُّبِيْنٌ","6":"وَكَذٰلِكَ يَجْتَبِيْكَ رَبُّكَ وَيُعَلِّمُكَ مِنْ تَأْوِيْلِ الْاَحَادِيْثِ وَيُتِمُّ نِعْمَتَهٗ عَلَيْكَ وَعَلٰٓى اٰلِ يَعْقُوْبَ كَمَآ اَتَمَّهَا عَلٰٓى اَبَوَيْكَ مِنْ قَبْلُ اِبْرٰهِيْمَ وَاِسْحٰقَۗ اِنَّ رَبَّكَ عَلِيْمٌ حَكِيْمٌ ࣖ","7":"۞ لَقَدْ كَانَ فِيْ يُوْسُفَ وَاِخْوَتِهٖٓ اٰيٰتٌ لِّلسَّاۤىِٕلِيْنَ ","8":"اِذْ قَالُوْا لَيُوْسُفُ وَاَخُوْهُ اَحَبُّ اِلٰٓى اَبِيْنَا مِنَّا وَنَحْنُ عُصْبَةٌ ۗاِنَّ اَبَانَا لَفِيْ ضَلٰلٍ مُّبِيْنٍۙ ","9":" ۨاقْتُلُوْا يُوْسُفَ اَوِ اطْرَحُوْهُ اَرْضًا يَّخْلُ لَكُمْ وَجْهُ اَبِيْكُمْ وَتَكُوْنُوْا مِنْۢ بَعْدِهٖ قَوْمًا صٰلِحِيْنَ","10":"قَالَ قَاۤئِلٌ مِّنْهُمْ لَا تَقْتُلُوْا يُوْسُفَ وَاَلْقُوْهُ فِيْ غَيٰبَتِ الْجُبِّ يَلْتَقِطْهُ بَعْضُ السَّيَّارَةِ اِنْ كُنْتُمْ فٰعِلِيْنَ","11":"قَالُوْا يٰٓاَبَانَا مَالَكَ لَا تَأْمَنَّ۫ا عَلٰى يُوْسُفَ وَاِنَّا لَهٗ لَنَاصِحُوْنَ","12":"اَرْسِلْهُ مَعَنَا غَدًا يَّرْتَعْ وَيَلْعَبْ وَاِنَّا لَهٗ لَحٰفِظُوْنَ","13":"قَالَ اِنِّيْ لَيَحْزُنُنِيْٓ اَنْ تَذْهَبُوْا بِهٖ وَاَخَافُ اَنْ يَّأْكُلَهُ الذِّئْبُ وَاَنْتُمْ عَنْهُ غٰفِلُوْنَ ","14":"قَالُوْا لَىِٕنْ اَكَلَهُ الذِّئْبُ وَنَحْنُ عُصْبَةٌ اِنَّآ اِذًا لَّخٰسِرُوْنَ","15":"فَلَمَّا ذَهَبُوْا بِهٖ وَاَجْمَعُوْٓا اَنْ يَّجْعَلُوْهُ فِيْ غَيٰبَتِ الْجُبِّۚ وَاَوْحَيْنَآ اِلَيْهِ لَتُنَبِّئَنَّهُمْ بِاَمْرِهِمْ هٰذَا وَهُمْ لَا يَشْعُرُوْنَ","16":"وَجَاۤءُوْٓ اَبَاهُمْ عِشَاۤءً يَّبْكُوْنَۗ","17":"قَالُوْا يٰٓاَبَانَآ اِنَّا ذَهَبْنَا نَسْتَبِقُ وَتَرَكْنَا يُوْسُفَ عِنْدَ مَتَاعِنَا فَاَكَلَهُ الذِّئْبُۚ وَمَآ اَنْتَ بِمُؤْمِنٍ لَّنَا وَلَوْ كُنَّا صٰدِقِيْنَ","18":"وَجَاۤءُوْ عَلٰى قَمِيْصِهٖ بِدَمٍ كَذِبٍۗ قَالَ بَلْ سَوَّلَتْ لَكُمْ اَنْفُسُكُمْ اَمْرًاۗ فَصَبْرٌ جَمِيْلٌ ۗوَاللّٰهُ الْمُسْتَعَانُ عَلٰى مَا تَصِفُوْنَ","19":"وَجَاۤءَتْ سَيَّارَةٌ فَاَرْسَلُوْا وَارِدَهُمْ فَاَدْلٰى دَلْوَهٗ ۗقَالَ يٰبُشْرٰى هٰذَا غُلٰمٌ ۗوَاَسَرُّوْهُ بِضَاعَةً ۗوَاللّٰهُ عَلِيْمٌ ۢبِمَا يَعْمَلُوْنَ","20":"وَشَرَوْهُ بِثَمَنٍۢ بَخْسٍ دَرَاهِمَ مَعْدُوْدَةٍ ۚوَكَانُوْا فِيْهِ مِنَ الزَّاهِدِيْنَ ࣖ ","21":"وَقَالَ الَّذِى اشْتَرٰىهُ مِنْ مِّصْرَ لِامْرَاَتِهٖٓ اَكْرِمِيْ مَثْوٰىهُ عَسٰىٓ اَنْ يَّنْفَعَنَآ اَوْ نَتَّخِذَهٗ وَلَدًا ۗوَكَذٰلِكَ مَكَّنَّا لِيُوْسُفَ فِى الْاَرْضِۖ وَلِنُعَلِّمَهٗ مِنْ تَأْوِيْلِ الْاَحَادِيْثِۗ وَاللّٰهُ غَالِبٌ عَلٰٓى اَمْرِهٖ وَلٰكِنَّ اَكْثَرَ النَّاسِ لَا يَعْلَمُوْنَ","22":"وَلَمَّا بَلَغَ اَشُدَّهٗٓ اٰتَيْنٰهُ حُكْمًا وَّعِلْمًا ۗوَكَذٰلِكَ نَجْزِى الْمُحْسِنِيْنَ","23":"وَرَاوَدَتْهُ الَّتِيْ هُوَ فِيْ بَيْتِهَا عَنْ نَّفْسِهٖ وَغَلَّقَتِ الْاَبْوَابَ وَقَالَتْ هَيْتَ لَكَ ۗقَالَ مَعَاذَ اللّٰهِ اِنَّهٗ رَبِّيْٓ اَحْسَنَ مَثْوَايَۗ اِنَّهٗ لَا يُفْلِحُ الظّٰلِمُوْنَ","24":"وَلَقَدْ هَمَّتْ بِهٖۙ وَهَمَّ بِهَا ۚ لَوْلَآ اَنْ رَّاٰى بُرْهَانَ رَبِّهٖۗ كَذٰلِكَ لِنَصْرِفَ عَنْهُ السُّوْۤءَ وَالْفَحْشَاۤءَۗ اِنَّهٗ مِنْ عِبَادِنَا الْمُخْلَصِيْنَ ","25":"وَاسْتَبَقَا الْبَابَ وَقَدَّتْ قَمِيْصَهٗ مِنْ دُبُرٍ وَّاَلْفَيَا سَيِّدَهَا لَدَا الْبَابِۗ قَالَتْ مَا جَزَاۤءُ مَنْ اَرَادَ بِاَهْلِكَ سُوْۤءًا اِلَّآ اَنْ يُّسْجَنَ اَوْ عَذَابٌ اَلِيْمٌ ","26":"قَالَ هِيَ رَاوَدَتْنِيْ عَنْ نَّفْسِيْ وَشَهِدَ شَاهِدٌ مِّنْ اَهْلِهَاۚ اِنْ كَانَ قَمِيْصُهٗ قُدَّ مِنْ قُبُلٍ فَصَدَقَتْ وَهُوَ مِنَ الْكٰذِبِيْنَ ","27":"وَاِنْ كَانَ قَمِيْصُهٗ قُدَّ مِنْ دُبُرٍ فَكَذَبَتْ وَهُوَ مِنَ الصّٰدِقِيْنَ ","28":"فَلَمَّا رَاٰى قَمِيْصَهٗ قُدَّ مِنْ دُبُرٍ قَالَ اِنَّهٗ مِنْ كَيْدِكُنَّ ۗاِنَّ كَيْدَكُنَّ عَظِيْمٌ ","29":"يُوْسُفُ اَعْرِضْ عَنْ هٰذَا وَاسْتَغْفِرِيْ لِذَنْۢبِكِۖ اِنَّكِ كُنْتِ مِنَ الْخٰطِـِٕيْنَ ࣖ ","30":"۞ وَقَالَ نِسْوَةٌ فِى الْمَدِيْنَةِ امْرَاَتُ الْعَزِيْزِ تُرَاوِدُ فَتٰىهَا عَنْ نَّفْسِهٖۚ قَدْ شَغَفَهَا حُبًّاۗ اِنَّا لَنَرٰىهَا فِيْ ضَلٰلٍ مُّبِيْنٍ ","31":"فَلَمَّا سَمِعَتْ بِمَكْرِهِنَّ اَرْسَلَتْ اِلَيْهِنَّ وَاَعْتَدَتْ لَهُنَّ مُتَّكَاً وَّاٰتَتْ كُلَّ وَاحِدَةٍ مِّنْهُنَّ سِكِّيْنًا وَّقَالَتِ اخْرُجْ عَلَيْهِنَّ ۚ فَلَمَّا رَاَيْنَهٗٓ اَكْبَرْنَهٗ وَقَطَّعْنَ اَيْدِيَهُنَّۖ وَقُلْنَ حَاشَ لِلّٰهِ مَا هٰذَا بَشَرًاۗ اِنْ هٰذَآ اِلَّا مَلَكٌ كَرِيْمٌ ","32":"قَالَتْ فَذٰلِكُنَّ الَّذِيْ لُمْتُنَّنِيْ فِيْهِ ۗوَلَقَدْ رَاوَدْتُّهٗ عَنْ نَّفْسِهٖ فَاسْتَعْصَمَ ۗوَلَىِٕنْ لَّمْ يَفْعَلْ مَآ اٰمُرُهٗ لَيُسْجَنَنَّ وَلَيَكُوْنًا مِّنَ الصّٰغِرِيْنَ ","33":"قَالَ رَبِّ السِّجْنُ اَحَبُّ اِلَيَّ مِمَّا يَدْعُوْنَنِيْٓ اِلَيْهِ ۚوَاِلَّا تَصْرِفْ عَنِّيْ كَيْدَهُنَّ اَصْبُ اِلَيْهِنَّ وَاَكُنْ مِّنَ الْجٰهِلِيْنَ ","34":"فَاسْتَجَابَ لَهٗ رَبُّهٗ فَصَرَفَ عَنْهُ كَيْدَهُنَّ ۗاِنَّهٗ هُوَ السَّمِيْعُ الْعَلِيْمُ ","35":"ثُمَّ بَدَا لَهُمْ مِّنْۢ بَعْدِ مَا رَاَوُا الْاٰيٰتِ لَيَسْجُنُنَّهٗ حَتّٰى حِيْنٍ ࣖ ","36":"وَدَخَلَ مَعَهُ السِّجْنَ فَتَيٰنِ ۗقَالَ اَحَدُهُمَآ اِنِّيْٓ اَرٰىنِيْٓ اَعْصِرُ خَمْرًا ۚوَقَالَ الْاٰخَرُ اِنِّيْٓ اَرٰىنِيْٓ اَحْمِلُ فَوْقَ رَأْسِيْ خُبْزًا تَأْكُلُ الطَّيْرُ مِنْهُ ۗنَبِّئْنَا بِتَأْوِيْلِهٖ ۚاِنَّا نَرٰىكَ مِنَ الْمُحْسِنِيْنَ","37":"قَالَ لَا يَأْتِيْكُمَا طَعَامٌ تُرْزَقٰنِهٖٓ اِلَّا نَبَّأْتُكُمَا بِتَأْوِيْلِهٖ قَبْلَ اَنْ يَّأْتِيَكُمَا ۗذٰلِكُمَا مِمَّا عَلَّمَنِيْ رَبِّيْۗ اِنِّيْ تَرَكْتُ مِلَّةَ قَوْمٍ لَّا يُؤْمِنُوْنَ بِاللّٰهِ وَهُمْ بِالْاٰخِرَةِ هُمْ كٰفِرُوْنَۙ ","38":"وَاتَّبَعْتُ مِلَّةَ اٰبَاۤءِيْٓ اِبْرٰهِيْمَ وَاِسْحٰقَ وَيَعْقُوْبَۗ مَا كَانَ لَنَآ اَنْ نُّشْرِكَ بِاللّٰهِ مِنْ شَيْءٍۗ ذٰلِكَ مِنْ فَضْلِ اللّٰهِ عَلَيْنَا وَعَلَى النَّاسِ وَلٰكِنَّ اَكْثَرَ النَّاسِ لَا يَشْكُرُوْنَ","39":"يٰصَاحِبَيِ السِّجْنِ ءَاَرْبَابٌ مُتَفَرِّقُوْنَ خَيْرٌ اَمِ اللّٰهُ الْوَاحِدُ الْقَهَّارُۗ ","40":"مَا تَعْبُدُوْنَ مِنْ دُوْنِهٖٓ اِلَّآ اَسْمَاۤءً سَمَّيْتُمُوْهَآ اَنْتُمْ وَاٰبَاۤؤُكُمْ مَّآ اَنْزَلَ اللّٰهُ بِهَا مِنْ سُلْطٰنٍۗ اِنِ الْحُكْمُ اِلَّا لِلّٰهِ ۗاَمَرَ اَلَّا تَعْبُدُوْٓا اِلَّآ اِيَّاهُ ۗذٰلِكَ الدِّيْنُ الْقَيِّمُ وَلٰكِنَّ اَكْثَرَ النَّاسِ لَا يَعْلَمُوْنَ ","41":"يٰصَاحِبَيِ السِّجْنِ اَمَّآ اَحَدُكُمَا فَيَسْقِيْ رَبَّهٗ خَمْرًا ۗوَاَمَّا الْاٰخَرُ فَيُصْلَبُ فَتَأْكُلُ الطَّيْرُ مِنْ رَّأْسِهٖ ۗ قُضِيَ الْاَمْرُ الَّذِيْ فِيْهِ تَسْتَفْتِيٰنِۗ ","42":"وَقَالَ لِلَّذِيْ ظَنَّ اَنَّهٗ نَاجٍ مِّنْهُمَا اذْكُرْنِيْ عِنْدَ رَبِّكَۖ فَاَنْسٰىهُ الشَّيْطٰنُ ذِكْرَ رَبِّهٖ فَلَبِثَ فِى السِّجْنِ بِضْعَ سِنِيْنَ ࣖ ","43":"وَقَالَ الْمَلِكُ اِنِّيْٓ اَرٰى سَبْعَ بَقَرٰتٍ سِمَانٍ يَّأْكُلُهُنَّ سَبْعٌ عِجَافٌ وَّسَبْعَ سُنْۢبُلٰتٍ خُضْرٍ وَّاُخَرَ يٰبِسٰتٍۗ يٰٓاَيُّهَا الْمَلَاُ اَفْتُوْنِيْ فِيْ رُؤْيَايَ اِنْ كُنْتُمْ لِلرُّءْيَا تَعْبُرُوْنَ","44":"قَالُوْٓا اَضْغَاثُ اَحْلَامٍ ۚوَمَا نَحْنُ بِتَأْوِيْلِ الْاَحْلَامِ بِعٰلِمِيْنَ ","45":"وَقَالَ الَّذِيْ نَجَا مِنْهُمَا وَادَّكَرَ بَعْدَ اُمَّةٍ اَنَا۠ اُنَبِّئُكُمْ بِتَأْوِيْلِهٖ فَاَرْسِلُوْنِ ","46":"يُوْسُفُ اَيُّهَا الصِّدِّيْقُ اَفْتِنَا فِيْ سَبْعِ بَقَرٰتٍ سِمَانٍ يَّأْكُلُهُنَّ سَبْعٌ عِجَافٌ وَّسَبْعِ سُنْۢبُلٰتٍ خُضْرٍ وَّاُخَرَ يٰبِسٰتٍۙ لَّعَلِّيْٓ اَرْجِعُ اِلَى النَّاسِ لَعَلَّهُمْ يَعْلَمُوْنَ ","47":"قَالَ تَزْرَعُوْنَ سَبْعَ سِنِيْنَ دَاَبًاۚ فَمَا حَصَدْتُّمْ فَذَرُوْهُ فِيْ سُنْۢبُلِهٖٓ اِلَّا قَلِيْلًا مِّمَّا تَأْكُلُوْنَ ","48":"ثُمَّ يَأْتِيْ مِنْۢ بَعْدِ ذٰلِكَ سَبْعٌ شِدَادٌ يَّأْكُلْنَ مَا قَدَّمْتُمْ لَهُنَّ اِلَّا قَلِيْلًا مِّمَّا تُحْصِنُوْنَ","49":"ثُمَّ يَأْتِيْ مِنْۢ بَعْدِ ذٰلِكَ عَامٌ فِيْهِ يُغَاثُ النَّاسُ وَفِيْهِ يَعْصِرُوْنَ ࣖ","50":"وَقَالَ الْمَلِكُ ائْتُوْنِيْ بِهٖ ۚفَلَمَّا جَاۤءَهُ الرَّسُوْلُ قَالَ ارْجِعْ اِلٰى رَبِّكَ فَسْـَٔلْهُ مَا بَالُ النِّسْوَةِ الّٰتِيْ قَطَّعْنَ اَيْدِيَهُنَّ ۗاِنَّ رَبِّيْ بِكَيْدِهِنَّ عَلِيْمٌ ","51":"قَالَ مَا خَطْبُكُنَّ اِذْ رَاوَدْتُّنَّ يُوْسُفَ عَنْ نَّفْسِهٖۗ قُلْنَ حَاشَ لِلّٰهِ مَا عَلِمْنَا عَلَيْهِ مِنْ سُوْۤءٍ ۗقَالَتِ امْرَاَتُ الْعَزِيْزِ الْـٰٔنَ حَصْحَصَ الْحَقُّۖ اَنَا۠ رَاوَدْتُّهٗ عَنْ نَّفْسِهٖ وَاِنَّهٗ لَمِنَ الصّٰدِقِيْنَ ","52":"ذٰلِكَ لِيَعْلَمَ اَنِّيْ لَمْ اَخُنْهُ بِالْغَيْبِ وَاَنَّ اللّٰهَ لَا يَهْدِيْ كَيْدَ الْخَاۤىِٕنِيْنَ ۔","53":"۞ وَمَآ اُبَرِّئُ نَفْسِيْۚ اِنَّ النَّفْسَ لَاَمَّارَةٌ ۢ بِالسُّوْۤءِ اِلَّا مَا رَحِمَ رَبِّيْۗ اِنَّ رَبِّيْ غَفُوْرٌ رَّحِيْمٌ","54":"وَقَالَ الْمَلِكُ ائْتُوْنِيْ بِهٖٓ اَسْتَخْلِصْهُ لِنَفْسِيْۚ فَلَمَّا كَلَّمَهٗ قَالَ اِنَّكَ الْيَوْمَ لَدَيْنَا مَكِيْنٌ اَمِيْنٌ","55":"قَالَ اجْعَلْنِيْ عَلٰى خَزَاۤىِٕنِ الْاَرْضِۚ اِنِّيْ حَفِيْظٌ عَلِيْمٌ","56":"وَكَذٰلِكَ مَكَّنَّا لِيُوْسُفَ فِى الْاَرْضِ يَتَبَوَّاُ مِنْهَا حَيْثُ يَشَاۤءُۗ نُصِيْبُ بِرَحْمَتِنَا مَنْ نَّشَاۤءُ وَلَا نُضِيْعُ اَجْرَ الْمُحْسِنِيْنَ","57":"وَلَاَجْرُ الْاٰخِرَةِ خَيْرٌ لِّلَّذِيْنَ اٰمَنُوْا وَكَانُوْا يَتَّقُوْنَ ࣖ","58":"وَجَاۤءَ اِخْوَةُ يُوْسُفَ فَدَخَلُوْا عَلَيْهِ فَعَرَفَهُمْ وَهُمْ لَهٗ مُنْكِرُوْنَ","59":"وَلَمَّا جَهَّزَهُمْ بِجَهَازِهِمْ قَالَ ائْتُوْنِيْ بِاَخٍ لَّكُمْ مِّنْ اَبِيْكُمْ ۚ اَلَا تَرَوْنَ اَنِّيْٓ اُوْفِى الْكَيْلَ وَاَنَا۠ خَيْرُ الْمُنْزِلِيْنَ ","60":"فَاِنْ لَّمْ تَأْتُوْنِيْ بِهٖ فَلَا كَيْلَ لَكُمْ عِنْدِيْ وَلَا تَقْرَبُوْنِ","61":"قَالُوْا سَنُرَاوِدُ عَنْهُ اَبَاهُ وَاِنَّا لَفَاعِلُوْنَ","62":"وَقَالَ لِفِتْيٰنِهِ اجْعَلُوْا بِضَاعَتَهُمْ فِيْ رِحَالِهِمْ لَعَلَّهُمْ يَعْرِفُوْنَهَآ اِذَا انْقَلَبُوْٓا اِلٰٓى اَهْلِهِمْ لَعَلَّهُمْ يَرْجِعُوْنَ","63":"فَلَمَّا رَجَعُوْٓا اِلٰٓى اَبِيْهِمْ قَالُوْا يٰٓاَبَانَا مُنِعَ مِنَّا الْكَيْلُ فَاَرْسِلْ مَعَنَآ اَخَانَا نَكْتَلْ وَاِنَّا لَهٗ لَحٰفِظُوْنَ","64":"قَالَ هَلْ اٰمَنُكُمْ عَلَيْهِ اِلَّا كَمَآ اَمِنْتُكُمْ عَلٰٓى اَخِيْهِ مِنْ قَبْلُۗ فَاللّٰهُ خَيْرٌ حٰفِظًا وَّهُوَ اَرْحَمُ الرّٰحِمِيْنَ","65":"وَلَمَّا فَتَحُوْا مَتَاعَهُمْ وَجَدُوْا بِضَاعَتَهُمْ رُدَّتْ اِلَيْهِمْۗ قَالُوْا يٰٓاَبَانَا مَا نَبْغِيْۗ هٰذِهٖ بِضَاعَتُنَا رُدَّتْ اِلَيْنَا وَنَمِيْرُ اَهْلَنَا وَنَحْفَظُ اَخَانَا وَنَزْدَادُ كَيْلَ بَعِيْرٍۗ ذٰلِكَ كَيْلٌ يَّسِيْرٌ","66":"قَالَ لَنْ اُرْسِلَهٗ مَعَكُمْ حَتّٰى تُؤْتُوْنِ مَوْثِقًا مِّنَ اللّٰهِ لَتَأْتُنَّنِيْ بِهٖٓ اِلَّآ اَنْ يُّحَاطَ بِكُمْۚ فَلَمَّآ اٰتَوْهُ مَوْثِقَهُمْ قَالَ اللّٰهُ عَلٰى مَا نَقُوْلُ وَكِيْلٌ","67":"وَقَالَ يٰبَنِيَّ لَا تَدْخُلُوْا مِنْۢ بَابٍ وَّاحِدٍ وَّادْخُلُوْا مِنْ اَبْوَابٍ مُّتَفَرِّقَةٍۗ وَمَآ اُغْنِيْ عَنْكُمْ مِّنَ اللّٰهِ مِنْ شَيْءٍۗ اِنِ الْحُكْمُ اِلَّا لِلّٰهِ ۗعَلَيْهِ تَوَكَّلْتُ وَعَلَيْهِ فَلْيَتَوَكَّلِ الْمُتَوَكِّلُوْنَ","68":"وَلَمَّا دَخَلُوْا مِنْ حَيْثُ اَمَرَهُمْ اَبُوْهُمْۗ مَا كَانَ يُغْنِيْ عَنْهُمْ مِّنَ اللّٰهِ مِنْ شَيْءٍ اِلَّا حَاجَةً فِيْ نَفْسِ يَعْقُوْبَ قَضٰىهَاۗ وَاِنَّهٗ لَذُوْ عِلْمٍ لِّمَا عَلَّمْنٰهُ وَلٰكِنَّ اَكْثَرَ النَّاسِ لَا يَعْلَمُوْنَ ࣖ","69":"وَلَمَّا دَخَلُوْا عَلٰى يُوْسُفَ اٰوٰٓى اِلَيْهِ اَخَاهُ قَالَ اِنِّيْٓ اَنَا۠ اَخُوْكَ فَلَا تَبْتَىِٕسْ بِمَا كَانُوْا يَعْمَلُوْنَ","70":"فَلَمَّا جَهَّزَهُمْ بِجَهَازِهِمْ جَعَلَ السِّقَايَةَ فِيْ رَحْلِ اَخِيْهِ ثُمَّ اَذَّنَ مُؤَذِّنٌ اَيَّتُهَا الْعِيْرُ اِنَّكُمْ لَسَارِقُوْنَ","71":"قَالُوْا وَاَقْبَلُوْا عَلَيْهِمْ مَّاذَا تَفْقِدُوْنَ","72":"قَالُوْا نَفْقِدُ صُوَاعَ الْمَلِكِ وَلِمَنْ جَاۤءَ بِهٖ حِمْلُ بَعِيْرٍ وَّاَنَا۠ بِهٖ زَعِيْمٌ","73":"قَالُوْا تَاللّٰهِ لَقَدْ عَلِمْتُمْ مَّا جِئْنَا لِنُفْسِدَ فِى الْاَرْضِ وَمَا كُنَّا سَارِقِيْنَ","74":"قَالُوْا فَمَا جَزَاۤؤُهٗٓ اِنْ كُنْتُمْ كٰذِبِيْنَ","75":"قَالُوْا جَزَاۤؤُهٗ مَنْ وُّجِدَ فِيْ رَحْلِهٖ فَهُوَ جَزَاۤؤُهٗ ۗ كَذٰلِكَ نَجْزِى الظّٰلِمِيْنَ","76":"فَبَدَاَ بِاَوْعِيَتِهِمْ قَبْلَ وِعَاۤءِ اَخِيْهِ ثُمَّ اسْتَخْرَجَهَا مِنْ وِّعَاۤءِ اَخِيْهِۗ كَذٰلِكَ كِدْنَا لِيُوْسُفَۗ مَا كَانَ لِيَأْخُذَ اَخَاهُ فِيْ دِيْنِ الْمَلِكِ اِلَّآ اَنْ يَّشَاۤءَ اللّٰهُ ۗنَرْفَعُ دَرَجَاتٍ مَّنْ نَّشَاۤءُۗ وَفَوْقَ كُلِّ ذِيْ عِلْمٍ عَلِيْمٌ","77":"۞ قَالُوْٓا اِنْ يَّسْرِقْ فَقَدْ سَرَقَ اَخٌ لَّهٗ مِنْ قَبْلُۚ فَاَسَرَّهَا يُوْسُفُ فِيْ نَفْسِهٖ وَلَمْ يُبْدِهَا لَهُمْۚ قَالَ اَنْتُمْ شَرٌّ مَّكَانًا ۚوَاللّٰهُ اَعْلَمُ بِمَا تَصِفُوْنَ","78":"قَالُوْا يٰٓاَيُّهَا الْعَزِيْزُ اِنَّ لَهٗٓ اَبًا شَيْخًا كَبِيْرًا فَخُذْ اَحَدَنَا مَكَانَهٗ ۚاِنَّا نَرٰىكَ مِنَ الْمُحْسِنِيْنَ","79":"قَالَ مَعَاذَ اللّٰهِ اَنْ نَّأْخُذَ اِلَّا مَنْ وَّجَدْنَا مَتَاعَنَا عِنْدَهٗٓ ۙاِنَّآ اِذًا لَّظٰلِمُوْنَ ࣖ","80":"فَلَمَّا اسْتَا۟يْـَٔسُوْا مِنْهُ خَلَصُوْا نَجِيًّاۗ قَالَ كَبِيْرُهُمْ اَلَمْ تَعْلَمُوْٓا اَنَّ اَبَاكُمْ قَدْ اَخَذَ عَلَيْكُمْ مَّوْثِقًا مِّنَ اللّٰهِ وَمِنْ قَبْلُ مَا فَرَّطْتُّمْ فِيْ يُوْسُفَ فَلَنْ اَبْرَحَ الْاَرْضَ حَتّٰى يَأْذَنَ لِيْٓ اَبِيْٓ اَوْ يَحْكُمَ اللّٰهُ لِيْۚ وَهُوَ خَيْرُ الْحٰكِمِيْنَ","81":"اِرْجِعُوْٓا اِلٰٓى اَبِيْكُمْ فَقُوْلُوْا يٰٓاَبَانَآ اِنَّ ابْنَكَ سَرَقَۚ وَمَا شَهِدْنَآ اِلَّا بِمَا عَلِمْنَا وَمَا كُنَّا لِلْغَيْبِ حٰفِظِيْنَ","82":"وَسْـَٔلِ الْقَرْيَةَ الَّتِيْ كُنَّا فِيْهَا وَالْعِيْرَ الَّتِيْٓ اَقْبَلْنَا فِيْهَاۗ وَاِنَّا لَصٰدِقُوْنَ","83":"قَالَ بَلْ سَوَّلَتْ لَكُمْ اَنْفُسُكُمْ اَمْرًاۗ فَصَبْرٌ جَمِيْلٌ ۗعَسَى اللّٰهُ اَنْ يَّأْتِيَنِيْ بِهِمْ جَمِيْعًاۗ اِنَّهٗ هُوَ الْعَلِيْمُ الْحَكِيْمُ","84":"وَتَوَلّٰى عَنْهُمْ وَقَالَ يٰٓاَسَفٰى عَلٰى يُوْسُفَ وَابْيَضَّتْ عَيْنٰهُ مِنَ الْحُزْنِ فَهُوَ كَظِيْمٌ ","85":"قَالُوْا تَاللّٰهِ تَفْتَؤُا تَذْكُرُ يُوْسُفَ حَتّٰى تَكُوْنَ حَرَضًا اَوْ تَكُوْنَ مِنَ الْهَالِكِيْنَ","86":"قَالَ اِنَّمَآ اَشْكُوْا بَثِّيْ وَحُزْنِيْٓ اِلَى اللّٰهِ وَاَعْلَمُ مِنَ اللّٰهِ مَا لَا تَعْلَمُوْنَ","87":"يٰبَنِيَّ اذْهَبُوْا فَتَحَسَّسُوْا مِنْ يُّوْسُفَ وَاَخِيْهِ وَلَا تَا۟يْـَٔسُوْا مِنْ رَّوْحِ اللّٰهِ ۗاِنَّهٗ لَا يَا۟يْـَٔسُ مِنْ رَّوْحِ اللّٰهِ اِلَّا الْقَوْمُ الْكٰفِرُوْنَ","88":"فَلَمَّا دَخَلُوْا عَلَيْهِ قَالُوْا يٰٓاَيُّهَا الْعَزِيْزُ مَسَّنَا وَاَهْلَنَا الضُّرُّ وَجِئْنَا بِبِضَاعَةٍ مُّزْجٰىةٍ فَاَوْفِ لَنَا الْكَيْلَ وَتَصَدَّقْ عَلَيْنَاۗ اِنَّ اللّٰهَ يَجْزِى الْمُتَصَدِّقِيْنَ","89":"قَالَ هَلْ عَلِمْتُمْ مَّا فَعَلْتُمْ بِيُوْسُفَ وَاَخِيْهِ اِذْ اَنْتُمْ جَاهِلُوْنَ","90":"قَالُوْٓا ءَاِنَّكَ لَاَنْتَ يُوْسُفُۗ قَالَ اَنَا۠ يُوْسُفُ وَهٰذَآ اَخِيْ قَدْ مَنَّ اللّٰهُ عَلَيْنَاۗ اِنَّهٗ مَنْ يَّتَّقِ وَيَصْبِرْ فَاِنَّ اللّٰهَ لَا يُضِيْعُ اَجْرَ الْمُحْسِنِيْنَ","91":"قَالُوْا تَاللّٰهِ لَقَدْ اٰثَرَكَ اللّٰهُ عَلَيْنَا وَاِنْ كُنَّا لَخٰطِـِٕيْنَ","92":"قَالَ لَا تَثْرِيْبَ عَلَيْكُمُ الْيَوْمَۗ يَغْفِرُ اللّٰهُ لَكُمْ ۖوَهُوَ اَرْحَمُ الرّٰحِمِيْنَ","93":"اِذْهَبُوْا بِقَمِيْصِيْ هٰذَا فَاَلْقُوْهُ عَلٰى وَجْهِ اَبِيْ يَأْتِ بَصِيْرًا ۚوَأْتُوْنِيْ بِاَهْلِكُمْ اَجْمَعِيْنَ ࣖ","94":"وَلَمَّا فَصَلَتِ الْعِيْرُ قَالَ اَبُوْهُمْ اِنِّيْ لَاَجِدُ رِيْحَ يُوْسُفَ لَوْلَآ اَنْ تُفَنِّدُوْنِ","95":"قَالُوْا تَاللّٰهِ اِنَّكَ لَفِيْ ضَلٰلِكَ الْقَدِيْمِ","96":"فَلَمَّآ اَنْ جَاۤءَ الْبَشِيْرُ اَلْقٰىهُ عَلٰى وَجْهِهٖ فَارْتَدَّ بَصِيْرًاۗ قَالَ اَلَمْ اَقُلْ لَّكُمْۙ اِنِّيْٓ اَعْلَمُ مِنَ اللّٰهِ مَا لَا تَعْلَمُوْنَ","97":"قَالُوْا يٰٓاَبَانَا اسْتَغْفِرْ لَنَا ذُنُوْبَنَآ اِنَّا كُنَّا خٰطِـِٕيْنَ","98":"قَالَ سَوْفَ اَسْتَغْفِرُ لَكُمْ رَبِّيْ ۗاِنَّهٗ هُوَ الْغَفُوْرُ الرَّحِيْمُ","99":"فَلَمَّا دَخَلُوْا عَلٰى يُوْسُفَ اٰوٰٓى اِلَيْهِ اَبَوَيْهِ وَقَالَ ادْخُلُوْا مِصْرَ اِنْ شَاۤءَ اللّٰهُ اٰمِنِيْنَ ۗ ","100":"وَرَفَعَ اَبَوَيْهِ عَلَى الْعَرْشِ وَخَرُّوْا لَهٗ سُجَّدًاۚ وَقَالَ يٰٓاَبَتِ هٰذَا تَأْوِيْلُ رُءْيَايَ مِنْ قَبْلُ ۖقَدْ جَعَلَهَا رَبِّيْ حَقًّاۗ وَقَدْ اَحْسَنَ بِيْٓ اِذْ اَخْرَجَنِيْ مِنَ السِّجْنِ وَجَاۤءَ بِكُمْ مِّنَ الْبَدْوِ مِنْۢ بَعْدِ اَنْ نَّزَغَ الشَّيْطٰنُ بَيْنِيْ وَبَيْنَ اِخْوَتِيْۗ اِنَّ رَبِّيْ لَطِيْفٌ لِّمَا يَشَاۤءُ ۗاِنَّهٗ هُوَ الْعَلِيْمُ الْحَكِيْمُ","101":"۞ رَبِّ قَدْ اٰتَيْتَنِيْ مِنَ الْمُلْكِ وَعَلَّمْتَنِيْ مِنْ تَأْوِيْلِ الْاَحَادِيْثِۚ فَاطِرَ السَّمٰوٰتِ وَالْاَرْضِۗ اَنْتَ وَلِيّٖ فِى الدُّنْيَا وَالْاٰخِرَةِۚ تَوَفَّنِيْ مُسْلِمًا وَّاَلْحِقْنِيْ بِالصّٰلِحِيْنَ","102":"ذٰلِكَ مِنْ اَنْۢبَاۤءِ الْغَيْبِ نُوْحِيْهِ اِلَيْكَۚ وَمَا كُنْتَ لَدَيْهِمْ اِذْ اَجْمَعُوْٓا اَمْرَهُمْ وَهُمْ يَمْكُرُوْنَ","103":"وَمَآ اَكْثَرُ النَّاسِ وَلَوْ حَرَصْتَ بِمُؤْمِنِيْنَ","104":"وَمَا تَسْـَٔلُهُمْ عَلَيْهِ مِنْ اَجْرٍۗ اِنْ هُوَ اِلَّا ذِكْرٌ لِّلْعٰلَمِيْنَ ࣖ","105":"وَكَاَيِّنْ مِّنْ اٰيَةٍ فِى السَّمٰوٰتِ وَالْاَرْضِ يَمُرُّوْنَ عَلَيْهَا وَهُمْ عَنْهَا مُعْرِضُوْنَ","106":"وَمَا يُؤْمِنُ اَكْثَرُهُمْ بِاللّٰهِ اِلَّا وَهُمْ مُّشْرِكُوْنَ","107":"اَفَاَمِنُوْٓا اَنْ تَأْتِيَهُمْ غَاشِيَةٌ مِّنْ عَذَابِ اللّٰهِ اَوْ تَأْتِيَهُمُ السَّاعَةُ بَغْتَةً وَّهُمْ لَا يَشْعُرُوْنَ","108":"قُلْ هٰذِهٖ سَبِيْلِيْٓ اَدْعُوْٓا اِلَى اللّٰهِ ۗعَلٰى بَصِيْرَةٍ اَنَا۠ وَمَنِ اتَّبَعَنِيْ ۗوَسُبْحٰنَ اللّٰهِ وَمَآ اَنَا۠ مِنَ الْمُشْرِكِيْنَ","109":"وَمَآ اَرْسَلْنَا مِنْ قَبْلِكَ اِلَّا رِجَالًا نُّوْحِيْٓ اِلَيْهِمْ مِّنْ اَهْلِ الْقُرٰىۗ اَفَلَمْ يَسِيْرُوْا فِى الْاَرْضِ فَيَنْظُرُوْا كَيْفَ كَانَ عَاقِبَةُ الَّذِيْنَ مِنْ قَبْلِهِمْۗ وَلَدَارُ الْاٰخِرَةِ خَيْرٌ لِّلَّذِيْنَ اتَّقَوْاۗ اَفَلَا تَعْقِلُوْنَ","110":"حَتّٰٓى اِذَا اسْتَا۟يْـَٔسَ الرُّسُلُ وَظَنُّوْٓا اَنَّهُمْ قَدْ كُذِبُوْا جَاۤءَهُمْ نَصْرُنَاۙ فَنُجِّيَ مَنْ نَّشَاۤءُ ۗوَلَا يُرَدُّ بَأْسُنَا عَنِ الْقَوْمِ الْمُجْرِمِيْنَ","111":"لَقَدْ كَانَ فِيْ قَصَصِهِمْ عِبْرَةٌ لِّاُولِى الْاَلْبَابِۗ مَا كَانَ حَدِيْثًا يُّفْتَرٰى وَلٰكِنْ تَصْدِيْقَ الَّذِيْ بَيْنَ يَدَيْهِ وَتَفْصِيْلَ كُلِّ شَيْءٍ وَّهُدًى وَّرَحْمَةً لِّقَوْمٍ يُّؤْمِنُوْنَ ࣖ"},translations:{id:{name:d,text:{"1":"Alif Lam Ra. Ini adalah ayat-ayat Kitab (Al-Qur'an) yang jelas.","2":"Sesungguhnya Kami menurunkannya sebagai Qur'an berbahasa Arab, agar kamu mengerti.","3":"Kami menceritakan kepadamu (Muhammad) kisah yang paling baik dengan mewahyukan Al-Qur'an ini kepadamu, dan sesungguhnya engkau sebelum itu termasuk orang yang tidak mengetahui.","4":"(Ingatlah), ketika Yusuf berkata kepada ayahnya, “Wahai ayahku! Sungguh, aku (bermimpi) melihat sebelas bintang, matahari dan bulan; kulihat semuanya sujud kepadaku.”","5":"Dia (ayahnya) berkata, “Wahai anakku! Janganlah engkau ceritakan mimpimu kepada saudara-saudaramu, mereka akan membuat tipu daya (untuk membinasakan)mu. Sungguh, setan itu musuh yang jelas bagi manusia.”","6":"Dan demikianlah, Tuhan memilih engkau (untuk menjadi Nabi) dan mengajarkan kepadamu sebagian dari takwil mimpi dan menyempurnakan (nikmat-Nya) kepadamu dan kepada keluarga Yakub, sebagaimana Dia telah menyempurnakan nikmat-Nya kepada kedua orang kakekmu sebelum itu, (yaitu) Ibrahim dan Ishak. Sungguh, Tuhanmu Maha Mengetahui, Mahabijak-sana.","7":"Sungguh, dalam (kisah) Yusuf dan saudara-saudaranya terdapat tanda-tanda (kekuasaan Allah) bagi orang yang bertanya. ","8":"Ketika mereka berkata, “Sesungguhnya Yusuf dan saudaranya (Bunyamin) lebih dicintai ayah daripada kita, padahal kita adalah satu golongan (yang kuat). Sungguh, ayah kita dalam kekeliruan yang nyata.","9":"Bunuhlah Yusuf atau buanglah dia ke suatu tempat agar perhatian ayah tertumpah kepadamu, dan setelah itu kamu menjadi orang yang baik.”","10":"Seorang di antara mereka berkata, “Janganlah kamu membunuh Yusuf, tetapi masukan saja dia ke dasar sumur agar dia dipungut oleh sebagian musafir, jika kamu hendak berbuat.”","11":"Mereka berkata, “Wahai ayah kami! Mengapa engkau tidak mempercayai kami terhadap Yusuf, padahal sesungguhnya kami semua menginginkan kebaikan baginya.","12":"Biarkanlah dia pergi bersama kami besok pagi, agar dia bersenang-senang dan bermain-main, dan kami pasti menjaganya.”","13":"Dia (Yakub) berkata, “Sesungguhnya kepergian kamu bersama dia (Yusuf) sangat menyedihkanku dan aku khawatir dia dimakan serigala, sedang kamu lengah darinya.”","14":"Sesungguhnya mereka berkata, “Jika dia dimakan serigala, padahal kami golongan (yang kuat), kalau demikian tentu kami orang-orang yang rugi.”","15":"Maka ketika mereka membawanya dan sepakat memasukkan ke dasar sumur, Kami wahyukan kepadanya, “Engkau kelak pasti akan menceritakan perbuatan ini kepada mereka, sedang mereka tidak menyadari.”","16":"Kemudian mereka datang kepada ayah mereka pada petang hari sambil menangis.","17":"Mereka berkata, “Wahai ayah kami! Sesungguhnya kami pergi berlomba dan kami tinggalkan Yusuf di dekat barang-barang kami, lalu dia dimakan serigala; dan engkau tentu tidak akan percaya kepada kami, sekalipun kami berkata benar.”","18":"Dan mereka datang membawa baju gamisnya (yang berlumuran) darah palsu. Dia (Yakub) berkata, “Sebenarnya hanya dirimu sendirilah yang memandang baik urusan yang buruk itu; maka hanya bersabar itulah yang terbaik (bagiku). Dan kepada Allah saja memohon pertolongan-Nya terhadap apa yang kamu ceritakan.”","19":"Dan datanglah sekelompok musafir, mereka menyuruh seorang pengambil air. Lalu dia menurunkan timbanya. Dia berkata, “Oh, senangnya, ini ada seorang anak muda!” Kemudian mereka menyembunyikannya sebagai barang dagangan. Dan Allah Maha Mengetahui apa yang mereka kerjakan.","20":"Dan mereka menjualnya (Yusuf) dengan harga rendah, yaitu beberapa dirham saja, sebab mereka tidak tertarik kepadanya.","21":"Dan orang dari Mesir yang membelinya berkata kepada istrinya,” Berikanlah kepadanya tempat (dan layanan) yang baik, mudah-mudahan dia bermanfaat bagi kita atau kita pungut dia sebagai anak.” Dan demikianlah Kami memberikan kedudukan yang baik kepada Yusuf di negeri (Mesir), dan agar Kami ajarkan kepadanya takwil mimpi. Dan Allah berkuasa terhadap urusan-Nya, tetapi kebanyakan manusia tidak mengerti.","22":"Dan ketika dia telah cukup dewasa Kami berikan kepadanya kekuasaan dan ilmu. Demikianlah Kami memberi balasan kepada orang-orang yang berbuat baik.","23":"Dan perempuan yang dia (Yusuf) tinggal di rumahnya menggoda dirinya. Dan dia menutup pintu-pintu, lalu berkata, “Marilah mendekat kepadaku.” Yusuf berkata, “Aku berlindung kepada Allah, sungguh, tuanku telah memperlakukan aku dengan baik.” Sesungguhnya orang yang zalim itu tidak akan beruntung.","24":"Dan sungguh, perempuan itu telah berkehendak kepadanya (Yusuf). Dan Yusuf pun berkehendak kepadanya, sekiranya dia tidak melihat tanda (dari) Tuhannya. Demikianlah, Kami palingkan darinya keburukan dan kekejian. Sungguh, dia (Yusuf) termasuk hamba Kami yang terpilih.","25":"Dan keduanya berlomba menuju pintu dan perempuan itu menarik baju gamisnya (Yusuf) dari belakang hingga koyak dan keduanya mendapati suami perempuan itu di depan pintu. Dia (perempuan itu) berkata, “Apakah balasan terhadap orang yang bermaksud buruk terhadap istrimu, selain dipenjarakan atau (dihukum) dengan siksa yang pedih?”","26":"Dia (Yusuf) berkata, “Dia yang menggodaku dan merayu diriku.” Seorang saksi dari keluarga perempuan itu memberikan kesaksian, “Jika baju gamisnya koyak di bagian depan, maka perempuan itu benar, dan dia (Yusuf) termasuk orang yang dusta.","27":"Dan jika baju gamisnya koyak di bagian belakang, maka perempuan itulah yang dusta, dan dia (Yusuf) termasuk orang yang benar.”","28":"Maka ketika dia (suami perempuan itu) melihat baju gamisnya (Yusuf) koyak di bagian belakang, dia berkata, “Sesungguhnya ini adalah tipu dayamu. Tipu dayamu benar-benar hebat.”","29":"Wahai Yusuf! ”Lupakanlah ini, dan (istriku) mohonlah ampunan atas dosamu, karena engkau termasuk orang yang bersalah.”","30":"Dan perempuan-perempuan di kota berkata, “Istri Al-Aziz menggoda dan merayu pelayannya untuk menundukkan dirinya, pelayannya benar-benar membuatnya mabuk cinta. Kami pasti memandang dia dalam kesesatan yang nyata.”","31":"Maka ketika perempuan itu mendengar cercaan mereka, diundangnyalah perempuan-perempuan itu dan disediakannya tempat duduk bagi mereka, dan kepada masing-masing mereka diberikan sebuah pisau (untuk memotong jamuan), kemudian dia berkata (kepada Yusuf), “Keluarlah (tampakkanlah dirimu) kepada mereka.” Ketika perempuan-perempuan itu melihatnya, mereka terpesona kepada (keelokan rupa)nya, dan mereka (tanpa sadar) melukai tangannya sendiri. Seraya berkata, “Mahasempurna Allah, ini bukanlah manusia. Ini benar-benar malaikat yang mulia.”","32":"Dia (istri Al-Aziz) berkata, “Itulah orangnya yang menyebabkan kamu mencela aku karena (aku tertarik) kepadanya, dan sungguh, aku telah menggoda untuk menundukkan dirinya tetapi dia menolak. Jika dia tidak melakukan apa yang aku perintahkan kepadanya, niscaya dia akan dipenjarakan, dan dia akan menjadi orang yang hina.”","33":"Yusuf berkata, “Wahai Tuhanku! Penjara lebih aku sukai daripada memenuhi ajakan mereka. Jika aku tidak Engkau hindarkan dari tipu daya mereka, niscaya aku akan cenderung untuk (memenuhi keinginan mereka) dan tentu aku termasuk orang yang bodoh.”","34":"Maka Tuhan memperkenankan doa Yusuf, dan Dia menghindarkan Yusuf dari tipu daya mereka. Dialah Yang Maha Mendengar, Maha Mengetahui.","35":"Kemudian timbul pikiran pada mereka setelah melihat tanda-tanda (kebenaran Yusuf) bahwa mereka harus memenjarakannya sampai waktu tertentu.","36":"Dan bersama dia masuk pula dua orang pemuda ke dalam penjara. Salah satunya berkata, “Sesungguhnya aku bermimpi memeras anggur,” dan yang lainnya berkata, “Aku bermimpi, membawa roti di atas kepalaku, sebagiannya dimakan burung.” Berikanlah kepada kami takwilnya. Sesungguhnya kami memandangmu termasuk orang yang berbuat baik.","37":"Dia (Yusuf) berkata, “Makanan apa pun yang akan diberikan kepadamu berdua aku telah dapat menerangkan takwilnya, sebelum (makanan) itu sampai kepadamu. Itu sebagian dari yang diajarkan Tuhan kepadaku. Sesungguhnya aku telah meninggalkan agama orang-orang yang tidak beriman kepada Allah, bahkan mereka tidak percaya kepada hari akhirat.","38":"Dan aku mengikuti agama nenek moyangku: Ibrahim, Ishak dan Yakub. Tidak pantas bagi kami (para nabi) mempersekutukan sesuatu apa pun dengan Allah. Itu adalah dari karunia Allah kepada kami dan kepada manusia (semuanya); tetapi kebanyakan manusia tidak bersyukur.","39":"Wahai kedua penghuni penjara! Manakah yang baik, tuhan-tuhan yang bermacam-macam itu ataukah Allah Yang Maha Esa, Mahaperkasa?","40":"Apa yang kamu sembah selain Dia, hanyalah nama-nama yang kamu buat-buat baik oleh kamu sendiri maupun oleh nenek moyangmu. Allah tidak menurunkan suatu keterangan pun tentang hal (nama-nama) itu. Keputusan itu hanyalah milik Allah. Dia telah memerintahkan agar kamu tidak menyembah selain Dia. Itulah agama yang lurus, tetapi kebanyakan manusia tidak mengetahui.","41":"Wahai kedua penghuni penjara, “Salah seorang di antara kamu, akan bertugas menyediakan minuman khamar bagi tuannya. Adapun yang seorang lagi dia akan disalib, lalu burung memakan sebagian kepalanya. Telah terjawab perkara yang kamu tanyakan (kepadaku).”","42":"Dan dia (Yusuf) berkata kepada orang yang diketahuinya akan selamat di antara mereka berdua, “Terangkanlah keadaanku kepada tuanmu.” Maka setan menjadikan dia lupa untuk menerangkan (keadaan Yusuf) kepada tuannya. Karena itu dia (Yusuf) tetap dalam penjara beberapa tahun lamanya.","43":"Dan raja berkata (kepada para pemuka kaumnya), “Sesungguhnya aku bermimpi melihat tujuh ekor sapi betina yang gemuk dimakan oleh tujuh ekor sapi betina yang kurus; tujuh tangkai (gandum) yang hijau dan (tujuh tangkai) lainnya yang kering. Wahai orang yang terkemuka! Terangkanlah kepadaku tentang takwil mimpiku itu jika kamu dapat menakwilkan mimpi.” ","44":"Mereka menjawab, “(Itu) mimpi-mimpi yang kosong dan kami tidak mampu menakwilkan mimpi itu.”","45":"Dan berkatalah orang yang selamat di antara mereka berdua dan teringat (kepada Yusuf) setelah beberapa waktu lamanya, “Aku akan memberitahukan kepadamu tentang (orang yang pandai) menakwilkan mimpi itu, maka utuslah aku (kepadanya).”","46":"”Yusuf, wahai orang yang sangat dipercaya! Terangkanlah kepada kami (takwil mimpi) tentang tujuh ekor sapi betina yang gemuk yang dimakan oleh tujuh (ekor sapi betina) yang kurus, tujuh tangkai (gandum) yang hijau dan (tujuh tangkai) lainnya yang kering agar aku kembali kepada orang-orang itu, agar mereka mengetahui.”","47":"Dia (Yusuf) berkata, “Agar kamu bercocok tanam tujuh tahun (berturut-turut) sebagaimana biasa; kemudian apa yang kamu tuai hendaklah kamu biarkan di tangkainya kecuali sedikit untuk kamu makan.","48":"Kemudian setelah itu akan datang tujuh (tahun) yang sangat sulit, yang menghabiskan apa yang kamu simpan untuk menghadapinya (tahun sulit), kecuali sedikit dari apa (bibit gandum) yang kamu simpan. ","49":"Setelah itu akan datang tahun, di mana manusia diberi hujan (dengan cukup) dan pada masa itu mereka memeras (anggur).”","50":"Dan raja berkata, “Bawalah dia kepadaku.” Ketika utusan itu datang kepadanya, dia (Yusuf) berkata, “Kembalilah kepada tuanmu dan tanyakan kepadanya bagaimana halnya perempuan-perempuan yang telah melukai tangannya. Sungguh, Tuhanku Maha Mengetahui tipu daya mereka.”","51":"Dia (raja) berkata (kepada perempuan-perempuan itu), “Bagaimana keadaanmu ketika kamu menggoda Yusuf untuk menundukkan dirinya?” Mereka berkata, “Mahasempurna Allah, kami tidak mengetahui sesuatu keburukan darinya.” Istri Al-Aziz berkata, “Sekarang jelaslah kebenaran itu, akulah yang menggoda dan merayunya, dan sesungguhnya dia termasuk orang yang benar.”","52":"(Yusuf berkata), “Yang demikian itu agar dia (Al-Aziz) mengetahui bahwa aku benar-benar tidak mengkhianatinya ketika dia tidak ada (di rumah), dan bahwa Allah tidak meridai tipu daya orang-orang yang berkhianat. ","53":"Dan aku tidak (menyatakan) diriku bebas (dari kesalahan), karena sesungguhnya nafsu itu selalu mendorong kepada kejahatan, kecuali (nafsu) yang diberi rahmat oleh Tuhanku. Sesungguhnya Tuhanku Maha Pengampun, Maha Penyayang.","54":"Dan raja berkata, “Bawalah dia (Yusuf) kepadaku, agar aku memilih dia (sebagai orang yang dekat) kepadaku.” Ketika dia (raja) telah bercakap-cakap dengan dia, dia (raja) berkata, “Sesungguhnya kamu (mulai) hari ini menjadi seorang yang berkedudukan tinggi di lingkungan kami dan dipercaya.”","55":"Dia (Yusuf) berkata, “Jadikanlah aku bendaharawan negeri (Mesir); karena sesungguhnya aku adalah orang yang pandai menjaga, dan berpengetahuan.”","56":"Dan demikianlah Kami memberi kedudukan kepada Yusuf di negeri ini (Mesir); untuk tinggal di mana saja yang dia kehendaki. Kami melimpahkan rahmat kepada siapa yang Kami kehendaki dan Kami tidak menyia-nyiakan pahala orang yang berbuat baik.","57":"Dan sungguh, pahala akhirat itu lebih baik bagi orang-orang yang beriman dan selalu bertakwa.","58":"Dan saudara-saudara Yusuf datang (ke Mesir) lalu mereka masuk ke (tempat)nya. Maka dia (Yusuf) mengenal mereka, sedang mereka tidak mengenalinya (lagi) kepadanya.","59":"Dan ketika dia (Yusuf) menyiapkan bahan makanan untuk mereka, dia berkata, “Bawalah kepadaku saudaramu yang seayah dengan kamu (Bunyamin), tidakkah kamu melihat bahwa aku menyempurnakan takaran dan aku adalah penerima tamu yang terbaik?","60":"Maka jika kamu tidak membawanya kepadaku, maka kamu tidak akan mendapat jatah (gandum) lagi dariku dan jangan kamu mendekatiku.”","61":"Mereka berkata, “Kami akan membujuk ayahnya (untuk membawanya) dan kami benar-benar akan melaksanakannya.”","62":"Dan dia (Yusuf) berkata kepada pelayan-pelayannya, “Masukkanlah barang-barang (penukar) mereka ke dalam karung-karungnya, agar mereka mengetahuinya apabila telah kembali kepada keluarganya, mudah-mudahan mereka kembali lagi.”","63":"Maka ketika mereka telah kembali kepada ayahnya (Yakub) mereka berkata, “Wahai ayah kami! Kami tidak akan mendapat jatah (gandum) lagi, (jika tidak membawa saudara kami), sebab itu biarkanlah saudara kami pergi bersama kami agar kami mendapat jatah, dan kami benar-benar akan menjaganya.”","64":"Dia (Yakub) berkata, “Bagaimana aku akan mempercayakannya (Bunyamin) kepadamu, seperti aku telah mempercayakan saudaranya (Yusuf) kepada kamu dahulu?” Maka Allah adalah penjaga yang terbaik dan Dia Maha Penyayang di antara para penyayang.","65":"Dan ketika mereka membuka barang-barangnya, mereka menemukan barang-barang (penukar) mereka dikembalikan kepada mereka. Mereka berkata, “Wahai ayah kami! Apalagi yang kita inginkan. Ini barang-barang kita dikembalikan kepada kita, dan kita akan dapat memberi makan keluarga kita, dan kami akan memelihara saudara kami, dan kita akan mendapat tambahan jatah (gandum) seberat beban seekor unta. Itu suatu hal yang mudah (bagi raja Mesir).”","66":"Dia (Yakub) berkata, “Aku tidak akan melepaskannya (pergi) bersama kamu, sebelum kamu bersumpah kepadaku atas (nama) Allah, bahwa kamu pasti akan membawanya kepadaku kembali, kecuali jika kamu dikepung (musuh).” Setelah mereka mengucapkan sumpah, dia (Yakub) berkata, “Allah adalah saksi terhadap apa yang kita ucapkan.”","67":"Dan dia (Yakub) berkata, “Wahai anak-anakku! Janganlah kamu masuk dari satu pintu gerbang, dan masuklah dari pintu-pintu gerbang yang berbeda; namun demikian aku tidak dapat mempertahankan kamu sedikit pun dari (takdir) Allah. Keputusan itu hanyalah bagi Allah. Kepada-Nya aku bertawakal dan kepada-Nya pula bertawakallah orang-orang yang bertawakal.”","68":"Dan ketika mereka masuk sesuai dengan perintah ayah mereka, (masuknya mereka itu) tidak dapat menolak sedikit pun keputusan Allah, (tetapi itu) hanya suatu keinginan pada diri Yakub yang telah ditetapkannya. Dan sesungguhnya dia mempunyai pengetahuan, karena Kami telah mengajarkan kepadanya. Tetapi kebanyakan manusia tidak mengetahui.","69":"Dan ketika mereka masuk ke (tempat) Yusuf, dia menempatkan saudaranya (Bunyamin) di tempatnya, dia (Yusuf) berkata, “Sesungguhnya aku adalah saudaramu, jangan engkau bersedih hati terhadap apa yang telah mereka kerjakan.”","70":"Maka ketika telah disiapkan bahan makanan untuk mereka, dia (Yusuf) memasukkan piala ke dalam karung saudaranya. Kemudian berteriaklah seseorang yang menyerukan, “Wahai kafilah! Sesungguhnya kamu pasti pencuri.” ","71":"Mereka bertanya, sambil menghadap kepada mereka (yang menuduh), “Kamu kehilangan apa?”","72":"Mereka menjawab, “Kami kehilangan piala raja, dan siapa yang dapat mengembalikannya akan memperoleh (bahan makanan seberat) beban unta, dan aku jamin itu.”","73":"Mereka (saudara-saudara Yusuf) menjawab, “Demi Allah, sungguh, kamu mengetahui bahwa kami datang bukan untuk berbuat kerusakan di negeri ini dan kami bukanlah para pencuri.”","74":"Mereka berkata, “Tetapi apa hukumannya jika kamu dusta?”","75":"Mereka menjawab, “Hukumannya ialah pada siapa ditemukan dalam karungnya (barang yang hilang itu), maka dia sendirilah menerima hukumannya. Demikianlah kami memberi hukuman kepada orang-orang zalim.”","76":"Maka mulailah dia (memeriksa) karung-karung mereka sebelum (memeriksa) karung saudaranya sendiri, kemudian dia mengeluarkan (piala raja) itu dari karung saudaranya. Demikianlah Kami mengatur (rencana) untuk Yusuf. Dia tidak dapat menghukum saudaranya menurut undang-undang raja, kecuali Allah menghendakinya. Kami angkat derajat orang yang Kami kehendaki; dan di atas setiap orang yang berpengetahuan ada yang lebih mengetahui.","77":"Mereka berkata, “Jika dia mencuri, maka sungguh sebelum itu saudaranya pun pernah pula mencuri.” Maka Yusuf menyembunyikan (kejengkelan) dalam hatinya dan tidak ditampakkannya kepada mereka. Dia berkata (dalam hatinya), “Kedudukanmu justru lebih buruk. Dan Allah Maha Mengetahui apa yang kamu terangkan.”","78":"Mereka berkata, “Wahai Al-Aziz! Dia mempunyai ayah yang sudah lanjut usia, karena itu ambillah salah seorang di antara kami sebagai gantinya, sesungguhnya kami melihat engkau termasuk orang-orang yang berbuat baik.”","79":"Dia (Yusuf) berkata, “Aku memohon perlindungan kepada Allah dari menahan (seseorang), kecuali orang yang kami temukan harta kami padanya, jika kami (berbuat) demikian, berarti kami orang yang zalim.”","80":"Maka ketika mereka berputus asa darinya (putusan Yusuf) mereka menyendiri (sambil berunding) dengan berbisik-bisik. Yang tertua di antara mereka berkata, “Tidakkah kamu ketahui bahwa ayahmu telah mengambil janji dari kamu dengan (nama) Allah dan sebelum itu kamu telah menyia-nyiakan Yusuf? Sebab itu aku tidak akan meninggalkan negeri ini (Mesir), sampai ayahku mengizinkan (untuk kembali), atau Allah memberi keputusan terhadapku. Dan Dia adalah hakim yang terbaik.”","81":"Kembalilah kepada ayahmu dan katakanlah, “Wahai ayah kami! Sesungguhnya anakmu telah mencuri dan kami hanya menyaksikan apa yang kami ketahui dan kami tidak mengetahui apa yang di balik itu.","82":"Dan tanyalah (penduduk) negeri tempat kami berada, dan kafilah yang datang bersama kami. Dan kami adalah orang yang benar.”","83":"Dia (Yakub) berkata, “Sebenarnya hanya dirimu sendiri yang memandang baik urusan (yang buruk) itu. Maka (kesabaranku) adalah kesabaran yang baik. Mudah-mudahan Allah mendatangkan mereka semuanya kepadaku. Sungguh, Dialah Yang Maha Mengetahui, Mahabijaksana.”","84":"Dan dia (Yakub) berpaling dari mereka (anak-anaknya) seraya berkata, “Aduhai dukacitaku terhadap Yusuf,” dan kedua matanya menjadi putih karena sedih. Dia diam menahan amarah (terhadap anak-anaknya).","85":"Mereka berkata, “Demi Allah, engkau tidak henti-hentinya mengingat Yusuf, sehingga engkau (mengidap) penyakit berat atau engkau termasuk orang-orang yang akan binasa.”","86":"Dia (Yakub) menjawab, “Hanya kepada Allah aku mengadukan kesusahan dan kesedihanku. Dan aku mengetahui dari Allah apa yang tidak kamu ketahui.","87":"Wahai anak-anakku! Pergilah kamu, carilah (berita) tentang Yusuf dan saudaranya dan jangan kamu berputus asa dari rahmat Allah. Sesungguhnya yang berputus asa dari rahmat Allah, hanyalah orang-orang yang kafir.”","88":"Maka ketika mereka masuk ke (tempat) Yusuf, mereka berkata, “Wahai Al-Aziz! Kami dan keluarga kami telah ditimpa kesengsaraan dan kami datang membawa barang-barang yang tidak berharga, maka penuhilah jatah (gandum) untuk kami, dan bersedekahlah kepada kami. Sesungguhnya Allah memberi balasan kepada orang yang bersedekah.”","89":"Dia (Yusuf) berkata, “Tahukah kamu (kejelekan) apa yang telah kamu perbuat terhadap Yusuf dan saudaranya karena kamu tidak menyadari (akibat) perbuatanmu itu?”","90":"Mereka berkata, “Apakah engkau benar-benar Yusuf?” Dia (Yusuf) menjawab, “Aku Yusuf dan ini saudaraku. Sungguh, Allah telah melimpahkan karunia-Nya kepada kami. Sesungguhnya barangsiapa bertakwa dan bersabar, maka Sungguh, Allah tidak menyia-nyiakan pahala orang yang berbuat baik.”","91":"Mereka berkata, “Demi Allah, sungguh Allah telah melebihkan engkau di atas kami, dan sesungguhnya kami adalah orang yang bersalah (berdosa).”","92":"Dia (Yusuf) berkata, “Pada hari ini tidak ada cercaan terhadap kamu, mudah-mudahan Allah mengampuni kamu. Dan Dia Maha Penyayang di antara para penyayang.","93":"Pergilah kamu dengan membawa bajuku ini, lalu usapkan ke wajah ayahku, nanti dia akan melihat kembali; dan bawalah seluruh keluargamu kepadaku.”","94":"Dan ketika kafilah itu telah keluar (dari negeri Mesir), ayah mereka berkata, “Sesungguhnya Aku mencium bau Yusuf, sekiranya kamu tidak menuduhku lemah akal (tentu kamu membenarkan aku).”","95":"Mereka (keluarganya) berkata, “Demi Allah, sesungguhnya engkau masih dalam kekeliruanmu yang dahulu.”","96":"Maka ketika telah tiba pembawa kabar gembira itu, maka diusapkannya (baju itu) ke wajahnya (Yakub), lalu dia dapat melihat kembali. Dia (Yakub) berkata, “Bukankah telah aku katakan kepadamu, bahwa aku mengetahui dari Allah apa yang tidak kamu ketahui.”","97":"Mereka berkata, “Wahai ayah kami! Mohonkanlah ampunan untuk kami atas dosa-dosa kami, sesungguhnya kami adalah orang yang bersalah (berdosa).” ","98":"Dia (Yakub) berkata, “Aku akan memohonkan ampunan bagimu kepada Tuhanku. Sungguh, Dia Yang Maha Pengampun, Maha Penyayang.”","99":"Maka ketika mereka masuk ke (tempat) Yusuf, dia merangkul (dan menyiapkan tempat untuk) kedua orang tuanya seraya berkata, “Masuklah kamu ke negeri Mesir, insya Allah dalam keadaan aman.”","100":"Dan dia menaikkan kedua orang tuanya ke atas singgasana. Dan mereka (semua) tunduk bersujud kepadanya (Yusuf). Dan dia (Yusuf) berkata, “Wahai ayahku! Inilah takwil mimpiku yang dahulu itu. Dan sesungguhnya Tuhanku telah menjadikannya kenyataan. Sesungguhnya Tuhanku telah berbuat baik kepadaku, ketika Dia membebaskan aku dari penjara dan ketika membawa kamu dari dusun, setelah setan merusak (hubungan) antara aku dengan saudara-saudaraku. Sungguh, Tuhanku Mahalembut terhadap apa yang Dia kehendaki. Sungguh, Dia Yang Maha Mengetahui, Mahabijaksana.","101":"Tuhanku, sesungguhnya Engkau telah menganugerahkan kepadaku sebagian kekuasaan dan telah mengajarkan kepadaku sebagian takwil mimpi. (Wahai Tuhan) pencipta langit dan bumi, Engkaulah pelindungku di dunia dan di akhirat, wafatkanlah aku dalam keadaan muslim dan gabungkanlah aku dengan orang yang saleh.” ","102":"Itulah sebagian berita gaib yang Kami wahyukan kepadamu (Muhammad); padahal engkau tidak berada di samping mereka, ketika mereka bersepakat mengatur tipu muslihat (untuk memasukkan Yusuf ke dalam sumur).","103":"Dan kebanyakan manusia tidak akan beriman walaupun engkau sangat menginginkannya.","104":"Dan engkau tidak meminta imbalan apa pun kepada mereka (terhadap seruanmu ini), sebab (seruan) itu adalah pengajaran bagi seluruh alam.","105":"Dan berapa banyak tanda-tanda (kebesaran Allah) di langit dan di bumi yang mereka lalui, namun mereka berpaling daripadanya.","106":"Dan kebanyakan mereka tidak beriman kepada Allah, bahkan mereka mempersekutukan-Nya.","107":"Apakah mereka merasa aman dari kedatangan siksa Allah yang meliputi mereka, atau kedatangan Kiamat kepada mereka secara mendadak, sedang mereka tidak menyadarinya?","108":"Katakanlah (Muhammad), “Inilah jalanku, aku dan orang-orang yang mengikutiku mengajak (kamu) kepada Allah dengan yakin, Mahasuci Allah, dan aku tidak termasuk orang-orang musyrik.”","109":"Dan Kami tidak mengutus sebelummu (Muhammad), melainkan orang laki-laki yang Kami berikan wahyu kepadanya di antara penduduk negeri. Tidakkah mereka bepergian di bumi lalu melihat bagaimana kesudahan orang-orang sebelum mereka (yang mendustakan rasul). Dan sungguh, negeri akhirat itu lebih baik bagi orang yang bertakwa. Tidakkah kamu mengerti?","110":"Sehingga apabila para rasul tidak mempunyai harapan lagi (tentang keimanan kaumnya) dan telah meyakini bahwa mereka telah didustakan, datanglah kepada mereka (para rasul) itu pertolongan Kami, lalu diselamatkan orang yang Kami kehendaki. Dan siksa Kami tidak dapat ditolak dari orang yang berdosa.","111":"Sungguh, pada kisah-kisah mereka itu terdapat pengajaran bagi orang yang mempunyai akal. (Al-Qur'an) itu bukanlah cerita yang dibuat-buat, tetapi membenarkan (kitab-kitab) yang sebelumnya, menjelaskan segala sesuatu, dan (sebagai) petunjuk dan rahmat bagi orang-orang yang beriman."}}},tafsir:{id:{kemenag:{name:"Kemenag",source:"Aplikasi Quran Kementrian Agama Republik Indonesia",text:{"1":"Ayat pertama surah Yusuf ini sama bunyinya dengan ayat pertama pada surah Yunus kecuali pada akhir ayat pertama surah Yunus ada kata \"al hakim\" sedang pada ayat pertama surah ini terdapat kata \"al-Mubin\".\n\nAl-hakim artinya penuh hikmat dan al-Mubin artinya nyata, jelas, dan terang. Biasanya dengan memperhatikan ayat pertama dari tiap-tiap surah sudah dapat diperkirakan apa pokok-pokok isi surah itu. Surah Yunus yang ayat pertamanya diakhiri dengan al-Hakim, terdapat di dalamnya masalah-masalah hikmat dan filsafat, seperti masalah keesaan Allah, sifat-sifat-Nya, kebenaran risalah yang dibawa para nabi yang dikuatkan dengan berbagai macam mukjizat, masalah hari kebangkitan, hari pembalasan, dan sebagainya. Semuanya itu adalah masalah-masalah yang harus direnungkan dan difikirkan secara mendalam dan termasuk masalah hikmat dan filsafat. Adapun surah Yusuf ayat pertamanya diakhiri dengan al-Mubin. Hal ini mengisyaratkan bahwa di dalamnya terdapat suatu kisah yang sangat menarik, digubah dengan susunan kata-kata yang mempesona penuh balagah dan falsafah dalam suatu jalinan cerita yang indah yang mendorong pembacanya untuk mengikuti sampai akhir, suatu kisah yang patut menjadi contoh dan teladan yang menggambarkan dengan jelas bagaimana kehidupan seorang nabi yang mulia semenjak kecilnya mengalami beraneka ragam penderitaan sampai ia menjadi penguasa yang disegani dan dihormati di negeri Mesir.","2":"Pada ayat ini, Allah menegaskan bahwa Dia menurunkan Al-Quran dalam bahasa Arab yang fasih agar dapat direnungkan dan difikirkan isi dan maknanya. Memang Al-Quran diturunkan untuk semua manusia, bahkan juga untuk jin, tetapi karena yang pertama-tama menerimanya ialah penduduk Mekah, maka wajarlah bila firman itu ditujukan lebih dahulu kepada mereka dan seterusnya berlaku untuk semua umat manusia. Pertama-tama Allah menuntut perhatian orang-orang Quraisy dan orang-orang Arab seluruhnya supaya mereka memperhatikan isinya dengan sebaik-baiknya karena di dalamnya terkandung bermacam-macam ilmu pengetahuan yang bermanfaat bagi mereka di dunia dan akhirat seperti hukum-hukum agama, kisah para nabi dan rasul, hal-hal yang bertalian dengan pembangunan masyarakat, pokok-pokok kemakmuran, akhlak, filsafat, tata cara berpolitik, baik yang bersifat nasional maupun yang bersifat internasional, dan lain sebagainya. Semuanya itu diutarakan dalam bahasa Arab yang indah susunannya mudah dipahami oleh mereka.","3":"Pada ayat ini, Allah mengkhususkan firman-Nya kepada Nabi Muhammad saw dan tentu saja untuk diperhatikan oleh orang Arab dan umat manusia seluruhnya. Para mufasir mengatakan bahwa surah Yusuf ini adalah salah satu surah dalam Al-Quran yang diturunkan untuk menghibur dan menggembirakan hati Nabi Muhammad saw di kala beliau menderita tekanan-tekanan yang berat dari kaum Quraisy berupa cemoohan, hinaan, pembangkangan, dan tindakan kekerasan sehingga beliau terpaksa hijrah bersama Abu Bakar ke Medinah. Memang demikianlah halnya karena kisah Nabi Yusuf ini adalah suatu kisah yang menarik sekali, dikisahkan dengan cara terperinci, tiap babak mengandung hikmah yang dalam dan pelajaran yang besar manfaatnya bagi orang yang memperhatikannya, apalagi bila dilihat dari segi keindahan susunan bahasa dan isi ceritanya yang belum dikenal seluruhnya baik oleh Nabi Muhammad saw sendiri maupun oleh kaum Quraisy dan orang Arab pada umumnya.\n\nKisah ini selain menceritakan keadaan Nabi Yakub a.s. beserta anak-anaknya yang masih hidup dengan cara kehidupan orang-orang Badui, menceritakan pula bagaimana kehidupan dalam masyarakat yang telah maju dan berkebudayaan tinggi, bagaimana kehidupan para penguasa yang penuh dengan kemewahan serta kesenangan dan bagaimana pula cara mereka mengendalikan pemerintahan dan mengatur perekonomian negara. Benarlah firman Allah yang mengatakan bahwa kisah Nabi Yusuf a.s. yang akan dikisahkan berikut ini adalah kisah yang paling baik, menarik, dan yang paling indah penggambarannya.","4":"Pada suatu ketika Nabi Yusuf a.s. memberitahukan kepada ayahnya Nabi Yakub bin Ishak bin Ibrahim bahwa ia bermimpi melihat sebelas bintang, matahari, dan bulan, semuanya tunduk dan sujud kepadanya. Tentu saja sujud di sini bukan dengan arti menyembah seperti yang kita kenal, tetapi hanyalah sujud dalam arti kiasan yaitu tunduk dan patuh. Sujud dengan arti tunduk dan patuh itu ada juga terdapat dalam Al-Quran, seperti firman Allah:\n\nDan tetumbuhan dan pepohonan, keduanya tunduk (kepada-Nya). (ar-Rahman\u002F55: 6)\n\nSetelah mendengar cerita itu, Nabi Yakub a.s. menyadari bahwa mimpi anaknya bukan mimpi biasa, tetapi merupakan ilham dari Allah sebagaimana kerapkali dialami oleh para nabi. Ia yakin bahwa anaknya ini akan menghadapi urusan yang sangat penting dan setelah dewasa menjadi pemimpin dimana masyarakat akan tunduk kepadanya tidak terkecuali saudara-saudaranya dan ibu-bapaknya. Ia merasa khawatir kalau hal ini diketahui oleh saudara-saudaranya, dan tentulah mereka akan merasa iri dan dengki terhadapnya serta berusaha untuk menyingkirkan atau membinasa-kannya apalagi mereka telah merasa bahwa ayah mereka lebih banyak menumpahkan kasih sayangnya kepadanya. Tergambarlah dalam khayal Nabi Yakub bagaimana nasib anaknya bila mimpi itu diketahui oleh saudara-saudaranya, tentulah mereka dengan segala usaha dan tipu daya akan mencelakakannya.","5":"Oleh sebab itu, Nabi Yakub a.s. berkata kepada anaknya, \"Hai anakku, jangan sekali-kali engkau beritahukan apa yang engkau lihat dalam mimpi itu, karena kalau mereka sampai mengetahuinya, mereka akan mengerti tabir mimpi itu dan mereka akan iri dan dengki terhadapmu. Aku melihat bahwa mimpi itu bukan sembarang mimpi. Mimpimu itu adalah sebagai ilham dari Allah bahwa engkau di belakang hari akan menjadi orang besar serta berpengaruh, dan manusia akan tunduk patuh kepadamu termasuk saudara-saudaramu dan aku serta ibumu. Aku tidak dapat menjamin bahwa saudara-saudaramu tidak akan melakukan tindakan-tindakan buruk terhadapmu.\"\n\nNasihat ayahnya itu disadari sepenuhnya oleh Yusuf dan selalu diingat dan dikenangnya sehingga nanti pada akhir kisah ketika ia telah dapat bertemu dengan seluruh keluarganya, ia tetap mengatakan bahwasanya setanlah yang memperdaya saudara-saudaranya sehingga terputus hubungan antara dia dengan keluarganya, sebagaimana tersebut dalam firman Allah:\n\nDan dia (Yusuf) berkata, \"Wahai ayahku! Inilah takwil mimpiku yang dahulu itu. Dan sesungguhnya Tuhanku telah menjadikannya kenyataan. Sesungguhnya Tuhanku telah berbuat baik kepadaku, ketika Dia membebaskan aku dari penjara dan ketika membawa kamu dari dusun, setelah setan merusak (hubungan) antara aku dengan saudara-saudaraku. Sungguh, Tuhanku Mahalembut terhadap apa yang Dia kehendaki. Sungguh, Dia Yang Maha Mengetahui, Mahabijaksana.\" (Yusuf\u002F12: 100)","6":"Selanjutnya ayahnya berkata, \"Demikianlah Tuhan akan memilihmu untuk menjadi nabi dan mengangkat derajatmu menjadi penguasa serta menganugerahkan kepadamu berbagai macam nikmat dan kemuliaan. Dia akan memberikan kepadamu ilmu dengan mengilhamkannya kepadamu. Dengan ilmu itu kamu dapat mentabirkan mimpi dan mengetahui hal-hal yang tidak dapat diketahui oleh manusia biasa.\" Hal ini terbukti di waktu Yusuf dalam penjara, dapat mentabirkan mimpi raja Mesir sehingga ia menjadi orang yang disegani dan diangkat menjadi penguasa tertinggi. Selain itu dapat mengetahui makanan apa yang akan dibawa oleh pegawai penjara sebelum makanan itu sampai ke kamar temannya seperti tersebut dalam firman Allah dalam surah ini juga.\n\nDia (Yusuf) berkata, \"Makanan apa pun yang akan diberikan kepadamu berdua aku telah dapat menerangkan takwilnya, sebelum (makanan) itu sampai kepadamu. Itu sebagian dari yang diajarkan Tuhan kepadaku.\" (Yusuf\u002F12: 37)\n\nKemudian Yakub berkata lagi kepada Yusuf dalam ayat ini, \"Allah akan menyempurnakan nikmat dan karunia-Nya kepadamu dan kepada keluarga Yakub termasuk ayahmu, saudaramu, dan keturunan mereka di belakang hari. Adapun nikmat dan karunia-Nya kepadamu ialah seperti yang telah diterangkan tadi, sedang nikmat dan karunia-Nya kepada ayah dan ibumu serta saudara-saudaramu dan keturunan mereka ialah terlepasnya mereka dari berbagai macam kesulitan serta marabahaya dan mendapat kehormatan serta kedudukan di Mesir, kemudian di antara keturunan keluarga Yakub akan diangkat pula beberapa orang nabi. Semua nikmat dan karunia itu telah diberikan Allah kepada kakekmu Ibrahim serta Ishak. Kepada Ibrahim, Allah telah menjanjikan akan memilih di antara keluarga dan keturunannya untuk menerima kenabian dan kitab suci.\"\n\nLanjut Yakub lagi, \"Demikianlah tabir mimpi itu dan bergembiralah dengan rahmat dan karunia Allah yang akan dianugerahkan kepadamu, tetapi engkau harus tabah dan sabar menghadapi segala ujiannya dan penuh tawakkal serta rela atas segala yang ditimpakan-Nya kepadamu, karena Dia Mahabijaksana dan Maha Mengetahui segala apa yang ditetapkan-Nya.\"","7":"Allah memperingatkan lebih dahulu bahwa pada kisah Nabi Yusuf a.s. ini terdapat teladan yang baik dan pelajaran bagi orang yang memperhatikannya yaitu betapa besar kekuasaan Allah swt, dan betapa luas hikmah dan kebijaksanaan-Nya dalam mengatur sesuatu dalam suatu rentetan kejadian yang akhirnya sampai kepada tujuan yang dimaksud yaitu pemberian rahmat dan karunia kepada orang yang dikasihi-Nya. Sesudah itu barulah Allah mengisahkan bagaimana sikap saudara-saudara Yusuf terhadapnya.","8":"Saudara-saudara Yusuf berkata sesama mereka, \"Sesungguhnya ayah kita lebih banyak menyayangi Yusuf dan saudaranya Bunyamin dan lebih banyak menumpahkan perhatiannya kepada keduanya, padahal kitalah yang lebih berhak untuk disayangi dan diperhatikan, karena kita ini sudah menjadi orang dewasa yang kuat dan dapat membelanya serta memenuhi segala kebutuhannya. Sikap ayah kita itu bertentangan dengan keadilan dan persamaan hak antara anak-anak. Mengapa ayah lebih mengutamakan dua orang anak yang lemah dan tak berdaya itu dari pada kita yang kuat serta lebih sanggup berkhidmat dan berbakti kepadanya?\"\n\nSepintas lalu nampak dengan jelas kebenaran ucapan saudara-saudara Yusuf itu, seakan-akan Nabi Yakub a.s. telah membuat kekeliruan dengan tindakannya itu padahal dia seorang nabi yang selalu dibimbing Allah dalam segala sikap dan tindakannya. Menurut riwayat memang Yakub menumpah-kan perhatian yang besar terhadap Yusuf, karena ada firasat dan tanda-tanda yang menunjukkan bahwa Yusuf mempunyai keistimewaan pada sifat dan pembawaannya. Keistimewaan ini tidak dimiliki oleh saudara-saudaranya yang lain. Maka Yakub sangat menaruh harapan kepadanya, apalagi setelah ia mendengar Yusuf menceritakan mimpinya. Jika Yakub lebih cinta kepada Yusuf dan lebih banyak memperhatikannya, maka hal itu adalah wajar, sebab Yusuf dan Bunyamin masih kecil-kecil dan lebih banyak membutuhkan perhatian dan bimbingan orang tuanya dibanding saudara-saudaranya yang sudah besar. Hanya sifat iri dan dengki sajalah yang mendorong saudara-saudaranya untuk melakukan tindakan permusuhan terhadapnya, bukanlah karena ayah mereka sudah menyimpang dari jalan keadilan.","9":"Dalam suatu musyawarah untuk menetapkan tindakan yang tepat dan tegas terhadap Yusuf, mereka mengusulkan agar dia dibunuh saja atau dibuang ke tempat yang jauh, sehingga ia tidak mungkin kembali atau binasa dan mati di tempat pembuangan itu. Dengan demikian, ayah mereka Yakub akan berputus asa dan tidak mempunyai harapan lagi untuk bertemu dengan anaknya yang paling disayanginya itu, dan lama kelamaan tentunya dia akan melupakannya. Selama ini yang menjadi halangan baginya untuk memperhatikan mereka ialah Yusuf di sampingnya. Bila Yusuf sudah tiada atau tersingkir ke negeri yang jauh, tentulah ayah mereka akan kembali memperhatikan dan menyayangi mereka. Mereka menginsyafi bahwa tindakan ini adalah suatu tindakan yang kejam tidak berperikemanusiaan, suatu tindakan kriminal yang sangat besar dosanya. Akan tetapi, mereka telah jauh tersesat dari jalan yang benar dan terjerumus ke dalam perangkap setan, sehingga tidak nampak lagi oleh mereka akibat perbuatan itu bagi ayah dan diri mereka sendiri jika perbuatan itu dilakukan.\n\nMereka membujuk diri mereka sendiri dengan mengatakan, meskipun mereka telah berdosa, pintu tobat masih terbuka lebar. Mereka akan bertobat dengan tobat nasuha dan tidak akan berbuat seperti itu lagi, dan menjadi hamba Allah yang saleh. Tentu Allah akan menerima tobat, mengampuni segala dosa dan kesalahan hamba-Nya, dengan demikian ayah mereka akan merasa senang kepada mereka, dan Allah tidak akan menyiksa mereka.","10":"Rupanya masih ada di antara mereka yang tidak mau melaksanakan usul itu dan masih mengalir dalam tubuhnya rasa kasih sayang terhadap saudaranya dan tergambar dalam khayalnya, betapa ngerinya perbuatan itu. Dia mengusulkan agar Yusuf jangan dibunuh jika hanya ingin memisahkan dari ayahnya dan menarik perhatian ayah mereka kembali. Mengapa untuk mencapai tujuan itu kita harus melakukan pembunuhan, melakukan suatu dosa besar yang belum tentu akan diampuni Tuhan? Dia mempunyai usul yang tidak begitu berat dosanya yaitu menjatuhkan Yusuf ke dalam sumur dan nanti dia akan ditemukan oleh para musafir dan akan dibawa mereka ke negeri yang jauh. Dengan demikian, Yusuf tidak akan mati dan mereka bebas dari dosa pembunuhan sedang maksud dan tujuan tercapai juga. Akhirnya usul ini mereka terima dengan baik, dan mereka sudah bertekad dalam hati untuk melaksanakannya.","11":"Pada ayat ini, terbayang dengan jelas betapa besar kecurigaan Nabi Yakub terhadap para saudara Yusuf dan kekhawatirannya apabila ia membiarkan Yusuf bergaul dengan mereka, apalagi setelah mendengar cerita Yusuf tentang mimpinya. Sikap ayah mereka itu sangat menjengkelkan hati dan menyinggung perasaan mereka. Dengan terus terang mereka berkata, \"Wahai ayah kami, mengapa engkau selalu mencurigai kami terhadap Yusuf, padahal kami tetap mencintai dan menyayanginya, selalu berusaha agar dia senang dan gembira, dan tidak pernah terlintas dalam pikiran kami akan menyakiti hatinya apalagi menganiayanya. Mengapa engkau tidak membiarkan dia bergaul, bercengkerama dengan sewajarnya seakan-akan engkau menaruh curiga terhadap kami.\"","12":"Saudara-saudara Yusuf kembali membujuk ayahnya dengan menyatakan, \"Biarkanlah dia pergi berekreasi dengan kami besok ke tempat pengembalaan, berolah raga, dan berlomba. Kami akan membawa makanan yang enak-enak dan buah-buahan yang lezat, yang akan kami santap setelah selesai bermain-main. Kami akan selalu menjaga dan memeliharanya dari segala bahaya. Percayakanlah dia kepada kami. Insya Allah dia akan senang bersama kami dan kami pun menyenangi dia, dan dia akan kami bawa pulang dengan selamat dan tidak kurang suatu apa.\"","13":"Yakub berkata kepada mereka, \"Hai anak-anakku! Aku akan menjadi gelisah dan sedih jika kamu membawanya bermain-main berolah raga dan berlomba dan tinggal sendirian karena masih kecil, dan belum sanggup melayanimu bermain-main? Siapa tahu datang serigala lalu menerkamnya sedangkan kamu semua sedang asyik bermain-main.\"","14":"Mereka menjawab, \"Wahai ayah kami, sungguh tidak pada tempat-nya ayah curiga dan gelisah serupa itu dan janganlah ayah merasa khawatir atas keselamatan Yusuf. Kami ini sudah besar-besar dan dewasa, kami ini orang-orang kuat semuanya, dan kami telah berjanji akan menjaganya. Apa yang ayah khawatirkan itu tidak mungkin akan terjadi, dan kalau terjadi juga maka apalah arti hidup bagi kami, jika kami yang besar dan yang kuat ini tidak bisa menjamin keselamatan adik kami. Dengan demikian kami akan termasuk orang-orang yang merugi, orang yang tidak berharga sedikitpun.\" Akhirnya karena desakan yang sangat kuat dari saudara-saudara Yusuf dan mereka telah memberikan jaminan pula, maka dengan perasaan yang berat, terpaksalah Yakub memberi izin kepada mereka untuk membawa Yusuf bermain-main ke tempat gembala di padang pasir.","15":"Pada ayat 10 surah ini telah diterangkan bahwa saudara-saudara Yusuf telah sepakat akan memasukkan Yusuf ke dalam sumur dengan harapan ia akan ditemukan oleh kafilah yang ingin mengambil air dan di bawa ke negeri yang jauh agar ia tidak dapat ketemu lagi dengan ayahnya. Pada ayat ini diterangkan bahwa sesampainya mereka di suatu tempat yang ada sumurnya mereka melaksanakan permufakatan jahat mereka, dan memasukkan Yusuf ke dalam sumur. Dengan demikian, mereka merasa amat gembira karena momok yang selama ini menghantui jiwa mereka sudah tidak ada lagi. Menurut anggapan mereka Yusuflah yang merebut kasih sayang ayahnya dan sekarang karena dia tidak ada lagi tentulah kasih sayang Yakub akan bertumpah kepada mereka. Bagaimana dengan Yusuf sendiri yang telah mendekam dalam sumur yang gelap itu? Tentu dia sangat bersedih hati dan terbayanglah dalam pikirannya bahwa dia akan mati kedinginan dan kelaparan dan tidak akan bertemu lagi dengan ayah ibunya serta saudara-saudaranya. Pada saat yang amat kritis itulah, Allah mengilhamkan kepadanya agar dia jangan khawatir dan jangan bersedih hati. Allah akan memeliharanya dan melepaskannya dari bahaya yang menimpanya. Nanti dia akan mendapat pertolongan dari kafilah dan akhirnya ia akan mendapat kedudukan yang tinggi, sehingga ia dapat mengingatkan saudara-saudaranya atas pengkhianatan mereka, sedang mereka sendiri tidak sadar bahwa orang yang menceritakan itu adalah Yusuf sendiri.","16":e,"17":e,"18":"Untuk memperkuat kebenaran cerita itu mereka membawa baju Yusuf yang telah berlumuran darah dan mereka berkata kepada ayahnya, \"Inilah bukti kebenaran kami.\" Padahal, darah yang melekat pada baju itu bukanlah darah Yusuf. Yakub melihat dan memperhatikan baju itu.\n\nDidapatinya baju itu hanya berlumuran darah saja, tetapi masih utuh tak ada yang robek dan tak ada pula yang berlubang-lubang bekas cakaran dan gigitan serigala, pasti saudara-saudaranya inilah yang telah berbuat aniaya terhadapnya, lalu ia berkata kepada mereka, \"Aku tidak percaya sama sekali akan ceritamu yang dibuat-buat itu dan aku yakin bahwa jiwamu yang jahat dan kotor, telah mempengaruhi dan mendorongmu untuk melakukan penganiayaan terhadap saudaramu sendiri.\" Tetapi apalah daya seorang ayah yang telah tua terhadap anak-anaknya yang sudah besar dan kuat. Dia tidak dapat berbuat apa-apa lagi kecuali menahan rasa amarah dan menekan perasaan hatinya yang amat kecewa dan sedih itu. Kini anaknya yang paling dicintainya dan kepadanya dia selalu menggantungkan harapan sudah tak ada lagi di sampingnya karena tindakan anak-anaknya sendiri. Apakah dia akan menuntut balas ataukah dia akan menyelidiki sendiri ke mana anaknya itu sebenarnya, sedang dia tidak berdaya lagi.\n\nDalam keadaan seperti itu tidak ada yang lebih baik baginya kecuali bersabar dan tawakal sepenuhnya kepada Allah. Jalan inilah yang dipilih Yakub meskipun ia tetap sedih dan tetap menangis atas kehilangan jantung hatinya. Ia tidak percaya sama sekali akan cerita anak-anaknya. Oleh karena itu, ia berserah diri kepada Allah dan selalu memohon pertolongan-Nya agar anaknya Yusuf diselamatkan dari segala marabahaya.","19":"Tidak lama sesudah Yusuf berada di dalam sumur, datanglah kafilah dari Madyan hendak berangkat ke Mesir. Kebetulan persediaan air mereka sudah habis dan pergilah mereka ke sumur itu lalu menjatuhkan timba ke dalamnya untuk mengambil air. Melihat timba diulurkan ke dalam sumur, hati Yusuf gembira dan timbul harapan di dalam hatinya bahwa dia akan dapat keluar dari bahaya yang sedang dihadapinya. Dengan cepat dia pegang tali timba itu kuat-kuat, sehingga orang yang menimba heran mengapa air sumur ini amat berat. Tetapi mereka tetap menarik tali itu bersama-sama, dan ternyata bukan air yang terangkat, tetapi seorang anak kecil yang manis dan elok rupanya. Alangkah gembiranya pemimpin kafilah itu melihat anak yang sehat dan segar bugar itu. Terbayanglah dalam pikirannya ia akan mendapat keuntungan yang besar dengan menjualnya kepada orang kaya di Mesir nanti. Dengan cepat ia memerintahkan agar Yusuf disembunyikan supaya jangan kelihatan oleh orang lain karena mungkin orang-orang di daerah itu akan mengakui bahwa anak itu adalah anak penduduk kampung itu sendiri. Tetapi Allah Maha Mengetahui niat pemimpin kafilah itu sebagaimana Dia mengetahui apa maksud dan tujuan saudara-saudara Yusuf memasukkannya ke dalam sumur.","20":"Akhirnya sampailah kafilah itu ke Mesir dan di sana mereka jual Yusuf dengan harga yang murah sekali dibanding dengan mahalnya harga budak di negeri itu, apalagi Yusuf adalah seorang anak yang tampan dan segar bugar.\n\nPara mufasir mengatakan tentang \"beberapa dirham yang dihitung\" bahwa yang pasti harganya kurang dari 40 dirham karena menurut adat kebiasaan di sana bila uang itu jumlahnya 40 dirham atau lebih, maka uang itu tidak dihitung lagi tetapi ditimbang. Mereka menjual Yusuf dengan harga yang begitu murah karena mereka khawatir kalau-kalau ada orang yang tahu bahwa Yusuf bukan budak, mengapa ia diperjualbelikan sedang dia adalah anak yang merdeka, anak orang baik. Karena kekhawatiran itulah mereka ingin cepat-cepat berlepas diri dari dia, asal mereka diberi uang berapa pun jumlahnya cukuplah bagi mereka. Rupanya sudah ditakdirkan Allah mereka menjual Yusuf kepada seorang penguasa yang amat berpengaruh di Mesir yaitu menteri yang kaya yang disebut al-Aziz agar dia mendapatkan kesempatan untuk menaiki kekuasaan dan kemuliaan.","21":"Menteri yang mengambil Yusuf sangat gembira dan berbesar hati karena dapat membeli seorang anak yang elok rupanya, segar dan sehat badannya ditambah lagi karena terdapat padanya tanda-tanda yang baik yang menunjukkan bahwa dia akan mempunyai masa depan yang gemilang sama seperti firasat ayahnya Yakub terhadapnya.\n\nDiriwayatkan bahwa Abdullah bin Masud pernah berkata tentang hal ini, katanya, \"Orang-orang yang paling tepat firasatnya adalah tiga orang, pertama, al-Aziz ketika ia memerintahkan kepada istrinya agar Yusuf diberikan tempat dan kedudukan yang baik di istananya; kedua, puteri syekh dari Madyan yang meminta kepada ayahnya agar Nabi Musa a.s. diserahi tugas memelihara dombanya sebagai orang gajian; dan ketiga, Abu Bakar ketika dia mengangkat Umar bin Khaththab sebagai penggantinya. \n\nOleh karena gembiranya, menteri itu memerintahkan kepada istrinya, \"Berikanlah kepadanya tempat yang baik di istana ini. Perlakukanlah dia sebagai salah seorang keluarga bukan sebagai hamba atau pelayan, karena dia akan menjadi seorang yang berjasa kepada kita dan negara atau kita angkat dia sebagai anak yang kita cintai dan sayangi yang akan menjadi pewaris kita kelak kemudian hari.\"\n\nDemikianlah Allah mengatur dan mentakdirkan dengan membentangkan jalan bagi Yusuf dan memberi kesempatan kepadanya agar ia mengembang-kan bakat dan kepandaiannya sehingga dia mendapat kedudukan yang tinggi di Mesir. Di samping itu, Allah mengajarkan pula kepadanya ilmu menafsirkan mimpi dan dengan ilmu itu kelak ia dapat berhubungan dengan raja dengan cara menafsirkan mimpi raja sehingga ia dikeluarkan dari penjara dan mendapat kepercayaan yang besar sekali dan akhirnya diserahkan kepadanya urusan perbendaharaan dan kekayaan negara. Demikianlah Allah melaksanakan kehendak-Nya itu, tetapi kebanyakan manusia tidak mengetahui.","22":"Di kala Yusuf mulai dewasa, Allah memberikan pula kepadanya kecerdasan dan kebijaksanaan sehingga ia mampu memberikan pendapat dan pikirannya dalam berbagai macam masalah yang dihadapi. Allah juga memberikan kepadanya ilmu, meskipun ia tidak belajar. Ilmu yang didapat tanpa belajar ini dinamai ilmu ladunni karena ia semata-mata ilham dan karunia dari Allah.\n\nDemikianlah Allah memberi balasan kepada Yusuf yang tidak pernah mengotori dirinya dengan perbuatan keji dan jahat, selalu menjaga kebersihan hati nuraninya, selalu bersifat sabar dan tawakal atas musibah dan bahaya yang menimpanya. Demikianlah Allah membalas setiap insan yang berbuat baik.","23":"Istri al-Aziz adalah seorang perempuan cantik, sangat dimuliakan oleh seluruh penghuni istana, karena di samping dia istri al-Aziz, dia juga berbudi tinggi, berakhlak mulia, bersih dari sifat-sifat congkak dan sombong, menjauhi segala hal yang akan menjatuhkan derajatnya. Tetapi setelah Yusuf tinggal di istana sebagai salah seorang keluarganya, istri al-Aziz mulai tertarik kepadanya karena akhlak dan ketampanannya. Suatu ketika, setelah mengunci semua pintu rumah, istri al-Aziz merayu Yusuf untuk berselingkuh. Yusuf sebagai seorang yang jujur dan berakhlak mulia sangat terkejut mendengar rayuan dan ajakan itu, apalagi yang mengajaknya itu adalah istri majikannya sendiri yang telah memberinya tempat berteduh dan memperlakukannya seperti anaknya sendiri. Selain dari itu, bila ia mematuhi ajakan demikian, berarti ia telah melakukan maksiat yang sangat dimurkai Allah. Karena itu dengan spontan ia menjawab, \"Aku berlindung kepada Allah agar aku jangan terjerumus ke dalam perbuatan keji dan mungkar. Suamimu itu adalah tuanku, majikanku yang telah berbuat baik kepadaku, apakah kebaikannya aku balas dengan kekejian? Ini adalah suatu kezaliman dan aku tidak akan melakukannya karena tidak ada orang yang zalim yang sukses dan bahagia hidupnya.\"","24":"Istri al-Aziz tidak mau berhenti, karena ia menganggap Yusuf sebagai budak yang harus melaksanakan keinginan dan perintahnya. Bila Yusuf menolak, istri al-Aziz akan mencelakakannya. Tetapi dari pihak Yusuf, ia telah bertekad pula untuk menolaknya karena perbuatan itu melanggar agama, mengkhianati tuannya yang telah berjasa dan berbuat baik kepadanya dan merusak kehormatannya dan kehormatan tuannya. Yusuf dan istri al-Aziz masing-masing telah mempunyai tekad yang bertolak belakang antara satu sama lainnya.","25":"Dalam keadaan yang bertambah gawat itu, yang seorang tetap mendesak dan yang lain tetap menolak, Yusuf memutuskan akan lari dari hadapan istri majikannya dan dengan cepat ia melompat ke pintu tetapi istri al-Aziz menangkap bajunya dari belakang hingga robek. Dalam keadaan tarik-menarik itu, muncullah al-Aziz di muka pintu. Dengan serta merta berteriaklah istri al-Aziz mengatakan bahwa Yusuf mencoba memperkosa-nya dengan kekerasan. Dia meminta kepada suaminya agar Yusuf diberi ganjaran yang setimpal. Balasan yang tepat bagi orang yang melakukan kejahatan terhadap keluarganya ialah penjara atau siksa yang pedih.","26":"Ayat ini menerangkan tentang bersihnya Yusuf dari berbuat serong, Yusuf adalah seorang pemuda yang takut kepada Tuhannya, yang tidak goyah imannya oleh bujuk rayu seorang wanita. Dengan tegas dia berkata kepada menteri, suami dari perempuan itu, \"Dalam peristiwa yang terjadi ini, sebenarnya perempuan itulah yang menggoda saya dan mengajak saya untuk memenuhi kehendak nafsunya, sampai saya melompat lari seperti yang tuan dapati sekarang ini.\" Dalam peristiwa Yusuf ini, banyak sekali tindakan yang bisa diambil oleh menteri untuk mencari bukti-bukti yang membenar-kan bahwa Yusuf adalah seorang yang bersih, karena Yusuf adalah budak yang biasanya tidak berani berbuat serong terhadap istri majikannya. Yusuf didapati oleh al-Aziz sedang melompat hendak keluar dari dalam rumah. Ini menunjukkan bahwa al-Aziz melihat istrinya dalam keadaan bersalah dengan mengenakan pakaian yang bagus sekali, dengan bedak dan wangi-wangian yang semerbak baunya, sedang tidak terdapat di muka Yusuf bekas-bekasnya. Sebagai bukti yang lain yang kuat sekali, bahwa suaminya tidak pernah melihat akhlak Yusuf yang buruk, semenjak Yusuf tinggal di rumahnya.","27":"Dengan pengetahuan dan pengalamannya terhadap Yusuf, sebenar-nya al-Aziz telah mempercayai bahwa Yusuf tidak bersalah. Kemudian keyakinannya ini dikuatkan lagi oleh saksi yang lain, yang menyatakan, bahwa Yusuf tidak bersalah. Saksi itu ialah anak paman isteri al-Aziz, menurut sebagian mufassir namanya adalah Zulaikha, seorang cerdik cendekiawan lagi bijaksana. Saksi itu berkata, \"Kami mendengar suatu keributan, tarik-tarikan dalam rumah, sampai kami mendengar bunyi kain sobek. Kalau baju Yusuf yang sobek di muka, maka perempuan itulah yang benar dan Yusuf pendusta. Kalau bajunya sobek di bagian belakang, benarlah Yusuf dan perempuan itu pendusta.\" Menurut sebagian riwayat, yang menjadi saksi peristiwa ini, ialah seorang bayi yang ditakdirkan Allah dapat berbicara untuk sekedar menjadi saksi. Tetapi riwayat ini adalah lemah. Pendapat yang kuat yang menyatakan bahwa saksi dalam peristiwa ini, ialah anak paman istri al-Aziz itu sendiri.","28":"Setelah diadakan penyelidikan dan pertukaran pikiran antara menteri dengan keluarga istrinya tentang peristiwa yang terjadi ini, maka diperiksalah baju Yusuf yang sobek itu. Ternyata baju Yusuf bagian belakang yang robek. Jelaslah dalam peristiwa ini, Yusuf yang benar tidak dapat dibantah dan diragukan lagi. Maka tuduhan perempuan itu terhadap Yusuf adalah palsu. Tapi bagaimanapun pandainya orang bersalah mengemukakan alasan-alasannya, namun yang bersalah akan diketahui juga, sesuai dengan pepatah: \"Sepandai-pandainya membungkus yang busuk, akhirnya akan berbau juga.\" Setelah jelas duduk perkara peristiwa ini, maka menteri berkata kepada istrinya, \"Sekarang jelas, engkau telah membujuk dan merayu Yusuf. Ketahuilah, bujuk rayu yang seperti itu besar bahayanya. Untung Yusuf seorang pemuda yang kuat imannya, tidak terpengaruh oleh godaan seperti yang engkau lakukan itu.\"","29":"Selanjutnya dalam ayat ini, menteri itu berkata, \"Wahai Yusuf, peliharalah dirimu, tutup mulutmu, jangan sampai kejadian ini engkau ceritakan kepada orang lain. Kejadian ini adalah rahasia kami, kalau diketahui orang, kami akan mendapat malu. Engkau jangan merasa takut dalam persoalan ini, percayalah bahwa kami tetap menjaga namamu, sebab engkau benar-benar orang yang berakhlak mulia dan beriman kuat. Engkau hai istriku, bertakwalah kepada Tuhanmu, minta ampunlah atas dosamu, karena engkau termasuk orang yang bersalah dan berdosa. Kesalahanmu sangat besar yaitu mengkhianati suamimu, dan kesalahan menuduh orang lain yang bersih dan suci.\"","30":"Dalam ayat ini diterangkan bahwa kejadian yang dirahasiakan itu, akhirnya tersebar juga. Bagaimana usaha menteri beserta segenap keluarga istana menutup-nutupi rahasia rumah tangganya, usahanya itu sia-sia saja. Berita itu telah menjadi buah bibir perempuan dalam kota. Lebih-lebih di kalangan istri pembesar-pembesar dan pemimpin kerajaan itu. Mereka membicarakannya, bahwa istri menteri menggoda bujangnya. Bukan hanya sekadar mengatakan bahwa istri menteri telah jatuh cinta kepada bujangnya itu, dan tidak memperdulikan lagi akibat-akibat buruk yang akan terjadi, seperti nama suaminya menjadi tercemar. Selanjutnya mereka mengatakan, \"Sungguh kami melihat istri menteri itu sudah menempuh jalan sesat yang akan membawa kepada kehinaan.\"","31":"Pergunjingan perempuan-perempuan itu sampai juga ke telinga istri menteri yang menyebabkan ia merasa marah bercampur malu. Dia tidak mengira bahwa berita mengenai dirinya akan tersebar luas seperti itu, sebab sudah cukup usahanya untuk menutupi rahasia itu. Dia mencari akal, bagaimana caranya menutup malu yang sudah tersebar luas itu. Maka diundangnyalah perempuan-perempuan terkemuka itu datang ke rumahnya menghadiri suatu jamuan. Untuk pesta itu, sudah diatur tempat sebaik-baiknya, makanan yang enak-enak, dan minuman dari berbagai macam sudah disiapkan. Tidak ketinggalan buah-buahan yang segar dan manis yang bermacam jenis dan ragamnya sudah disediakan di meja makan. Kursi-kursi yang bagus sudah disusun untuk dapat duduk bersantai, menikmati makanan dan buah-buahan yang lezat cita rasanya. Undangan ini mendapat sambutan yang hangat, lebih-lebih dari perempuan-perempuan yang ingin mengetahui kejadian yang sudah menjadi buah bibir selama ini, terutama ingin melihat anak muda yang bernama Yusuf itu. Meriah sekali pesta itu. Gelak tawa bersahut-sahutan, omong dan kelakar menjadi-jadi. Bermacam makanan dihidangkan tidak putus-putusnya. Begitu juga minuman. Terakhir sekali dihidangkan buah-buahan. Kepada masing-masing yang hadir diberikan sebuah pisau untuk mengupas buah-buahan. Di saat itu, istri menteri yang menjadi nyonya rumah, memerintahkan kepada Yusuf untuk ke luar ke tengah-tengah para tamu yang sedang duduk bersantai memotong buah-buahan untuk memperkenalkan dirinya. Maka keluarlah Yusuf dan berdiri di hadapan tamu-tamu itu. Baru saja perempuan-perempuan itu melihat wajah Yusuf yang sangat elok seperti bulan purnama, kagumlah mereka melihatnya, bahkan lupa akan diri mereka masing-masing karena terpesona oleh kegagahan dan ketampanan Yusuf. Dengan tidak sadar, pisau yang ada di tangan mereka, mereka potongkan ke tangan dan jari mereka sendiri, bukan untuk memotong buah-buahan dan mereka tidak merasakan sakit perihnya.\n\nDari mulut mereka keluar kata-kata, \"Mahasempurna Allah, dia bukanlah manusia, tetapi adalah malaikat yang mulia.\" Begitu kagum dan tercengang mereka melihat Yusuf yang sangat menawan dan menggetarkan jantung mereka, inilah sosok orang yang mereka bicarakan sehari-hari dengan mempersalahkan dan mengejek istri menteri.","32":"Ayat ini menerangkan bahwa perempuan-perempuan yang diundang itu kagum dan terpesona melihat Yusuf. Melihat reaksi mereka, istri menteri itu gembira, lalu berkata, \"Inilah dia Yusuf yang selalu kamu guncingkan dan selalu kamu mencela sikap saya terhadap Yusuf dan kejadian antara saya dengan dia baru-baru ini. Sekarang kamu semua terpesona memandanginya. Baru sepintas lalu kamu memandangnya, kamu sudah lupa diri. Lihatlah kamu sudah memotong jarimu karena terpesona memandang Yusuf.\"\n\nIstri al-Aziz berkata, \"Saya akui terus terang, memang sayalah yang telah jatuh cinta kepadanya dan sayalah yang menggodanya dan mengajaknya berlaku serong. Tetapi dia tetap enggan dan berlindung diri kepada Tuhannya. Dia berpaling dan menjauhkan dirinya daripadaku. Aku terus menggodanya dan merayunya sampai dia mau mengikuti keinginan hawa nafsuku. Seandainya dia juga tidak mau, aku akan katakan kepada suamiku, supaya dia dimasukkan ke dalam penjara dan tentunya dia akan menjadi orang yang hina. Suamiku tidak berani menolak usulku itu dan suamiku akan menghukum dia sesuai dengan keinginanku.\"\n\nSengaja kata-kata itu dilontarkannya di hadapan tamu-tamu dalam jamuan yang meriah itu, supaya didengar oleh Yusuf sendiri dan supaya para tamu dapat melunakkan hati Yusuf. Lebih baik mematuhi apa saja kehendak istri al-Aziz daripada mendapat kemarahan yang akhirnya akan dipenjara-kan, hidup bersama-sama dengan orang-orang jahat dan hina-dina. Bila Yusuf mau mengikuti kehendaknya, tentu Yusuf akan beruntung seluruh kekayaan dan kemewahan isi istana itu dapat pula dikuasai Yusuf. Pendek-nya, semua yang hadir pada waktu itu telah berpihak kepada istri al-Aziz, tidak lagi menyalahkan dan mengejeknya. Semua membenarkan, sudah sepantasnya istri menteri tergoda dan tergila-gila oleh Yusuf yang tinggal di rumahnya. Maka semua perempuan itu, turut membujuk Yusuf agar mematuhi kehendak istri menteri itu, tanpa malu-malu dan takut-takut.","33":"Ayat ini menerangkan bagaimana keteguhan hati dan kekuatan iman Yusuf yang tidak mempan segala bujukan dan rayuan, begitu juga semua kata-kata untuk melunakkan hati Yusuf yang keluar dari mulut perempuan-perempuan itu. Tidak mencemaskan hati Yusuf gertakan dan ancaman yang mengatakan bahwa Yusuf akan dipenjarakan dan dihukum, kalau dia tidak mau tunduk mengikuti ajakan untuk berbuat serong itu. Mendengar semua itu, Yusuf hanya berlindung diri kepada Allah, menundukkan kepala sambil berdoa agar dijauhkan Tuhan dari godaan perempuan-perempuan itu seraya berkata, \"Ya Tuhanku, penjara yang gelap lagi sempit itu lebih baik bagiku daripada dalam istana, menghadapi perempuan-perempuan yang cantik yang selalu menggoda dan mengajakku untuk memenuhi keinginan hawa nafsunya. Aku khawatir ya Allah, bila aku masih tinggal dalam istana ini, selalu berhadapan dengan perempuan-perempuan yang menggodaku, kalau-kalau semangatku melemah, imanku luntur, sehingga aku terperosok jatuh ke lembah kehinaan bersama mereka. Ya Allah, hindarkanlah aku dari godaan-godaan mereka. Tidak ada daya dan kekuatan bagiku untuk lepas dari bahaya itu selain dengan pertolongan dan petunjuk-Mu. Ya Allah, kalau bukan karena pertolongan dan petunjuk-Mu, aku akan jadi orang yang bodoh, sesat jalan dan mudah terpedaya akhirnya terjerumus ke dalam lembah kehinaan dan maksiat.\"","34":"Ayat ini menerangkan bahwa akhirnya Yusuf dimasukkan ke dalam penjara. Doa Yusuf diperkenankan Tuhannya, agar Yusuf tetap dipelihara dari godaan dan tipu-daya perempuan-perempuan itu. Maka menteri memasukkan Yusuf ke dalam penjara sekadar memenuhi permintaan istrinya, oleh karena istrinya meminta kepada suaminya supaya jangan membocorkan peristiwa itu dan berusaha menenteramkan suasana rumah tangganya. Maksud Allah mengabulkan doa Yusuf untuk masuk penjara berlainan dengan maksud pembesar itu (al-Aziz). Maksud Allah ialah supaya Yusuf tetap bersih, terpelihara dari segala godaan yang mengotori jiwanya. Juga supaya Yusuf menjadi orang yang sabar dan tahan menderita dalam penjara, bergaul dengan orang-orang yang sudah lama meringkuk dalam penjara dengan bermacam-macam karakter, tingkah laku, dan perangainya. Sebab Yusuf akan diangkat Allah menjadi nabi untuk kaumnya. Penjara adalah tempat mendewasakannya dan tempat pertama kali Allah menurunkan wahyu kepadanya. Oleh karena itu, Allah selalu menjaganya dan Allah adalah Maha Mendengar lagi Maha Mengetahui segala doa yang dipanjatkan dan segala perbuatan yang dikerjakan hamba-Nya.","35":"Ayat ini menerangkan bahwa menteri beserta istrinya telah melihat bukti-bukti bahwa Yusuf adalah orang baik, jujur, dan mempunyai akhlak yang mulia serta mempunyai keimanan dan kepercayaan yang teguh kepada Tuhannya. Selama mereka bergaul dengan Yusuf, tidak pernah mereka melihat perbuatan Yusuf yang salah. Nyata bagi mereka, bahwa Yusuf selalu dipelihara Tuhannya dan dilindungi-Nya dari perbuatan-perbuatan yang keji. Walaupun dia dituduh, dibujuk, dan diancam namun Yusuf tetap tenang dan selalu meminta perlindungan kepada Tuhannya. Hal seperti itu bukan saja diketahui dengan jelas oleh menteri dan istrinya, tetapi juga oleh seluruh keluarga istana. Sungguh pun begitu, Yusuf tetap dimasukkan ke dalam penjara untuk waktu yang tidak ditentukan sebagai pelaksanaan dari permintaan istrinya, agar dianggap oleh orang banyak bahwa Yusuf bersalah, padahal istrinya yang bersalah. Yusuf tidak merasa sengsara dan hina dalam penjara. Dengan pergaulan dalam penjara itu, Yusuf bertambah kuat imannya, bertambah tabah hati dan jiwanya, makin banyak rahasia manusia yang diketahuinya, dan makin besar keagungan Allah yang dirasakannya.","36":"Ayat ini menerangkan bahwa bersama-sama dengan Yusuf masuk pula ke dalam penjara dua orang pemuda. Menurut riwayat, kedua pemuda itu ialah bekas tukang siram kebun raja dan bekas bendahara raja. Keduanya dimarahi karena bersalah dan dimasukkan ke dalam penjara. Pada suatu ketika, Yusuf melihat kedua pemuda itu duduk dengan bersedih hati seperti orang melamun. Maka Yusuf menyapa kedua pemuda itu, \"Mengapa kalian dalam keadaan begini?\" Jawab mereka, \"Kami tadi malam bermimpi yang aneh dan ajaib, sehingga kami gelisah dan sedih seperti yang engkau lihat ini. Kami tidak tahu apa tafsir mimpi kami ini.\" Yusuf berkata kepada keduanya, \"Tafsir mimpi kamu itu hanya Allah yang mengetahuinya, cobalah ceritakan kepada saya apa mimpi kalian.\" Maka salah seorang dari keduanya bercerita tentang mimpinya dan katanya, \"Saya bermimpi bahwa saya sedang berada dalam sebuah kebun anggur yang sangat lebat buahnya dan menghijau warnanya. Seakan-akan di tangan saya ada sebuah gelas kepunyaan raja. Dengan gelas itulah, saya menampung airnya sesudah saya peras anggur itu untuk dijadikan minuman.\" Sesudah itu yang seorang lagi menceritakan mimpinya pula, seraya berkata, \"Saya bermimpi bahwa saya membawa sebuah keranjang di atas kepala saya, penuh dengan bermacam-macam roti dan makanan. Tiba-tiba terbang melayang di atas kepala saya beberapa ekor burung, lalu disambarnya semua roti dan makanan yang ada dalam keranjang itu dan dibawanya terbang jauh.\" Keduanya memohon kepada Yusuf, agar Yusuf sudi memberikan tafsir mimpi mereka. Kepada Yusuf tertumpu harapannya, karena hanya Yusuf yang paling mereka percayai. Selama dalam penjara mereka telah mengenal Yusuf sebagai orang yang baik, luas ilmunya, baik pergaulannya, dan dekat dengan Tuhannya.","37":"Dalam ayat ini diterangkan, sebelum Yusuf memberikan takwil mimpi kedua pemuda itu, lebih dahulu dia berdakwah tentang kebesaran dan kekuasaan Allah, tentang nikmat Allah yang telah diperolehnya, dan sikap yang tidak mau tunduk kepada agama yang tidak benar. Yusuf berkata kepada kedua pemuda itu, \"Sebelum kamu berdua menerima makanan yang dikirimkan untukmu, aku sudah tahu apa makanan itu dan akan aku jelaskan kepadamu sekarang ini.\"\n\nMenurut riwayat, bahwa orang-orang kerajaan ada yang mengirimkan kepada orang-orang yang bersalah dalam penjara yaitu makanan yang dicampur dengan racun dengan maksud untuk membunuh mereka. Yusuf sudah tahu maksud orang-orang kerajaan itu dan telah dijelaskan kepada kedua orang pemuda itu. Yusuf menjelaskan bahwa ilmu yang seperti itu adalah wahyu dari Tuhannya kepadanya. \"Dengan ilmu itulah saya dapat mentakwilkan mimpi, bukan seperti tukang tenung dan ahli nujum yang mempergunakan pertolongan setan, menerka-nerka dan menjampi-jampi yang belum tentu benar terkaannya itu,\" kata Yusuf. Selanjutnya Yusuf menjelaskan bahwa dia tidak mau terpengaruh oleh ajaran agama yang salah. Dia tinggalkan kepercayaan orang-orang yang tidak benar itu, orang-orang yang tidak mau beriman kepada Allah dan mengingkari kehidupan akhirat.","38":"Dalam ayat ini diterangkan bahwa Yusuf melanjutkan pembicaraan-nya dengan kedua pemuda itu sebelum menerangkan takwil mimpi mereka. Yusuf mengatakan bahwa dia hanya patuh mengikuti agama nenek moyangnya, yaitu agama Nabi Ibrahim, Ishak, dan Yakub a.s., agama tauhid bukan agama yang mempersekutukan Allah. \"Tidak sepantasnya bagi kami para nabi dan rasul untuk mempersekutukan Allah dengan yang lain, seperti halnya dengan golongan Firaun dan pengikut-pengikutnya. Mereka mempersekutukan Allah dengan yang lain, seperti matahari, bulan, berhala-berhala dan lain-lain. Kepercayaan tauhid itu termasuk karunia Allah kepada kami para nabi dan rasul, begitu juga kepada semua orang yang mempunyai kepercayaan yang sama. Allah telah memberikan petunjuk kepada kami dan manusia yang beriman. Dengan diutusnya kami para nabi dan para rasul, kami menunjukkan kepada mereka mana jalan yang lurus dan mana jalan yang bengkok, kami terangkan kepada mereka kepercayaan yang benar. Namun begitu masih ada saja manusia yang tidak tahu bersyukur kepada Allah,\" kata Yusuf.","39":"Yusuf meneruskan dakwahnya dengan menyeru kedua pemuda yang menjadi kawannya dalam penjara itu, \"Wahai kedua penghuni penjara, manakah yang lebih baik, tuhan yang bermacam-macam itu ataukah Allah Yang Maha Esa Yangperkasa?\" Seruan ini adalah yang ikhlas dari seorang kawan yang setia dan jujur kepada kawan-kawannya. Pertanyaan dalam seruan ini adalah merupakan suatu penegasan, bahwa berhentilah menyembah tuhan-tuhan yang bermacam-macam itu dan sembahlah Allah Yang Maha Esa lagi Mahaperkasa. Tuhan-tuhan yang bermacam-macam itu tidak akan dapat menolong mereka dari siksaan di akhirat. Hanya Allah Yang Maha Esa lagi Mahaperkasa saja yang dapat memberikan pertolongan di kala susah dan membantu di kala sempit.","40":"Kelanjutan dari seruan Yusuf adalah semua yang mereka sembah selain Allah itu adalah tuhan-tuhan palsu yang sengaja diberi nama bermacam-macam oleh mereka sendiri, bapak-bapak dan nenek-moyang mereka. Yusuf berkata, \"Kamu yang membuatnya, kamu yang memberinya nama dan kamu pula yang menyembahnya sebagai Tuhan. Padahal dia adalah benda yang lemah yang tidak mempunyai kekuatan apa-apa dan tidak ada pula keterangan dari Allah kepada rasul-rasul-Nya untuk membenarkan tuhan yang kamu buat-buat itu. Bahwa ketentuan yang benar tentang ketuhanan dan pengabdian ialah yang diatur oleh Allah yang telah diwahyukan kepada rasul-rasul-Nya. Allah telah memerintahkan, bahwa janganlah kamu menyembah selain Allah. Kepada-Nyalah kamu berdoa dan minta tolong, kepada-Nyalah kamu sujud bersimpuh. Itulah agama yang lurus. Tetapi kebanyakan manusia belum mengetahuinya.\"","41":"Pada ayat ini barulah diterangkan takwil mimpi kedua pemuda itu oleh Yusuf. Berkatalah Yusuf, \"Hai kedua kawan penghuni penjara, adapun mimpi yang pertama, takwilnya ialah, bahwa engkau segera akan keluar dari penjara ini dan kembali bekerja seperti dulu sebelum masuk penjara, yaitu sebagai tukang siram kebun raja dan akan memberi minum raja dengan khamar. Takwil mimpi kedua, bahwa engkau akan dihukum salib, lalu bangkaimu dan sebagian dari kepalamu akan dimakan burung. Begitulah takwil mimpi yang kamu tanyakan kepada saya sebagai wahyu yang telah diwahyukan kepadaku.\"","42":"Dalam ayat ini diterangkan bahwa Yusuf berpesan kepada pemuda yang keluar dengan takwil yang baik, agar disampaikan kepada raja, bahwa di dalam penjara masih banyak orang yang tidak bersalah dihukum. Mereka dihukum karena tuduhan-tuduhan yang tidak benar agar hal ini menjadi perhatian raja. Sampaikan juga kepada raja apa yang dia lihat dan didengar tentang Yusuf dan seruan untuk menganut agama tauhid dan lain-lain yang terjadi selama ia dalam penjara. Rupanya pemuda itu setelah sampai di luar, lupa menyampaikan pesan-pesan Yusuf kepada raja, sehingga Yusuf terpaksa meringkuk dalam penjara beberapa tahun lamanya.","43":"Dalam ayat ini diterangkan bahwa raja pada suatu ketika bermimpi yang sangat ajaib sekali dan sangat menggelisahkan hatinya. Belum pernah raja bermimpi seperti itu selama hidupnya. Maka dikumpulkannya semua orang cerdik pandainya, juru-juru tenung dan pembesar-pembesar kerajaannya. Lalu dia berkata, \"Aku bermimpi melihat tujuh ekor sapi yang gemuk-gemuk dimakan tujuh ekor sapi yang kurus, aku melihat tujuh butir gandum yang subur dan tujuh butir pula yang kering. Cobalah kamu ceritakan tabir mimpiku itu kalau di antara kamu ada yang mempunyai ilmu tabir mimpi.\"","44":"Tidak seorang pun dapat memecahkan permintaan raja itu. Bermacam-macam pendapat mereka, ada yang mengatakan bahwa itu adalah sebagai mimpi permainan tidur saja dan ada pula yang mengatakan bahwa itu adalah pengaruh angan-angan di waktu tidur yang tidak mempunyai arti apa-apa. Terhadap mimpi yang seperti itu, mereka tidak mempunyai ilmu untuk mencarikan tabirnya.","45":"Raja tidak puas mendengar jawaban mereka dan raja bertambah gelisah nampaknya. Raja ingin mengetahui tabir mimpinya, tetapi tidak tahu kepada siapa akan ditanyakan. Setelah tukang siram kebun raja yang pernah meringkuk dalam penjara bersama Yusuf mendengar kabar ini, dia teringat Yusuf yang sedang meringkuk dalam penjara yang pernah mentawilkan mimpinya sendiri dengan tepat. Dia dengan cepat datang menghadap raja seraya berkata, \"Ya tuanku, di dalam penjara ada seorang pemuda bernama Yusuf. Dia seorang yang mulia, mempunyai pikiran yang dalam, pandangan yang luas, dan dapat pula mentabirkan mimpi dengan tepat. Kalau tuanku utus saya kepadanya, pastilah saya kembali dengan membawa tabir mimpi tuanku itu yang tentunya akan meyakinkan tuanku kebenarannya.\"","46":"Raja gembira mendengar pendapat tukang siram kebunnya itu, lalu mengutusnya untuk menemui Yusuf dalam penjara. Sesampainya di penjara dan bertemu dengan Yusuf, dia berkata, \"Hai Yusuf, saudaraku yang mulia yang dapat dipercaya. Saya datang kepadamu untuk meminta suatu tabir mimpi: yaitu tujuh ekor sapi yang gemuk dimakan oleh tujuh ekor sapi yang kurus dan tujuh bulir gandum yang hampa kering dan ada pula tujuh bulir gandum yang rimbun. Mudah-mudahan saya kembali dengan membawa tabir mimpi itu dari engkau dan supaya dapat diketahui oleh orang banyak yang tentunya mereka akan berterima kasih kepadamu atas segala kelebihan dan kebaikan yang engkau berikan itu.\"","47":"Dengan segala kemurahan hati Yusuf menerangkan tabir mimpi raja itu, seolah-olah Yusuf menyampaikan kepada raja dan pembesar-pembesarnya, katanya, \"Wahai raja dan pembesar-pembesar negara semuanya, kamu akan menghadapi suatu masa tujuh tahun lamanya penuh dengan segala kemakmuran dan keamanan. Ternak berkembang biak, tumbuh-tumbuhan subur, dan semua orang akan merasa senang dan bahagia. Maka galakkanlah rakyat bertanam dalam masa tujuh tahun itu. Hasil dari tanaman itu harus kamu simpan, gandum disimpan dengan tangkai-tangkainya supaya tahan lama. Sebagian kecil kamu keluarkan untuk di makan sekadar keperluan saja.","48":"Sehabis masa yang makmur itu akan datang masa yang penuh kesengsaraan dan penderitaan selama tujuh tahun pula. Pada waktu itu ternak habis musnah, tanaman-tanaman tidak berbuah, udara panas, musim kemarau panjang. Sumber-sumber air menjadi kering dan rakyat menderita kekurangan makanan. Semua simpanan makanan akan habis, kecuali tinggal sedikit untuk kamu jadikan benih.","49":"Kemudian sesudah berlalu masa kesulitan dan kesengsaraan itu, maka datanglah masa hidup makmur, aman dan sentosa. Di masa itu bumi menjadi subur, hujan turun sangat lebatnya, manusia kelihatan beramai-ramai memeras anggur dengan aman dan gembira. Mereka telah duduk bersantai menikmati buah-buahan hasil kebunnya bersama anak-anak dan keluarganya. Itulah tabir mimpi raja itu saya sampaikan kepadamu untuk saudara sampaikan kepada raja dan pembesar-pembesarnya.\"","50":"Dalam ayat ini diterangkan bagaimana tertariknya raja dengan tabir mimpi yang disampaikan oleh utusannya itu, sehingga raja ingin sekali bertemu langsung dengan Yusuf, maka raja memerintahkan kembali menemui Yusuf di penjara lalu berkata, \"Pergilah engkau temui Yusuf di penjara dan bawalah dia kemari, supaya langsung aku mendengarkan per-kataannya dan aku dapat mengukur sampai di mana tinggi ilmunya dan luas pandangannya. Mudah-mudahan ilmunya itu dan pandangan-pandangannya itu berguna bagiku untuk keselamatan bangsa dan negaraku.\" Maka utusan itu pergi menemui Yusuf dan menyampaikan panggilan raja terhadap dirinya, agar ia datang menghadap raja, sebab raja membutuhkan nasihatnya dan akan mengangkatnya ke derajat yang tinggi. Yusuf memenuhi panggilan raja. Tetapi sebelum Yusuf datang menghadap, Yusuf minta kepada utusan raja itu agar dia kembali dan menanyakan kepada raja tentang peristiwa perempuan-perempuan yang sudah memotong jarinya sendiri dengan pisau supaya diketahui dengan jelas duduk perkaranya yang sebenarnya. Sehingga ketika datang menghadap raja, dia sudah dalam keadaan bebas dari tuduhan karena raja lebih mengetahui tentang tipu daya perempuan-perempuan itu.","51":"Setelah utusan kembali menemui raja dan menyampaikan permintaan Yusuf kepadanya, maka dengan segera raja memanggil isteri menteri dan semua perempuan-perempuan yang memotong jarinya itu dan berkata kepada mereka, \"Bagaimana pandanganmu terhadap Yusuf ketika kamu menggodanya dulu? Sebab Yusuf akan aku keluarkan dari penjara.\" Mereka menjawab, \"Bahwa Yusuf seorang pemuda yang suci murni, Maha Sempurna Allah, kami tiada melihat sesuatu yang buruk padanya.\" Istri menteri yang tergila-gila dan terus menggoda Yusuf selama bersama-sama tinggal di rumahnya pun berkata, \"Sudah terlalu lama Yusuf dalam penjara tanpa kesalahan apa-apa. Akulah yang bersalah karena aku tidak dapat menahan hawa nafsuku, aku selalu menggodanya.\" Sekarang jelaslah kebenaran itu, bahwa Yusuf tidak bersalah dan dia termasuk orang-orang yang benar.","52":"Ayat ini menerangkan pengakuan istri al-Aziz yang terus-terang mengatakan bahwa dialah yang bersalah, dialah yang menggoda, tetapi Yusuf tetap enggan dan berpaling, karena takut kepada Tuhannya. Semuanya itu menjadi bukti tentang kejujurannya. Ia tidak mau berdusta terhadap Yusuf walaupun Yusuf dalam penjara. Juga supaya diketahui oleh suaminya, bahwa dia berterus-terang seperti itu menunjukkan bahwa dia bersih, terpelihara dari perbuatan keji, karena kekuatan iman Yusuf. Istrinya tidak mau dituduh pengkhianat, sebab Allah swt tidak akan memberi petunjuk kepada setiap pengkhianatan.","53":"Dalam ayat ini dijelaskan bahwa Yusuf sebagai manusia mengakui bahwa setiap nafsu cenderung dan mudah disuruh untuk berbuat jahat kecuali jika diberi rahmat dan mendapat perlindungan dari Allah. Yusuf selamat dari godaan istri al-Aziz karena limpahan rahmat Allah dan perlindungan-Nya, meskipun sebagai manusia Yusuf juga tertarik pada istri al-Aziz sebagaimana perempuan itu tertarik kepadanya seperti diterangkan pada ayat 24:\n\nDan sungguh, perempuan itu telah berkehendak kepadanya (Yusuf). Dan Yusuf pun berkehendak kepadanya, sekiranya dia tidak melihat tanda (dari) Tuhannya. (Yusuf\u002F12: 24)\n\nTetapi ada pendapat lain yang menyatakan bahwa ayat 53 ini menerang-kan pengakuan istri al-Aziz dengan terharu dan rasa penyesalan yang mendalam bahwa dia tidak dapat membersihkan dirinya dari kesalahan dan ketelanjuran. Dia juga mengakui bahwa memang dia yang hampir meng-khianati suaminya dengan merayu Yusuf ketika suaminya tidak di rumah. Untuk menjaga nama baik diri, suami, dan keluarganya, dia menganjurkan supaya Yusuf dipenjarakan, atau ditimpakan kepadanya siksaan yang pedih. Istri al-Aziz telah melakukan kesalahan ganda, yaitu berdusta dan menuduh orang yang jujur dan bersih serta menjebloskannya ke penjara.\n\nPada akhir ayat ini dijelaskan bahwa Allah Maha Pengampun dan Maha Penyayang.","54":"Dalam suasana yang sangat mengharukan itu, raja memerintahkan supaya Yusuf dijemput dari penjara dan dibawa menghadap ke istana. Di istana, Yusuf menerangkan kepada raja semua pengalamannya semenjak dia tinggal di istana al-Aziz sampai dia masuk penjara dan akhirnya dapat bertemu muka dengan raja. Mendengar penjelasannya, timbullah keyakinan dalam hati raja bahwa Yusuf benar-benar seorang yang jujur dan setia, penuh rasa tanggung jawab, berbudi mulia, berilmu, dan tabah serta kuat imannya. Karena keyakinan itu, raja mengumumkan di hadapan pembesar dan pemimpin negara bahwa dia telah mengangkat Yusuf menjadi orang kepercayaannya. Semua urusan keuangan negara diserahkan sepenuhnya di bawah pimpinan dan tanggung jawabnya, dialah yang berhak sepenuhnya mengendalikan pemerintahan, dan satu-satunya orang yang dapat ber-hubungan langsung dengan raja. Menurut riwayat Ibnu Abbas, \"Ketika utusan raja sampai di penjara dia berkata kepada Yusuf, \"Tanggalkanlah baju penjara yang engkau pakai itu, pakailah baju baru ini, dan marilah bersama saya menghadap raja.\" Semua penghuni penjara berdoa untuknya, demikian pula sebaliknya, Yusuf berdoa pula untuk mereka. Ketika sampai di istana, raja merasa sangat heran karena dilihatnya Yusuf masih muda (waktu itu umurnya lebih kurang 30 tahun). \"Apakah dia yang masih muda ini telah dapat menakbirkan mimpiku dengan tepat, sedangkan semua ahli sihir dan pemuka agama di negeriku tidak ada yang dapat menakbirkannya.\" Lalu raja memerintahkan supaya dia duduk di hadapannya dan bertitah, \"Janganlah engkau merasa takut.\" Lalu dikalungkan ke lehernya kalung emas dan diberi jubah kebesaran dari sutra. Disediakan pula untuknya kuda berpelana yang dihiasi berbagai macam hiasan dan dipukulkan genderang di seluruh pelosok negeri Mesir sebagai pertanda dan pernyataan bahwa Yusuf telah diangkat menjadi khalifah (tangan kanan) raja.\" Demikian riwayat Ibnu Abbas. Kemudian raja bertitah, \"Sejak hari ini engkau mempunyai kedudukan yang tinggi di sisi kami dan kami percayakan kepadamu semua urusan negara.\"","55":"Kemudian raja menceritakan mimpinya kepada Yusuf dan meminta penjelasan tentang tindakan yang paling baik untuk menanggulangi tujuh tahun masa kering. Yusuf meminta kepada raja supaya semua urusan yang berhubungan dengan perekonomian negara diserahkan kepadanya agar dia dapat mengaturnya dengan sebaik-baiknya guna menghindari bahaya kelaparan, walaupun musim kemarau amat panjang. Selanjutnya Yusuf mengetengahkan rencana jangka panjangnya. Dia mengatakan bahwa dalam musim subur yang panjang itu pertanian harus ditingkatkan dan kepada seluruh rakyat diperintahkan supaya jangan ada tanah kosong yang tidak ditanami, sehingga bila datang musim kemarau yang panjang, simpanan bahan makanan yang disiapkan pada masa subur dapat diambil sedikit demi sedikit, sedang batang gandum bisa dimanfaatkan untuk makanan ternak. Raja sangat gembira mendengar pendapat Yusuf dan tambah percaya pada kecerdasan dan kebijaksanaannya. Semua usul Yusuf itu dapat diterimanya. Tidak hanya urusan pertanian, bahkan semua urusan negara telah diserahkan sepenuhnya kepada Yusuf. Dengan demikian, Yusuf telah menjadi penguasa yang sangat disegani, dihormati, dan disayangi di Mesir.","56":"Demikianlah Allah mengatur langkah demi langkah dan tahap demi tahap untuk menempatkan Yusuf pada kedudukan yang tinggi dan terhormat di Mesir dan berkuasa penuh di setiap pelosok negeri itu. Semua ini sesuai dengan sunah Allah yang dimulai dengan mimpi Nabi Yusuf melihat 11 buah bintang, matahari, dan bulan sujud kepadanya yang menyebabkan ayahnya Yakub bertambah sayang kepadanya sehingga saudara-saudaranya bertambah dengki terhadapnya. Kemudian Yusuf dimasukkan ke dalam sumur oleh mereka, lalu diambil oleh kafilah yang hendak pergi ke Mesir, dan dijual kepada penguasa di sana (al-Aziz) dengan harga yang amat murah. Akhirnya Yusuf menetap di istana sebagai salah seorang keluarga yang dipercaya. Kemudian ia digoda oleh istri al-Aziz dan difitnah sehingga dijebloskan ke dalam penjara. Dalam penjara, Yusuf dikaruniai Allah ilmu menakbirkan mimpi salah seorang penghuni penjara dan akhirnya ia menakbirkan mimpi raja. Setelah terbukti bahwa Yusuf tidak bersalah, timbullah kepercayaan raja terhadap dirinya bahwa ia orang yang jujur, setia, tabah dan sabar menghadapi cobaan, berakhlak mulia, berilmu, dan bijaksana, sehingga dia diangkat sebagai penguasa. \n\nSemua kejadian itu merupakan suatu rentetan yang saling terkait dan erat hubungan satu dengan lainnya. Terkesan pada mulanya seakan-akan Yusuf sudah ditakdirkan untuk selalu dirundung malang, tetapi pada akhirnya dia mendapat keberuntungan dan kebahagiaan. Dia sampai di Mesir sebagai seorang budak belian, tetapi kemudian menjadi orang yang paling dihormati dan disegani di sana. Kalau dia bukan seorang manusia yang jujur, ikhlas, dan suka berbuat baik dalam segala tindakannya, tentulah Allah tidak akan mengaruniakan kepadanya nikmat yang sebesar itu. Demikianlah Allah memberi rahmat kepada siapa yang dikehendaki-Nya dan sesungguhnya Allah memberi balasan yang berlipat ganda bagi setiap orang yang berbuat baik.","57":"Di samping balasan di dunia, Allah menyediakan pula di akhirat balasan yang lebih baik, lebih berharga dan lebih membahagiakan bagi orang-orang yang tetap beriman dan selalu bertakwa kepada-Nya yaitu surga Jannatun naim yang terdapat di dalamnya segala macam nikmat dan kesenangan yang belum pernah terlihat oleh mata, belum pernah terdengar oleh telinga, dan belum pernah terlintas dalam hati manusia.","58":"Dalam kitab Perjanjian Lama Kitab Kejadian 42: 2-25 disebutkan bahwa Yusuf mengadakan persiapan dan perbekalan secara besar-besaran untuk menghadapi bahaya kelaparan pada musim kering. Untuk itu, dia membangun gudang-gudang besar untuk menyimpan bahan makanan yang dihasilkan pada musim subur. Ketika datang musim kering, ternyata kekeringan itu bukan hanya terjadi di Mesir saja, tetapi meliputi negeri-negeri tetangga yang berdekatan terutama di negeri Palestina. Terdengarlah di sana berita bahwa pemerintahan Mesir mempunyai simpanan bahan makanan yang banyak sekali, sehingga dapat membantu meringankan penderitaan penduduk negeri-negeri tetangga itu. Penguasa di sana rela melepaskan sebagian dari simpanan itu dengan cara menjual kepada siapa yang sangat memerlukannya. Oleh karena itu, Yakub menyuruh anak-anaknya (saudara-saudara Yusuf) supaya mengumpulkan barang-barang dagangan dan membawanya ke Mesir untuk ditukarkan dengan bahan makanan. \n\nUntuk memenuhi permintaan Yakub, berangkatlah saudara-saudara Yusuf, kecuali Bunyamin karena tidak diizinkan oleh Yakub, untuk membeli bahan makanan yang sangat mereka perlukan. Ketika sampai di sana, mereka langsung menemui Yusuf dengan harapan akan segera dapat membeli bahan makanan, karena urusan ini sepenuhnya berada di tangan Yusuf. Ketika mereka masuk menghadap, Yusuf mengetahui bahwa yang datang itu adalah saudara-saudaranya sendiri, karena rupa dan jenis pakaian mereka masih melekat dalam ingatannya apalagi mereka berjumlah sepuluh orang. Yusuf berkata dalam hatinya, \"Tidak diragukan lagi mereka ini adalah saudara-saudara saya.\" Sebaliknya mereka tidak tahu sama sekali bahwa yang mereka hadapi adalah saudara sendiri. \n\nMereka semua tidak lagi ingat bentuk Yusuf karena sudah lama berpisah, apalagi yang mereka hadapi adalah seorang perdana menteri dengan pakaian kebesaran dan tanda-tanda penghargaan berkilau di bajunya. Tidak mungkin Yusuf menjadi orang yang memiliki jabatan yang amat tinggi itu karena mereka telah membuangnya ke dalam sumur. Kalaupun masih hidup, dia tentu akan menjadi budak belian yang diperas tenaganya oleh tuannya.","59":"Ayat ini menjelaskan bahwa Yusuf mengabulkan permintaan saudara-saudaranya untuk membeli barang-barang yang mereka bawa dan ditukar dengan bahan makanan. Dia kemudian memerintahkan supaya disiapkan untuk mereka 10 pikul bahan makanan dan keperluan-keperluan lain yang dibutuhkan dalam perjalanan, karena mereka berjumlah sepuluh orang, masing-masing berhak mendapat satu pikul. Tetapi mereka men-ceritakan bahwa di kampung mereka ada lagi 2 orang yang sangat memerlukan bahan makanan yaitu seorang saudara dan seorang ayah mereka sendiri.\n\nMereka memohon supaya mereka diberikan 12 pikulan sebab yang sepuluh pikulan itu hanya cukup untuk mereka saja, \"Ayah kami tidak dapat datang kemari karena sudah tua dan lemah, sedangkan saudara kami sengaja kami tinggalkan untuk menjaganya dan menyenangkan hatinya.\" Mendengar keterangan saudara-saudaranya itu, Yusuf berkata, \"Kalau demikian bawalah saudara kalian itu kemari sebagai bukti bagi kami atas kebenaran kalian semua dan kami akan mengabulkan permintaan kalian itu. Kami telah melihat sendiri bahan-bahan makanan yang disediakan untuk kalian semua berjumlah 10 pikulan, karena kami hanya sanggup menyerahkan satu pikulan untuk satu orang. Selain dari itu, selama di sini kalian semua sudah kami perlakukan dengan baik sebagai tamu kami karena begitulah biasanya kami memperlakukan tamu dengan sebaik-baiknya. Sekarang pulanglah kalian semua dan bawalah bahan makanan itu, kemudian datanglah kembali dengan membawa barang dagangan untuk ditukar dengan bahan makanan, tetapi dengan syarat kalian harus membawa saudara kalian sebagai bukti kebenaran dan kejujuran kalian.\"","60":"Selanjutnya Yusuf berkata, \"Jika kalian tidak membawanya, kalian tidak akan mendapat bahan makanan sama sekali karena itu berarti kalian bukan orang-orang yang jujur. Orang-orang yang pembohong dan pendusta tidak akan kami layani dan kami sangat membencinya. Sekali lagi kami tegaskan, kalau kalian tidak membawa saudara kalian itu, jangan diharap kalian akan diberi bahan makanan. Bahkan jangan mencoba mendekat ke negeri kami, apalagi menghadap kepada kami karena tidak ada tempat di sini bagi orang-orang yang tidak jujur.\"","61":"Saudara-saudara Yusuf menjawab, \"Kalau begitu, kami akan pulang dan berusaha dengan sungguh-sungguh agar ayah kami dapat mengizinkan saudara kami itu pergi bersama kami ke Mesir. Kami akan menceritakan kepadanya semua yang telah terjadi dan mengatakan bahwa kami telah disambut dengan baik sekali dan diperlakukan sebagai tamu selama kami berada di Mesir.\"","62":"Kemudian Yusuf memerintahkan kepada petugas-petugasnya yang mengurus bahan makanan agar semua barang-barang yang dibawa mereka dimasukkan kembali ke dalam karung-karung bahan makanan tanpa setahu mereka. Barang-barang itu terdiri dari berbagai macam bahan hasil produksi padang pasir, seperti kulit bulu domba dan lain sebagainya. Dengan mengembalikan barang-barang itu, mereka akan menyadari sepenuhnya betapa baiknya hati penguasa Mesir itu, dan betapa tinggi jasanya terhadap mereka. Mereka telah diperlakukan sebagai tamu selama di Mesir kemudian diberi bahan makanan, sedangkan barang-barang dagangan mereka sendiri dikembalikan, seakan-akan bahan makanan yang sepuluh pikul itu diberikan kepada mereka dengan cuma-cuma sebagai hadiah yang bagi mereka sendiri sangat diperlukan dan tak ternilai harganya. Dengan kesadaran itu, diharapkan timbul tekad yang kuat dalam hati mereka untuk kembali ke Mesir membawa barang-barang dan membawa Bunyamin sekaligus sebagaimana diamanatkan oleh Yusuf.","63":"Dalam ayat ini dijelaskan bahwa tatkala sampai di rumah dan bertemu dengan ayah mereka, saudara-saudara Yusuf memberitahukan semua pengalaman mereka di Mesir dan bagaimana baiknya sambutan penguasa di sana terhadap mereka dengan memperlakukan mereka sebagai tamu. Ketika akan pulang, mereka juga dibekali dengan barang-barang yang diperlukan selama dalam perjalanan. Mereka diberi bahan makanan sebanyak 10 pikulan yang ditukar dengan barang-barang yang mereka bawa karena mereka hanya sepuluh orang.\n\nMereka juga menceritakan kepada Yakub bahwa mereka telah mengatakan kepada penguasa Mesir tentang ayah mereka yang telah tua dan seorang saudara yang tidak dapat datang karena ditugaskan menjaga ayah mereka. Mereka meminta supaya diberi 12 pikulan. Penguasa itu menjawab bahwa kalau benar mereka mempunyai saudara, hendaklah dibawa ke Mesir. Penguasa itu akan memberi mereka lagi bahan makanan sebanyak yang diminta. Mereka diperingatkan bahwa kalau Bunyamin tidak dapat dibawa, mereka tidak boleh datang lagi ke Mesir, dan tidak akan diberi makanan, karena dianggap sebagai pendusta yang tidak layak dipercayai. Oleh sebab itu, mereka memohon kepada Yakub dengan sangat agar mengizinkan Bunyamin ikut bersama mereka. Dengan demikian, mereka akan diberi bahan makanan dan disambut dengan sambutan yang lebih baik karena telah memenuhi janji mereka untuk membawa Bunyamin ke Mesir. Mereka berjanji akan menjaga Bunyamin dengan sebaik-baiknya.","64":"Yakub terkejut mendengar permintaan mereka, sehingga dengan seketika menjawab, \"Apakah aku akan mempercayakan Bunyamin kepada kalian sebagaimana aku telah mempercayakan Yusuf dahulu? Apakah kalian belum puas dengan mencelakakan Yusuf sehingga sekarang kalian kembali ingin mencelakakan Bunyamin? Apakah aku akan percaya begitu saja kepada janji-janji dan jaminan kalian terhadap Bunyamin, padahal dahulu kalian telah membuat janji dan jaminan serupa ketika hendak membawa Yusuf bermain-main ke tempat penggembalaan di padang pasir? Aku tidak percaya lagi kepada ucapan dan janji kalian. Aku akan menggantungkan harapanku kepada Allah agar Dia tetap memelihara Bunyamin karena Dialah sebaik-baik Penjaga dan Penyayang. Kepada-Nyalah aku bertawakal dalam menghadapi segala persoalan. Hanya Dialah yang Maha Pengasih lagi Maha Penyayang, aku bermohon agar Dia selalu melimpahkan rahmat-Nya kepadaku dengan melindungi Bunyamin dan menjaga keselamatannya serta tidak akan menimpakan cobaan kepadaku seperti kehilangan Yusuf, anakku yang tercinta. Sesungguhnya rahmat Allah Mahaluas dan Karunia-Nya Mahabesar.\"","65":"Setelah saudara-saudara Yusuf membuka karung bahan makanan yang mereka bawa dari Mesir, ternyata mereka juga mendapatkan barang-barang mereka masih ada pula di dalamnya. Mereka berkata pada Yakub, \"Wahai ayah kami, barang-barang yang kami bawa ke Mesir ternyata dikembalikan. Ini adalah bukti yang nyata betapa baiknya hati penguasa Mesir itu kepada kita dan betapa pemurahnya sehingga dia tidak mau mengambil barang-barang kita sebagai penukar makanan yang diberikan kepada kita. Dia telah menolong kita dengan ikhlas tanpa mengharapkan balasan. Memang amat besar hutang budi kita. Oleh sebab itu, kita harus membalas jasa dan budi baiknya dengan memenuhi janji kami yaitu akan membawa Bunyamin ke Mesir. Kalau kami kembali ke Mesir membawanya, tentu kita akan mendapat bahan makanan lebih banyak, paling tidak akan bertambah satu pikulan karena kami sudah berjumlah sebelas orang. Bagi penguasa Mesir satu pikulan bahan makanan itu tentu tidak akan memberatkan karena gudang-gudangnya penuh dengan bahan makanan.\"","66":"Mendengar ucapan anak-anaknya itu, Yakub sadar bahwa budi baik penguasa Mesir itu harus dibalas dengan budi baik pula. Tidak ada cara untuk membalasnya kecuali dengan menepati janji anak-anaknya yang akan membawa Bunyamin karena dia dan anak-anaknya tidak mempunyai apa-apa lagi untuk dipersembahkan apalagi penguasa Mesir itu telah menolak menerima barang tukaran dan mengembalikan semuanya. Dengan perasaan yang berat, Yakub berkata kepada anak-anaknya bahwa kalau mereka harus membawa Bunyamin ke Mesir, maka ia tidak akan mengizinkan kecuali dengan janji yang dikuatkan dengan sumpah bahwa mereka benar-benar akan menjaga keselamatan Bunyamin dan membawanya kembali pulang. Mereka juga diminta untuk bersedia mengorbankan jiwa raga bila terjadi hal-hal yang membahayakan atau mengancam jiwanya. Anak-anak Yakub bersedia bersumpah untuk memenuhi syarat yang dikemukakan ayah mereka. Lalu mereka bersumpah dengan menyebut nama Allah bahwa mereka akan menjaga keselamatan Bunyamin, membelanya mati-matian bila terancam bahaya, dan akan membawanya pulang kembali. Setelah mendengar sumpah anak-anaknya itu, barulah hati Yakub merasa lega dan dia berkata, \"Allah menjadi saksi atas semua ucapan dan janjimu itu. Dialah Yang Mengawasi segala perbuatan dan tindak-tandukmu dan kepada-Nyalah aku serahkan keselamatan anakku.\"","67":"Pada ayat ini dijelaskan bahwa Nabi Yakub berkata kepada anak-anaknya agar ketika sampai di istana raja Mesir, mereka tidak masuk bersama-sama dari satu pintu gerbang, tetapi masuk dari pintu-pintu gerbang yang lain, supaya terhindar dari penglihatan mata orang yang hasad atau mengalami hal-hal yang tidak diinginkan. Di samping itu agar Bunyamin sempat bertemu dengan Yusuf secara terpisah dari saudara-saudaranya yang lain.\n\nNabi Yakub menasihatkan pula bahwa walaupun mereka sudah berusaha menghindari berbagai kemungkinan yang membahayakan, namun beliau tidak dapat mencegah ketentuan dari Allah, sebab keputusan menetapkan sesuatu hanya berada di tangan-Nya. Semua pekerjaan harus dilaksanakan sesuai dengan kemampuan dan disertai keyakinan bahwa ketentuan dari Allah pasti terjadi, dan tidak seorang pun yang dapat menghalang-halanginya. Oleh karena itu, hanya kepada-Nyalah semua orang bertawakal dan berserah diri.","68":"Tatkala putra-putra Nabi Yakub itu masuk ke istana Yusuf di Mesir sesuai dengan yang diperintahkannya, yaitu masuk dari pintu gerbang yang berlainan, cara yang mereka lakukan itu tidak dapat melepaskan mereka sedikit pun dari ketentuan Allah. Ini hanya keinginan Nabi Yakub yang harus dilaksanakan agar Yusuf dapat bertemu dengan Bunyamin empat mata, karena keduanya akan membuat perencanaan dan tindakan yang bijak-sana. Ini menunjukkan bahwa Nabi Yakub telah diberi ilmu pengetahuan dengan wahyu Allah swt, namun kebanyakan manusia tidak mengetahui, termasuk anak-anaknya sendiri.","69":"Ketika anak-anak Yakub masuk ke dalam ruangan khusus, Yusuf langsung mengenali adiknya, Bunyamin. Yusuf berusaha untuk bertemu empat mata dengannya seraya berkata, \"Jangan sedih dan gundah. Saya ini adalah saudara kandungmu, tapi hal ini jangan kamu ceritakan kepada saudara-saudara yang lain.\"\n\nDalam sebuah riwayat dikatakan bahwa tatkala saudara-saudara Yusuf masuk ke tempatnya, mereka memperkenalkan Bunyamin seraya berkata, \"Inilah saudara kami Bunyamin, yang diminta datang bersama-sama dengan kami, sekarang kami memperkenalkannya kepada Baginda.\" Yusuf menjawab, \"Terima kasih banyak, dan untuk kebaikan ini niscaya kami akan menyediakan balasannya.\" Lalu Yusuf menyediakan hidangan makanan untuk mereka yang semuanya berjumlah sebelas orang. Tiap-tiap meja untuk dua orang, sehingga semuanya sudah duduk berhadap-hadapan pada lima meja dalam lima buah kamar yang tertutup. Hanya tinggal Bunyamin sendirian tidak mempunyai pasangan. Yusuf berkata kepada tamu-tamunya, \"Kamu yang sepuluh orang, masing-masing berdua masuklah ke dalam kamar. Karena yang seorang ini, yaitu Bunyamin tidak mempunyai kawan, maka baiklah saya yang menemaninya.\" Setelah Yusuf dan Bunyamin berdua dalam sebuah kamar, maka Yusuf merangkulnya dengan penuh kemesraan, dan berkata, \"Apakah kamu suka menerima aku sebagai saudara-mu, ganti dari saudaramu yang hilang itu?\" Bunyamin menjawab, \"Siapa yang akan menolak mendapatkan saudara seperti engkau yang mulia ini? Namun engkau tidak dilahirkan dari bapakku Yakub dan ibuku Rahil.\" Karena tidak tahan mendengar ucapan itu, lalu Yusuf menangis dan merangkul Bunyamin seraya berkata, \"Akulah Yusuf, saudaramu yang dikatakan hilang itu.\" Lalu Yusuf menasihati saudaranya, supaya jangan bersedih atas apa yang telah dikerjakan oleh saudara-saudaranya terhadap-nya. Yusuf memberitahukan pula kepada Bunyamin rencananya terhadap saudara-saudaranya, untuk menguji mereka, apakah akhlaknya masih seperti dahulu atau sudah ada perubahan. Maksudnya supaya Bunyamin jangan terkejut, bila nanti terjadi hal-hal yang dilakukan Yusuf yang terasa janggal baginya.","70":"Maka tatkala bahan makanan itu sedang dipersiapkan, diam-diam Yusuf memasukkan piala (tempat minum yang dapat juga digunakan untuk menakar) raja ke dalam karung Bunyamin. Setelah kafilah itu bersiap-siap untuk berangkat meninggalkan Mesir, seorang utusan datang menyusul kafilah itu seraya berseru dengan suara yang keras, \"Hai kafilah, tunggu dulu sesungguhnya kamu adalah para pencuri.\"","71":"Saudara-saudara Yusuf segera menghentikan perjalanan mereka dan bertanya barang apakah yang hilang dari kerajaan, sehingga ia datang menyusul dan menuduh mereka sebagai pencuri.","72":"Penyeru itu berkata bahwa raja kehilangan piala yang ada cap kerajaan padanya. Barang siapa yang dapat mengembalikan piala itu akan memperoleh hadiah yaitu bahan makanan seberat beban unta. Penyeru itu menjelaskan pula bahwa dia menjamin akan tetap memberikan hadiah itu pada siapa saja yang bisa mengembalikannya.","73":"Saudara-saudara Yusuf berkata dengan maksud membersihkan diri dari tuduhan itu, \"Demi Allah kamu telah mengetahui bahwa kami datang ke Mesir ini, baik pertama maupun yang kedua kalinya, bukan untuk membuat kerusakan di negeri Mesir dengan mencuri ataupun melakukan kejahatan lainnya, dan kami yakin bahwa kami bukanlah pencuri.\"","74":"Penyeru itu bertanya, \"Tetapi apa akibatnya jika kamu berdusta? Dan ternyata piala raja itu disembunyikan di karung-karungmu.\"","75":"Mereka menjawab, \"Balasannya ialah siapa saja yang ditemukan piala itu di dalam karungnya, maka dialah pencurinya dan harus bersedia menerima akibatnya.\" Syariat yang berlaku menurut agama yang dibawa Nabi Yakub ialah si pencuri dijadikan hamba sahaya oleh orang yang kecurian selama satu tahun. Demikianlah Allah membalas kejahatan orang-orang yang zalim.","76":"Setelah kafilah kembali lagi ke Mesir dan menghadap Yusuf, ia mulai memeriksa karung-karung mereka semuanya dan yang terakhir diperiksa adalah karung Bunyamin. Sengaja beliau berbuat demikian untuk menutupi taktiknya. Kemudian Yusuf menemukan piala yang hilang itu dari karung Bunyamin. Dengan cara demikian Allah mengatur taktik Yusuf untuk mencapai maksudnya. Yusuf sama sekali tidak bermaksud menghu-kum saudaranya menurut undang-undang kerajaan kecuali jika Allah menghendakinya. Beliau sengaja membuat taktik ini untuk sekedar menguji akhlak saudara-saudaranya dan bukan untuk menyakiti Bunyamin, karena ia terlebih dahulu telah diberitahu tentang rencana tersebut. Allah meninggikan derajat orang-orang yang dikehendaki-Nya, baik berupa ilmu maupun keimanan dan memperlihatkan pula jalan kebenaran untuk mencapai maksudnya, seperti Allah telah mengangkat derajat Yusuf di atas saudara-saudaranya. Di atas setiap orang yang berpengetahuan ada lagi yang lebih mengetahui. Hanya Allah yang Maha Mengetahui.","77":"Dalam ayat ini, saudara-saudara Yusuf mengatakan bahwa jika Bunyamin ternyata mencuri, itu karena saudaranya Yusuf juga telah mencuri. Tuduhan mereka bahwa Yusuf pernah mencuri menunjukkan bahwa sifat dengki masih tertanam dalam hati mereka. Hal itu sempat menimbulkan perasaan jengkel dalam diri Yusuf. Akan tetapi, dengan sabar Yusuf mampu menyembunyikan kejengkelan itu dan tidak menampakkan-nya kepada mereka.\n\nBahwa Yusuf dikatakan pernah mencuri pada waktu ia masih kecil, sebenarnya tidaklah benar. Peristiwa yang sebenarnya bukanlah kasus pencurian, melainkan kasus yang direkayasa agar Yusuf kecil tetap tinggal bersama bibinya, tidak dibawa pulang oleh ayahnya, yaitu Nabi Yakub a.s. Kasusnya adalah seperti yang diriwayatkan oleh Mujahid r.a. yang menerangkan bahwa Yusuf ketika kecil dipelihara oleh bibinya yang sangat sayang kepadanya. Bibinya menyimpan ikat pinggang Nabi Ishak a.s. yang secara turun-temurun diwariskan kepada anaknya yang tertua. Nabi Yakub sering datang kepada saudara perempuannya, untuk mengambil Yusuf. Karena bibinya amat sayang kepadanya, beliau mempertahankan Yusuf supaya tetap di bawah asuhannya. Akhirnya, bibinya tersebut membuat suatu taktik dengan mengikatkan ikat pinggang pusaka tadi ke pinggang Yusuf dan ditutup oleh bajunya sehingga tidak kelihatan. Lalu, bibinya mengumumkan bahwa ikat pinggang pusaka itu hilang dicuri orang. Kemudian, semua anggota keluarga diperiksa. Ternyata ikat pinggang kedapatan dipakai oleh Yusuf. Menurut syariat Nabi Yakub a.s. waktu itu, Yusuf harus diserahkan kepada bibinya sebagai hamba sahaya selama satu tahun. Peristiwa inilah, antara lain, yang dituduhkan oleh saudara-saudaranya bahwa ia pernah mencuri.","78":"Pada ayat ini dijelaskan tentang apa yang dikatakan oleh saudara-saudara Yusuf kepada al-Aziz, bahwa Bunyamin yang ditetapkan sebagai pencuri itu mempunyai ayah yang telah lanjut usia, dan tidak bisa berpisah dengannya. Bunyamin adalah pengganti saudaranya yang hilang. Oleh karena itu, mereka mengharap kepada al-Aziz agar sudi mengambil salah seorang dari mereka sebagai jaminan karena Bunyamin lebih dicintai ayahnya. Mereka juga telah berjanji untuk menjaga keselamatan Bunyamin selama dalam perjalanan. Di samping itu, mereka pun memuji al-Aziz bahwa beliau adalah orang yang gemar berbuat baik. Pujian serupa itu tentu saja dengan maksud agar Bunyamin dibebaskan dari penahanan karena tuduhan pencurian. Mereka sebagai tamu merasa telah mendapatkan pelayanan dengan sebaik-baiknya, dan alangkah lebih sempurna jika kebaikan itu ditambah lagi dengan memenuhi permintaan mereka untuk membiarkan Bunyamin kembali kepada ayahnya yang selama ini dilanda kesedihan karena kehilangan Yusuf.","79":"Lalu Yusuf berkata kepada saudara-saudaranya bahwa dia melakukan tindakan salah jika melepaskan Bunyamin yang telah terbukti di dalam karungnya ditemukan barang yang hilang itu. Ia berlindung kepada Allah bahwa ia tak mungkin menangkap seseorang kecuali karena telah terbukti mencuri. Seandainya ia menerima usul saudara-saudaranya, berarti ia bertindak tidak adil karena telah menyalahi undang-undang atau peraturan yang berlaku di wilayah kerajaannya.","80":"Allah mengabarkan bahwa tatkala saudara-saudara Yusuf berputus asa karena Yusuf menolak salah seorang dari mereka untuk menggantikan Bunyamin, mereka lalu berkumpul untuk merundingkan secara rahasia apa yang akan mereka kerjakan selanjutnya. Saudaranya yang tertua yang bernama Yahuda berkata, \"Bukankah kamu mengetahui bahwa ayahmu, Yakub, telah mengambil janji yang berat dari kita dengan nama Allah bahwa kita akan sungguh-sungguh menjaga keselamatan Bunyamin dan sanggup mengembalikannya kepada ayah, kecuali jika kita menghadapi bahaya yang besar yang tidak dapat dihindari. Penahanan Bunyamin ini akan membuat ayah kita bertambah sedih, terlebih bila diingat bahwa kita dahulu telah menyia-nyiakan Yusuf.\" \"Oleh sebab itu,\" kata Yahuda lebih lanjut, \"aku tidak akan meninggalkan Mesir sampai ayahku mengizinkanku untuk kembali, atau sampai Allah memberi keputusan lain kepadaku karena Allahlah yang Maha Mengetahui perkara-perkara yang gaib dan Dia adalah Hakim yang paling baik.\"","81":"Lalu Yahuda memerintahkan kepada saudara-saudaranya yang lain supaya pulang menghadap ayah mereka dan melaporkan segala kejadian yang dialaminya di Mesir untuk menghindarkan tuduhan-tuduhan yang buruk. Yahuda berkata, \"Kembalilah kepada ayahmu dan sampaikanlah kepadanya bahwa anaknya, Bunyamin, telah mencuri piala raja dan akibatnya dijadikan hamba sahaya selama setahun sesuai dengan syariat yang berlaku.\" Ia juga menyuruh saudara-saudaranya untuk mengatakan kepada ayah mereka, Nabi Yakub, bahwa mereka hanya dapat menyaksikan apa yang diketahui. Mereka melihat sendiri bahwa piala raja itu dikeluarkan dari karung makanan Bunyamin. Mereka sama sekali tidak dapat mengetahui perkara yang gaib. Seandainya mereka tahu bahwa Bunyamin akan mencuri, tentu mereka tidak akan berjanji pada ayah mereka.","82":"Selanjutnya dijelaskan bahwa Yahuda juga menyarankan agar saudara-saudaranya mengatakan kepada ayah mereka untuk menanyakan hal ini kepada penduduk negeri tempat mereka berada di Mesir untuk membeli bahan makanan, karena soal pencurian itu sudah tersebar beritanya di kalangan mereka. Juga dapat ditanyakan kepada kafilah yang datang bersama-sama dengan mereka, dan sesungguhnya mereka adalah orang-orang yang benar dan selalu melaporkan apa yang benar-benar terjadi.","83":"Setelah berhadapan dengan putra-putranya yang memberi laporan seperti yang diamanatkan oleh Yahuda, Nabi Yakub berkata, \"Hanya dirimu sendirilah yang memandang baik perbuatan yang buruk itu, dan mengapa kamu mengatakan bahwa yang mencuri harus dijadikan hamba sahaya selama satu tahun, padahal ketentuan itu hanya ada pada syariat kita dan tidak ada dalam perundang-undangan mereka. Maka kesabaran yang baik itulah kesabaranku yang tidak diliputi oleh kejengkelan dan kemarahan. Mudah-mudahan Allah mendatangkan mereka semuanya kepadaku (Yusuf, Bunyamin, dan Yahuda), karena sesungguhnya Dialah Tuhan Yang Maha Mengetahui dan Mahabijaksana.\"","84":"Karena tidak senang menerima laporan yang disampaikan para putranya, maka Nabi Yakub berpaling dari mereka seraya berkata dengan penuh kesedihan, \"Aduhai dukacitaku terhadap Yusuf, karena aku tadinya menunggu-nunggu berita yang menggembirakan dari Mesir, tetapi kenyata-annya justru berita yang menyedihkan yang kuterima.\" Karena kesedihan yang terus-menerus dialaminya dan sering menangis, maka kedua mata Yakub menjadi putih, sehingga keadaannya seperti orang buta. Akan tetapi, beliau tetap masih bisa menahan amarah terhadap anak-anaknya.\n\nMenurut dunia ilmu pengetahuan, ketika seseorang menderita stres, tubuhnya bereaksi dan membangkitkan tanda bahaya, sehingga memicu terjadinya beragam reaksi biokimia di dalam tubuh: Kadar adrenalin dalam aliran darah meningkat; penggunaan energi dan reaksi tubuh mencapai titik tertinggi; gula, kolesterol dan asam-asam lemak tersalurkan ke dalam aliran darah; tekanan darah meningkat dan denyutnya mengalami percepatan. Ketika glukosa tersalurkan ke otak, kadar kolesterol naik, dan semua ini memunculkan masalah bagi tubuh. Mungkin hal ini pula yang dialami oleh Nabi Yaqub as ketika kehilangan anak yang disayanginya Nabi Yusuf a.s. \n\nStres yang parah, mampu mempengaruhi bahkan mengubah fungsi-fungsi normal organ tubuh. Hal ini dapat berakibat sangat buruk. Akibat stres, kadar adrenalin dan kortisol di dalam tubuh meningkat di atas batas normal. Peningkatan kadar kortisol dalam rentang waktu lama berujung pada gangguan organ tubuh antara lain dapat terjadi gangguan pada pankreas. Akibatnya timbul penyakit diabetes atau kencing manis yakni penyakit rusaknya sel-sel beta pankreas yang menghasilkan insulin, berakibat pada kadar gula darah tubuh tidak terkontrol. Dalam banyak kasus penyakit diabetes ini dapat menimbulkan gejala katarak yakni kekeruhan pada lensa mata yang mengakibatkan pandangan kabur. Apabila lensa menjadi keruh, maka cahaya yang masuk ke dalam mata dapat terpencar dan mengakibatkan pandangan kabur. \n\nPara ahli kedokteran (mata) sepakat bahwa penanganan yang kurang atau tidak terkontrol dengan baik dapat menyebabkan kebutaan pada penderita penyakit ini. Gejala utama katarak adalah penglihatan kabur, daya penglihatan berkurang secara progresif, adanya selaput tipis yang menghalangi pandangan, sangat silau jika berada di bawah cahaya yang terang. Pada perkembangan selanjutnya penglihatan semakin memburuk, pupil akan tampak berwarna putih (ada putih-putih pada hitam mata)\n\nDewasa ini penyakit \"mata putih\" (katarak) ini dapat disembuhkan terutama dengan semakin majunya teknologi kedokteran saat ini atau karena kadar gula dalam darah dapat dikontrol dengan baik. \n\nBerbeda tentunya dengan Nabi Yaqub a.s. yang kesembuhannya berlangsung secara cepat, mungkin karena mukjizat bagi seorang Nabi atau bisa juga sebagai buah dari \"kesabarannya\". Maha Suci Allah yang Maha Mengetahui dan Maha Penyembuh.","85":"Pada ayat ini, diterangkan bahwa ketika mendengar keluhan dan kesedihan ayahnya yang mendalam, anak-anak Yakub yang baru kembali dari Mesir berkata kepadanya, yang diawali dengan sumpah kepada Allah sebagai tanda rasa kasih dan sayang mereka, agar dia tidak selalu mengingat Yusuf karena peristiwa Yusuf itu sudah lama berlalu. Kalau selalu mengingat Yusuf, ia akan terus mengalami kesedihan yang mendalam, sehingga dikhawatirkan akan mendapat penyakit yang akan membinasakan atau meninggal dunia karenanya.","86":"Pada ayat ini, Allah menceritakan jawaban Nabi Yakub kepada anak-anaknya. Ia berkata, \"Wahai anak-anakku janganlah kalian mencela dan mencercaku. Aku tidak pernah mengadu kepadamu sekalian, begitu juga kepada manusia yang lain tentang kesedihan dan kesusahanku. Aku mengadu dan menyampaikan keluhan atas musibah yang menimpaku hanya kepada Allah swt. Kepada-Nya aku meminta perlindungan dan memohon untuk menghilangkan kesusahan dan kesedihan itu. Biarkanlah aku bermunajat dengan Tuhanku. Aku mengetahui dari wahyu yang diberikan Allah kepadaku bahwa Yusuf itu masih hidup dan tetap memperoleh rezeki. Ia adalah manusia pilihan Allah. Dia akan menyempurnakan nikmat-Nya kepada Yusuf dan keluarga Yakub. Semua itu tidak kalian ketahui, bahkan mengira bahwa Yusuf itu telah mati.\"","87":"Selanjutnya Yakub berkata kepada anak-anaknya bahwa ia tahu bahkan yakin mimpi Yusuf dulu itu benar dan ia akan sujud menghormatinya. Kalau mereka berpendapat lain, Yakub mengingatkan anak-anaknya bahwa satu saat Allah swt akan memperlihatkan kebenaran pendapatnya itu. Untuk itu, ia meminta anak-anaknya untuk kembali ke Mesir menyelidiki sampai mendapat berita yang pasti tentang Yusuf dan adiknya Bunyamin serta tidak berputus asa karena Allah telah berfirman:\n\nTidak ada yang berputus asa dari rahmat Tuhannya, kecuali orang yang sesat. (al-hijr\u002F15:56)\n\nOrang-orang mukmin tidak akan berputus asa karena musibah yang menimpanya, dan tidak goyah imannya karena bahaya yang melanda. Mereka bersabar dan tabah menghadapi segala kesulitan yang dialaminya. Ia dengan rela penuh ikhlas menerima takdir dari Allah swt dengan keyakinan bahwa suatu saat nanti Allah akan menghilangkan semua kesulitan itu, sebagaimana firman-Nya:\n\nSesungguhnya Allah membela orang-orang yang telah beriman. (al-hajj\u002F22: 38)\n\nKesimpulan","88":"Dalam ayat ini diterangkan bahwa setelah saudara-saudara Yusuf menerima anjuran dari ayahnya untuk kembali ke Mesir, mereka lalu berangkat. Sesampainya di Mesir, mereka masuk ke istana Yusuf dengan segala kerendahan diri. Mereka ingin mengetahui kebenaran keyakinan ayahnya yang pernah mengatakan bahwa al-Aziz itu adalah Yusuf. Mereka berkata kepada al-Aziz bahwa mereka ditimpa musibah kelaparan sehingga mereka menjadi kurus dan lemah karena kekurangan makanan, sedangkan keluarga mereka tidak sedikit. Mereka mengadukan halnya itu kepada al-Aziz, dengan maksud untuk mengetahui keadaan Yusuf dan Bunyamin. Mereka juga mengemukakan bahwa mereka datang membawa dagangan yang jelek dan rendah mutunya, sehingga mungkin tidak ada pedagang yang mau menawarnya. Mereka berharap agar al-Aziz mau menolong mereka dengan menyempurnakan takaran dagangannya tanpa mempertimbangkan kejelekannya. Kekurangan yang harus mereka bayar kepadanya agar disedekahkan saja kepada mereka. \n\nAllah membalas budi baik seseorang yang suka bersedekah dan Dia pulalah yang akan mengganti segala apa yang telah disedekahkan dan diinfakkan itu, sebagaimana firman-Nya:\n\nDan apa saja yang kamu infakkan, Allah akan menggantinya, dan Dialah pemberi rezeki yang terbaik. (Saba\u002F34: 39)","89":"Setelah anak-anak Yakub mengemukakan alasan-alasan mereka kembali ke Mesir, Yusuf menjawabnya dengan mengingatkan mereka atas kejahatan yang telah mereka lakukan terhadap Yusuf dan Bunyamin, adiknya. Yusuf juga mengatakan bahwa apa yang mereka perbuat kepada diri dan adiknya adalah perbuatan yang sangat jelek atau buruk. Mungkin karena kejahilan mereka pada waktu itu, mereka tidak mengetahui dan merasakan buruknya perbuatan itu walaupun bertentangan dengan syariat agama serta melanggar kewajiban berbuat baik kepada kedua orang tua dan perintah bergaul dengan baik terhadap karib kerabat. Ini adalah realisasi dari apa yang telah Allah wahyukan kepada Yusuf ketika ia dilemparkan ke dalam sumur oleh saudara-saudaranya sebagaimana firman Allah swt:\n\nKami wahyukan kepadanya, \"Engkau kelak pasti akan menceritakan perbuatan ini kepada mereka, sedang mereka tidak menyadari. (Yusuf\u002F12: 15)","90":"Setelah mendengar ucapan Yusuf, timbullah di hati mereka kesadaran bahwa yang di hadapan mereka itu adalah Yusuf. Untuk menguatkan dugaannya, mereka mengajukan pertanyaan dengan penuh rasa heran, \"Apakah kamu ini benar-benar Yusuf?\" Dua tahun lebih mereka bolak-balik bertemu Yusuf tetapi tidak mengenalinya. Sebaliknya, Yusuf mengenali mereka, namun ia sembunyikan dalam hati. Pertanyaan mereka dijawab oleh Yusuf dengan mengatakan, \"Aku ini adalah Yusuf yang telah kalian aniaya dengan penganiayaan yang cukup berat. Allah swt telah menolongku dan memuliakanku sampai memberiku pangkat yang tinggi. Aku tidak berdaya sama sekali ketika kalian berencana untuk membunuh dan membuangku ke dasar sumur yang dalam. Dan ini adikku, Bunyamin, yang telah kalian pisahkan dari aku, yang kemudian Allah swt memberikan karunia kepadanya sebagaimana kalian lihat. Allah swt melimpahkan karunia-Nya kepada kami berdua, menyatukan kami kembali sesudah berpisah sekian lama, memuliakan kami sesudah dihina, dan menyelamatkan kami dari segala ujian dan cobaan. \n\nAgama telah menetapkan dan pengalaman telah membuktikan bahwa orang yang bertakwa kepada Allah swt dengan mengerjakan segala perintah-Nya dan menjauhi segala larangan-Nya serta selalu sabar menghadapi ujian dan cobaan yang menimpanya serta tipu daya setan dan hawa nafsu yang selalu menggodanya, Allah tidak akan menyia-nyiakan balasan amalnya itu di dunia, lebih-lebih di akhirat. Di dunia diberi jalan keluar dari kesulitan yang dihadapinya serta diberi rezeki dari arah yang tidak diduga sebelumnya, dan di akhirat diberi pahala tanpa ada perhitungan. Firman Allah swt:\n\nBarang siapa yang bertakwa kepada Allah, niscaya Dia akan membukakan jalan keluar baginya. Dan Dia memberinya rezeki dari arah yang tidak disangka-sangkanya. (ath-thalaq\u002F65: 2-3)\n\nDan firman-Nya:\n\nHanya orang-orang yang bersabarlah yang disempurnakan pahalanya tanpa batas. (az-Zumar\u002F39: 10)","91":"Setelah Yusuf memberikan pengakuan siapa dirinya sebenarnya dan saudara-saudaranya telah meyakini bahwa al-Aziz itu adalah Yusuf, mereka secara jujur mengakui kemuliaan yang diberikan Allah swt kepada Yusuf tentang kelebihan ilmunya, dan ketinggian akhlak yang dimilikinya. Mereka dengan terus terang juga mengakui kesalahan yang telah mereka perbuat kepada Yusuf dan Bunyamin dengan sengaja dan direncanakan sebelumnya. Suatu kesalahan yang tidak diampuni oleh Allah swt kecuali dengan taubat nashuha (tobat yang sebenar-benarnya), dan tidak dapat dimaafkan kecuali dengan hati lapang dan budi luhur dari yang bersangkutan.","92":"Setelah mendengar pengakuan bersalah dari saudara-saudaranya secara terus terang, Yusuf sebagai seorang nabi, manusia pilihan yang mempunyai budi pekerti yang mulia, kesopanan yang tinggi, dengan tandas dan gamblang memaafkan segala kesalahan yang telah diperbuat kepadanya dan Bunyamin. Dia mendoakan semoga Allah swt mengampuni dosa saudara-saudaranya dengan syarat mereka mau bertobat dengan segala keikhlasan dan kerendahan hati, menyesali perbuatan buruk itu, bertekad tidak akan mengulanginya lagi, dan senantiasa berbuat baik, karena Allah adalah Maha Penyayang.\n\nBudi pekerti yang mulia dan akhlak yang tinggi sebagaimana yang dimiliki Nabi Yusuf a.s. itu juga pernah dicontohkan oleh Nabi Muhammad saw, yaitu ketika beliau dan bala tentaranya menaklukkan kota Mekah. Setelah Nabi Muhammad saw bertawaf dan kemudian salat sunat dua rakaat, beliau berdiri di samping Kabah menghadap para tawanan perang lalu berkata:\n\nApakah perkiraanmu terhadap apa yang akan saya perbuat terhadap kalian? Para tawanan menjawab, \"Kami hanya menyangka yang baik saja. Anda adalah saudara yang mulia dan anak saudara yang mulia.\" Nabi saw berkata, \"Saya akan mengatakan sebagaimana yang telah dikatakan oleh saudaraku Yusuf, \"Tidak ada celaan, cercaan, dan kekerasan sekarang ini.\" Maka keluarlah para tawanan itu (meninggalkan tempat) seakan-akan mereka dibangkitkan dari kubur. (Riwayat al-Bukhari dari Abu Hurairah)","93":"Setelah Yusuf menjelaskan siapa dirinya kepada saudara-saudaranya, dia lalu menanyakan kepada mereka tentang keadaan ayahnya. Mereka menjawab bahwa beliau tidak bisa melihat lagi. Seketika itu Yusuf memberikan baju gamisnya kepada saudara-saudaranya agar dibawa pulang ke negerinya. Sesampainya di rumah, baju gamis itu agar segera disapukan ke wajah beliau, niscaya dia akan melihat kembali. Yusuf berkata demikian berdasarkan wahyu. Dia juga mengetahui bahwa penyebab tertutupnya penglihatan ayahnya ialah terlalu banyak menangis. Apabila ayahnya mengetahui bahwa baju gamis itu adalah miliknya, yang menandakan bahwa ia masih hidup dan selamat dari aniaya dan cobaan yang dialaminya, tentu ayahnya akan senang dan timbul dalam hatinya perasaan gembira, dan akan melihat kembali seperti sediakala. Hal tersebut merupakan mukjizat bagi Nabi Yusuf. Ia juga meminta kepada saudaranya supaya mendatangkan segenap keluarganya ke Mesir, baik laki-laki, perempuan, maupun anak-anak, yang menurut suatu riwayat, semuanya berjumlah tujuh puluh orang.","94":"Tatkala barisan unta putra-putra Yakub keluar dari perbatasan negeri Mesir menuju tanah Syam, berkatalah Yakub kepada cucu-cucunya dan para kerabat yang berada di sampingnya pada waktu itu, \"Aku telah mencium bau Yusuf yang wangi, seperti baunya yang pernah aku kenal di waktu kecilnya. Andaikata kalian tidak berburuk sangka kepadaku, menyangka bahwa aku lemah akal, rusak pikiran karena terlalu tua, tentunya kalian akan membenarkan ucapanku ini bahwa aku benar-benar telah mencium bau Yusuf, dan dia masih hidup. Tidak lama lagi aku akan berjumpa dengannya dan merasa senang melihatnya.\" Ini adalah suatu mukjizat bagi Yakub yang dapat mencium bau Yusuf dari tempat yang amat jauh, kira-kira delapan hari perjalanan unta waktu itu.","95":"Dalam ayat ini dijelaskan bahwa tidak seorang pun di antara keluarga Yakub yang membenarkan ucapannya, bahkan mereka mengecamnya dengan ucapan yang tidak sepantasnya diucapkan kepada orang tua. Menurut mereka, Yakub keliru karena merasa akan segera berjumpa dengan Yusuf, padahal dalam anggapan mereka Yusuf telah tewas diterkam serigala. Anggapan Yakub ini, menurut mereka, sebagai tanda-tanda kesesatannya.","96":"Pada ayat ini, Allah swt menerangkan bahwa setelah pembawa kabar gembira itu sampai ke tempat ayahnya sesuai dengan anjuran Yusuf, Yahuda tampil ke depan membawa baju gamis Yusuf dan mengusapkannya ke wajah Yakub. Mata Yakub dengan seketika kembali melihat seperti sediakala. Yakub berkata kepada putra-putranya, \"Bukankah pernah kukatakan kepadamu ketika aku menyuruhmu ke Mesir mencari berita tentang Yusuf dan saudaranya, bahwa sesungguhnya aku tahu dengan perantaraan wahyu dari Allah swt, bukan khayalan dan angan-angan bahwa Yusuf itu masih hidup sedang kamu tidak mengetahuinya.\" Penyerahan baju Yusuf kepada ayahnya oleh Yahuda sebagai bukti bahwa Yusuf masih hidup mengingatkan Yakub pada penyerahan baju Yusuf yang berlumuran darah oleh Yahuda sebagai bukti bahwa Yusuf telah diterkam serigala.","97":"Setelah saudara-saudara Yusuf melihat bukti-bukti dan kenyataan yang tidak dapat dipungkiri, mereka menjadi sadar dan dengan jujur mengakui kesalahannya. Mereka juga meminta kepada ayahnya agar mau memohonkan ampun kepada Allah swt atas kedurhakaan yang telah mereka perbuat kepada ayahnya dan kezaliman yang dilakukan terhadap Yusuf. Pengakuan saudara-saudara Yusuf tentang kesalahan dan dosa yang telah diperbuat itu adalah pengakuan yang kedua kalinya. Sebelum itu, mereka pernah mengakui dosa dan kesalahannya di hadapan Yusuf, hanya pada waktu itu Yusuf langsung memohonkan ampunan dari Allah swt tanpa permintaan dari mereka.","98":"Setelah Yakub melihat kesadaran dan pengakuan anak-anaknya atas kesalahan yang mereka perbuat dengan terus terang serta permintaan mereka supaya ayahnya memohonkan ampunan kepada Allah swt, beliau menjawab, \"Aku akan memohonkan ampun bagimu kepada Allah swt. Semoga Allah swt mengampunimu semua karena Dia Maha Pengampun dan Maha Penyayang. Allah tidak akan mengecewakan seorang mukmin yang memohon kepada-Nya dengan sungguh-sungguh.\"","99":"Pada ayat ini, dijelaskan bahwa saudara-saudara Yusuf pulang ke negerinya untuk memboyong semua keluarganya ke Mesir sesuai dengan anjuran Yusuf. Setelah sampai, mereka memberitahukan kepada kedua orang tuanya tentang kedudukan Yusuf di Mesir, dimana dia adalah penguasa yang berkuasa penuh di sana. Disampaikan pula bahwa Yusuf mengundang semua keluarganya untuk menetap di Mesir bersama-sama dengannya, menikmati kemajuan dan keindahan kota Mesir. Mendengar berita itu, berangkatlah mereka bersama-sama ke Mesir. Setelah sampai di Mesir mereka bertemu dengan Yusuf dan rombongan yang pergi menjemput mereka di tengah jalan. Yusuf merangkul kedua orang tuanya dan berkata, \"Silakan memasuki negeri Mesir dengan selamat dan aman, insya Allah kamu sekalian tidak akan mengalami kesulitan dan kelaparan, sekalipun musim kemarau masih saja mencekam.\" Ucapan \"Insya Allah\" yang dikatakan Yusuf ini menjadi pelajaran bagi kita kaum Muslimin bahwa apabila hendak melakukan sesuatu, supaya disandarkan kepada kehendak Allah. Hal ini telah menjadi kebiasaan bagi para nabi dan shiddiqin. Hal tersebut sesuai pula dengan maksud firman Allah swt:\n\nDan jangan sekali-kali engkau mengatakan terhadap sesuatu, \"Aku pasti melakukan itu besok pagi,\" kecuali (dengan mengatakan), \"Insya Allah.\" (al-Kahf\u002F18: 23 dan 24)","100":"Ayat ini menjelaskan Yusuf kemudian mengangkat kedua orang tuanya dan mendudukkan mereka di atas singgasana sebagai penghormatan lebih daripada apa yang telah diperbuat kepada saudara-saudaranya. Mereka merebahkan diri seraya sujud memberi hormat kepada Yusuf, sebagaimana lazimnya orang-orang memberi hormat kepada raja dan para pembesar pada waktu itu. Yusuf lalu berkata, \"Wahai ayahku! Inilah takbir mimpiku dahulu ketika saya masih kecil yang telah saya sampaikan kepada ayah dengan ucapan:\n\nSungguh, aku (bermimpi) melihat sebelas bintang, matahari dan bulan; kulihat semuanya sujud kepadaku. (Yusuf\u002F12: 4)\n\nLebih lanjut Yusuf berkata, \"Allah swt menjadikan mimpiku itu benar-benar terjadi, bukan khayalan. Sebelas bintang itu adalah saudara-saudaraku yang berjumlah sebelas orang, sedang matahari dan bulan adalah ayah dan ibuku.\" Dengan keluarga inilah Allah swt memelihara keturunan Nabi Ishak, anak Nabi Ibrahim as, untuk mengembangkan agama tauhid di muka bumi ini. Selanjutnya Yusuf berkata kepada ayahnya, \"Allah swt telah berbuat baik kepadaku. Dia melepaskan aku dari penjara dan mengangkatku sebagai penguasa. Dia memindahkan ayah dari dusun padang pasir berpenghidupan sederhana dan kasar, ke negeri yang ramai, menikmati hidup yang bahagia, penyiaran agama yang benar, dan tolong menolong di dalam memajukan ilmu pengetahuan. Ini semua terjadi setelah setan memutus hubungan silaturrahim antara aku dan saudara-saudaraku sehingga rusaklah hubungan persaudaraan, dan timbullah rasa dengki dan buruk sangka antara kita. Sesungguhnya Allah swt Maha Mengetahui segala sesuatu yang bagaimanapun halusnya, bersifat lemah lembut kepada hamba-hamba-Nya, dan menetapkan apa yang Dia kehendaki dengan kebijaksanaan-Nya. Sesungguhnya Dia Maha Mengetahui apa yang menjadi maslahat bagi hamba-hamba-Nya. Tiada suatu hal yang tersembunyi bagi-Nya. Mahabijaksana di dalam segala hal, membalas orang-orang yang berbuat baik dengan kebaikan, dan kesudahan yang baik diberikan kepada orang-orang yang bertakwa.\"","101":"Ayat ini adalah pernyataan dan doa yang diucapkan Yusuf a.s. sesudah Allah swt menyelamatkannya dari dalam sumur, membebaskan dari fitnah istri al-Aziz dan perempuan-perempuan lainnya, membebaskan dari penderitaan dalam penjara, dan menganugerahinya pangkat dan kedudukan sesudah bebas dari semua tuduhan yang ditujukan kepadanya. Yusuf segera berdoa memohon kepada Allah swt supaya dilipatgandakan pahalanya di akhirat kelak sebagaimana dilipatgandakan karunia yang diterimanya di dunia. Yusuf berkata, \"Ya Tuhanku, Engkau telah menganugerahkan kepadaku kedudukan dan kekuasaan, mengajarkan kepadaku takbir mimpi, dan memberitahukan kepadaku hal-hal yang akan terjadi di kemudian hari dan rahasia-rahasia yang terkandung di dalam wahyu-Mu. Ya Allah! Engkaulah Pencipta langit dan bumi ini, menciptakan keduanya dengan baik dan teratur, kokoh dan rapi, Engkaulah Pelindungku di dunia dan di akhirat, melindungiku dari maksud jahat orang-orang yang memusuhiku dan orang-orang yang ingin berbuat jahat kepadaku. Ya Allah Yang Mahakuasa! Wafatkanlah aku dalam keadaan Islam, sesuai dengan wasiat leluhurku yang berbunyi:\n\nDan Ibrahim mewasiatkan (ucapan) itu kepada anak-anaknya, demikian pula Yakub, \"Wahai anak-anakku! Sesungguhnya Allah telah memilih agama ini untukmu, maka janganlah kamu mati kecuali dalam keadaan muslim. (al-Baqarah\u002F2: 132)\n\nYusuf melanjutkan doanya dengan mengatakan, \"Ya Allah Ya Tuhanku! Masukkanlah aku ke dalam kelompok orang-orang yang saleh dari leluhur kami seperti Nabi Ibrahim, Ismail, dan Ishak, begitu pula dengan para nabi dan rasul sebelumnya. Engkaulah Maha Pengasih, Maha Pemurah, dan Mahakuasa atas segala sesuatu.\"","102":"Pada ayat ini, Allah swt menerangkan bahwa kisah Yusuf yang telah dipaparkan di atas termasuk berita gaib. Berita gaib itu diwahyukan kepada Muhammad. Sebelumnya, ia dan umat Islam tidak mengetahuinya. Dia juga tidak mengetahui ketika saudara-saudara Yusuf bersatu dan sepakat untuk membuang Yusuf ke dalam sumur yang dalam, dan ketika mereka mengatur tipu daya dan makarnya. Muhammad saw mengetahui peristiwa yang telah dialami oleh Yusuf itu dengan perantaraan wahyu dari Allah swt. Peristiwa ini merupakan bukti yang nyata atas kebenaran kenabian dan kerasulan Muhammad saw. Bagi orang yang sadar, bukti ini menjadi alasan untuk mempercayai dan membenarkan kerasulan Muhammad saw itu.","103":"Pada ayat ini, diterangkan bahwa orang-orang yang telah benar-benar kafir dan terus-menerus membangkang, tidak akan beriman bagaimanapun kita mengharap dan menginginkannya, sekalipun telah diberikan alasan-alasan yang nyata dan meyakinkan. Begitu pula halnya dengan kebanyakan orang Quraisy Mekah, sekalipun telah diberikan bukti-bukti yang nyata, mereka tidak akan percaya dan tidak akan membenarkan kenabian dan kerasulan Muhammad saw. Oleh sebab itu, beriman atau tidaknya seseorang setelah menerima dakwah rasul bukan menjadi tanggung jawabnya. Firman Allah swt:\n\nSungguh, engkau (Muhammad) tidak dapat memberi petunjuk kepada orang yang engkau kasihi, tetapi Allah memberi petunjuk kepada orang yang Dia kehendaki, dan Dia lebih mengetahui orang-orang yang mau menerima petunjuk. (al-Qashash\u002F28: 56)","104":"Pada ayat ini, Allah swt mengingatkan Muhammad saw agar tidak meminta upah kepada siapa pun, sebagai imbalan dari dakwah dan anjurannya supaya mereka taat dan menyembah hanya kepada Allah swt serta meninggalkan agama berhala. Allah yang akan memberikan upah dan pahala atas usahanya itu, karena memang Al-Quran diturunkan kepadanya sebagai petunjuk melaksanakan tugasnya sebagai rasul. Al-Quran merupakan peringatan dan nasihat untuk membimbing dan memberi petunjuk kepada manusia yang akan membawa kepada kebahagiaan dunia dan akhirat.","105":"Pada ayat ini, Allah swt menerangkan bahwa tidak sedikit tanda-tanda yang menunjukkan keesaan, kesempurnaan, dan kekuasaan-Nya, seperti matahari, bulan, bintang-bintang, gunung-gunung, lautan, tanam-tanaman, dan lain-lain, yang bisa dilihat dan disaksikan sendiri oleh manusia. Akan tetapi, mereka tidak memperhatikannya dan tidak memikir-kan hikmah-hikmah yang terkandung di dalamnya. Semua itu menunjukkan bahwa Allah swt itu Esa, tiada Tuhan melainkan Dia. Dialah yang menciptakan semua makhluk dengan sempurna dan teratur. Kalaupun ada di antara mereka yang berusaha ingin mengetahui apa yang ada di langit dan di bumi, tetapi mereka lupa kepada Penciptanya. Dengan akalnya, mereka asyik menerapkan ilmunya, mengembangkan dan memanfaatkannya, tetapi jiwa mereka kosong dari mengingat Allah dan tidak beriman kepada-Nya. Ilmu saja, meskipun ada gunanya, tetapi tidak bermanfaat di akhirat kecuali apabila dilandasi iman kepada Allah. Alangkah berbahagianya orang yang dapat menyatukan keduanya. Orang itulah yang akan memperoleh kebaikan di dunia, dan akhirat serta selamat dari azab api neraka kelak.","106":"Ayat ini menjelaskan keadaan orang-orang Quraisy Mekah. Di samping percaya kepada Allah yang menciptakan segala sesuatu, mereka juga menyekutukan-Nya. Kalau mereka ditanya siapa yang menciptakan semua yang ada di bumi maupun di langit, mereka akan menjawab dengan tegas bahwa yang menciptakan semuanya itu ialah Allah swt sebagai tercantum dalam Al-Quran:\n\nDan sungguh, jika engkau (Muhammad) tanyakan kepada mereka, \"Siapakah yang menciptakan langit dan bumi?\" Tentu mereka akan menjawab, \"Allah.\" Katakanlah, \"Segala puji bagi Allah,\" tetapi kebanyakan mereka tidak mengetahui. (Luqman\u002F31: 25)\n\nPengakuan Quraisy Mekah terhadap eksistensi Allah juga diikuti dengan mempersekutukan-Nya. Mereka menyembah berhala dan menjadikan pendeta sebagai tuhan. Bahkan, ada di antara mereka yang mengatakan bahwa Allah itu mempunyai anak. Mahasuci Allah swt dari apa yang dituduhkan itu. Menyekutukan Allah itu adalah dosa yang paling besar. Ibnu Masud pernah bertanya kepada Nabi Muhammad saw tentang dosa yang paling besar. Nabi saw menjawab:\n\nBahwa kamu jadikan sekutu bagi Allah swt padahal Dialah yang menciptakanmu. (Riwayat al-Bukhari dan Muslim dari Ibnu Masud)","107":"Dalam ayat ini, Allah mempertanyakan apakah orang-orang yang mengakui Allah swt sebagai Penciptanya tetapi juga menyekutukan-Nya dengan mengadakan sembahan-sembahan selain-Nya, merasa aman dari azab yang akan menimpa mereka secara tiba-tiba. Apakah mereka merasa aman tidak akan menemui kematian secara mendadak dan tidak pernah diduga sebelumnya? Sekali-kali tidak! Sewaktu-waktu Allah swt dapat saja menimpakan azab kepada mereka, begitu juga Allah swt dapat memerintah-kan Malaikat Izrail untuk mencabut nyawanya secara mendadak tanpa diduga sebelumnya apabila Allah menghendaki. Allah swt Maha Pelaksana terhadap apa yang Dia kehendaki, sebagaimana firman-Nya:\n\nSungguh, Tuhanmu Maha Pelaksana terhadap apa yang Dia kehendaki. (Hud\u002F11: 107)\n\nSejalan dengan ayat 107 ini, firman Allah swt:\n\nMaka apakah orang yang membuat tipu daya yang jahat itu, merasa aman (dari bencana) dibenamkannya bumi oleh Allah bersama mereka, atau (terhadap) datangnya siksa kepada mereka dari arah yang tidak mereka sadari, atau Allah mengazab mereka pada waktu mereka dalam perjalanan; sehingga mereka tidak berdaya menolak (azab itu), atau Allah mengazab mereka dengan berangsur-angsur (sampai binasa). Maka sungguh, Tuhanmu Maha Pengasih, Maha Penyayang. (an-Nahl\u002F16: 45-47)\n\nDi antara hikmah disembunyikannya waktu kedatangan azab yang seolah-olah dengan tiba-tiba atau pencabutan nyawa oleh Izrail secara mendadak, ialah supaya mereka selalu siap siaga akan datangnya ajal. Dengan demikian, mereka selalu patuh dan taat dalam melaksanakan ibadah serta tidak melakukan maksiat. Mereka sadar hanya kepada Allah swt manusia menyembah dan tidak menyekutukan-Nya sedikit pun.","108":"Pada ayat ini, Allah swt memerintahkan kepada Muhammad saw untuk memberitahu umatnya bahwa dakwah yang dijalankannya, yang bertujuan mengajak manusia mengesakan Allah swt dan mengikhlaskan ibadah hanya kepada-Nya, adalah menjadi tugas dan kewajibannya. Rasul memiliki keyakinan bahwa usahanya ini akan berhasil karena apa yang dikemukakan dan dilaksanakannya dilandasi dengan bukti-bukti dan hujjah yang nyata. Yang demikian itu menjadi tugas dan kewajiban bagi orang-orang yang mempercayai dan mengikutinya sehingga segala macam bentuk penghambaan kepada selain Allah bisa musnah dari permukaan bumi ini. Perhatikanlah firman Allah swt yang mengajarkan cara berdakwah kepada Rasul dan umatnya:\n\nSerulah (manusia) kepada jalan Tuhanmu dengan hikmah dan pengajaran yang baik. (an-Nahl\u002F16: 125)\n\nPada potongan ayat berikutnya, Allah mengajarkan Muhammad saw untuk mensucikan-Nya dari tuduhan adanya sekutu dengan mengatakan Mahasuci Allah swt dari sangkaan bahwa Dia mempunyai sekutu dalam kekuasaan-Nya, dan ada yang wajib disembah selain Dia. Langit dan bumi serta segala isinya, bahkan semua yang ada, bertasbih menyucikan Allah dari hal yang demikian itu, firman Allah swt:\n\nLangit yang tujuh, bumi dan semua yang ada di dalamnya bertasbih kepada Allah. Dan tidak ada sesuatu pun melainkan bertasbih dengan memuji-Nya, tetapi kamu tidak mengerti tasbih mereka. Sungguh, Dia adalah Maha Penyantun, Maha Pengampun. (al-Isra\u002F17: 44)\n\nAyat 108 ini ditutup dengan satu ketegasan bahwa Nabi Muhammad saw tidak termasuk orang-orang yang musyrik.","109":"Pada ayat ini, Allah swt menerangkan bahwa Dia tidak mengutus rasul-rasul sebelum Muhammad saw kecuali laki-laki, bukan malaikat, dan bukan perempuan, serta menurunkan kepada mereka wahyu. Para rasul berasal dari penduduk negeri itu sendiri, supaya mereka mengikutinya. Ini merupakan jawaban terhadap tuduhan-tuduhan yang dilancarkan oleh orang-orang yang mengingkari kenabian Muhammad saw, yang menghendaki supaya rasul yang diutus itu dari jenis malaikat sebagaimana dikisahkan Allah swt di dalam firman-Nya:\n\nDan seandainya Allah menghendaki, tentu Dia mengutus malaikat. (al-Muminun\u002F23: 24)\n\nTidakkah orang-orang musyrik Quraisy yang mendustakan kenabian Muhammad saw dan mengingkari apa yang dibawanya seperti mengesakan Allah, mengikhlaskan ibadah semata-mata hanya kepada-Nya, bepergian di muka bumi dan melihat serta menyaksikan bagaimana akibat orang-orang yang mendustakan rasul-rasul dahulu. Mereka dibinasakan dan negerinya dihancurkan, seperti yang dialami kaum Nabi Hud, kaum Nabi Saleh, dan lain-lainnya. Sebaliknya orang-orang yang percaya kepada Allah dan rasul-Nya dan takut menyekutukan Allah, tidak berbuat dosa dan maksiat, akan memperoleh kesenangan nanti di negeri akhirat yang jauh lebih baik jika dibandingkan dengan apa yang didapat orang-orang musyrik di dunia ini. Apakah mereka tidak memikirkan perbedaan imbalan dan balasan antara orang-orang yang ingkar dan orang-orang yang percaya. Kesenangan yang didapat di dunia oleh orang-orang yang ingkar itu sangat terbatas. Apabila mereka meninggal dunia berakhirlah kesenangan itu, dan di negeri akhirat kelak mereka mendapat azab yang amat pedih tak henti-hentinya. Dan kesenangan yang diperoleh orang-orang yang beriman, tidak saja di dunia tetapi sampai ke akhirat nanti, karena kesenangan yang diperolehnya itu abadi selamanya.","110":"Ayat ini menjelaskan sunatullah yang telah berlaku pada umat-umat terdahulu. Allah swt mengutus para rasul-Nya dengan bukti yang nyata dan diperkuat dengan mukjizat. Setelah rasul-rasul itu ditentang, didustakan, dan dimusuhi oleh kaumnya sehingga merasakan tekanan yang amat berat, timbullah perasaan seakan-akan mereka berputus asa karena tidak ada harapan lagi kaumnya akan beriman dan kemenangan yang ditunggu-tunggu belum juga datang, pada saat itulah pertolongan Allah swt datang. Sedangkan orang-orang yang mendustakan para nabi ditimpa azab dengan tiba-tiba, seperti banjir besar yang menenggelamkan kaum Nabi Nuh, angin ribut yang membinasakan kaum Â'd (kaum Nabi Hud), siksaan yang menimpa kaum samud, dan bencana yang melanda negeri kaum Nabi Luth, sebagaimana tercantum dalam firman Allah swt:\n\nApakah tidak sampai kepada mereka berita (tentang) orang-orang yang sebelum mereka, (yaitu) kaum Nuh, Ad, Samud, kaum Ibrahim, penduduk Madyan, dan (penduduk) negeri-negeri yang telah musnah? Telah datang kepada mereka rasul-rasul dengan membawa bukti-bukti yang nyata; Allah tidak menzalimi mereka, tetapi merekalah yang menzalimi diri mereka sendiri. (at-Taubah\u002F9: 70)\n\nOrang-orang Quraisy yang tidak mau insaf dan kembali ke jalan yang benar, sekalipun telah ditunjukkan bukti-bukti yang nyata, akan ditimpakan Allah azab yang pedih. Sedangkan Nabi Muhammad diberi pertolongan berupa berbagai kemenangan yang telah diperolehnya seperti Perang Badar dan pada perang-perang berikutnya. Allah swt menyelamatkan para rasul beserta kaumnya yang beriman kepada-Nya, sedang orang-orang yang ingkar kepada Allah swt dan mendustakan rasul-rasul-Nya dan agama yang dibawanya akan diazab, tidak seorang pun dari mereka yang dapat menolak dan mengelak dari azab Allah itu.","111":"Pada ayat ini, Allah swt menerangkan bahwa semua kisah nabi-nabi, terutama Nabi Yusuf a.s. bersama ayah dan saudara-saudaranya, adalah pelajaran bagi orang-orang yang mempunyai akal sehat. Sedang orang-orang yang lalai yang tidak memanfaatkan akal dan pikirannya untuk memahami kenyataan yang ada, maka kisah Nabi tersebut tidak akan bermanfaat baginya. Mereka tidak akan dapat mengambil pelajaran dan peringatan darinya. Seharusnya mereka memperhatikan bahwa yang mampu dan kuasa menyelamatkan Nabi Yusuf a.s. setelah dibuang ke dasar sumur, meng-angkat derajatnya sesudah ia dipenjarakan, menguasai negeri Mesir sesudah dijual dengan harga murah, meninggikan pangkatnya dari saudara-saudara-nya yang ingin membinasakannya, dan mengumpulkan mereka kembali bersama kedua orang tuanya sesudah berpisah sekian lama, tentu sanggup dan kuasa pula memuliakan Muhammad, meninggikan kalimatnya, memenangkan agama yang dibawanya, serta membantu dan menguatkannya dengan tentara, pengikut, dan pendukung setia, sekalipun di dalam menjalani semuanya itu, beliau pernah mengalami kesukaran dan kesulitan. \n\nKitab suci Al-Quran yang membawa kisah-kisah tersebut, bukanlah suatu cerita yang dibuat-buat dan diada-adakan, tetapi adalah wahyu yang diturunkan Allah swt dan mukjizat yang melemahkan tokoh-tokoh sastra ulung ketika ditantang untuk menyusun yang seperti itu. Kisah-kisah itu diberitakan dari nabi yang tidak pernah mempelajari buku-buku dan tidak pernah bergaul dengan ulama-ulama cerdik pandai. Bahkan kitab Suci Al-Quran itu membenarkan isi kitab-kitab samawi yang diturunkan kepada nabi-nabi sebelumnya, seperti kitab Taurat, Injil, dan Zabur yang asli tentunya, bukan yang sudah ditambah dengan khurafat dan lain-lain hal yang tidak lagi terjaga kemurniannya. Dalam kitab suci Al-Quran diuraikan dengan jelas perintah-perintah Allah, larangan-larangan-Nya, janji-janji dan ancaman-Nya, sifat kesempurnaan yang wajib bagi-Nya dan suci dari sifat-sifat kekurangan dan hal-hal yang lain, sebagaimana firman Allah swt:\n\nTidak ada sesuatu pun yang Kami luputkan di dalam Kitab. (al-Anam\u002F6: 38)\n\nAl-Quran adalah petunjuk bagi orang-orang yang mau membacanya dengan penuh kesadaran dan yang mau meneliti dan mendalami isinya. Al-Quran juga akan membimbing mereka ke jalan yang benar dan membawa kepada kebahagiaan dunia dan akhirat. Al-Quran adalah rahmat bagi orang-orang yang beriman, yaitu mereka yang membenarkan dan mempercayai serta mengamalkan isinya, karena iman itu ialah ucapan yang dibenarkan oleh hati dan dibuktikan dengan amal perbuatan."}}}}},jsonldBreadcrumb:{"@context":f,"@type":"BreadcrumbList",itemListElement:[{"@type":a,position:1,name:"Home",item:"https:\u002F\u002Fwww.baca-quran.id\u002F"},{"@type":a,position:2,name:"QS 12",item:"https:\u002F\u002Fwww.baca-quran.id\u002F12\u002F"},{"@type":a,position:3,name:"QS 12:22",item:g}]},jsonLdArticle:{"@context":f,"@type":"NewsArticle",mainEntityOfPage:{"@type":"WebPage","@id":g},headline:b,image:["https:\u002F\u002Fwww.baca-quran.id\u002Fmeta-image.png"],datePublished:h,dateModified:h,author:{"@type":"Person",name:"Irfan Maulana"},description:c,publisher:{"@type":"Organization",name:"mazipan",logo:{"@type":"ImageObject",url:"https:\u002F\u002Fwww.baca-quran.id\u002Ficon.png"}}}}],fetch:{},mutations:[]}}("ListItem","Ayat ke 22, QS Yusuf (Yusuf) | Baca-Quran.id","Ayat ke 22, QS Yusuf (Yusuf) beserta terjemahan dan tafsir dari Kemenag, ❌ tanpa iklan, ❌ tanpa analitik, ✅ gratis sepenuhnya","Yusuf","Pada kedua ayat ini dikisahkan bahwa saudara-saudara Yusuf kembali menemui Yakub pada malam hari dengan muka yang pucat dan dengan air mata yang bercucuran seraya berkata, \"Wahai ayah kami, apa yang ayah khawatirkan selama ini benar-benar telah terjadi tanpa kemauan kami. Kami pergi bermain-main, dan kami tinggalkan Yusuf untuk menjaga pakaian dan barang-barang kami. Rupanya tanpa kami sadari karena asyiknya kami bermain, kami sudah jauh terpisah dari dia. Setelah kami kembali, kami dapati Yusuf sudah diterkam dan dimakan oleh serigala. Kami tidak mendengar pekik dan teriaknya karena kami telah jauh meninggalkan tempatnya. Kami menyadari bahwa ayah tidak akan percaya kepada cerita kami ini, meskipun kami menceritakan apa yang sebenarnya telah terjadi karena ayah selalu menaruh curiga terhadap kami. Tetapi malang yang tak dapat ditolak inilah yang terjadi dan kamipun tidak berdaya untuk menolongnya.\"","https:\u002F\u002Fschema.org","https:\u002F\u002Fwww.baca-quran.id\u002F12\u002F22\u002F","2021-08-01T10:39:54.934Z")));
import React from 'react'; import classNames from 'classnames'; import Gocd from '../lib/Gocd'; var allStatuses = { "Passed": "passed", "Cancelled": "cancelled", "Failed": "failed", "Unknown": "unknown", "Building": "building" }; export default React.createClass({ getInitialState: function(){ return {jobs: []}; }, componentDidMount: function() { if (this.props.drillDown) { Gocd.fetchJobs(this.props.data.details_path, (function(jobs){ this.setState({jobs: jobs}); }).bind(this), //TODO: error handling function(){}); } }, render: function() { let stageClass = classNames("stage", "fill-height-or-more", this.props.drillDown? undefined: allStatuses[this.props.data.status]); let renderJobs = () => this.state.jobs.map((job, index) => (<div key={index} className={classNames("job", allStatuses[job.result])}>{job.name}</div>)); return (<div className={stageClass}>{this.props.drillDown? renderJobs() :this.props.data.name}</div>); } });
// State is not application state, only the state // this reducer is reponsible for export default function(state = null, action){ switch (action.type) { case 'BOOK_SELECTED': return action.payload; } return state; }
import React, {Component} from 'react'; import styles from './style.css'; import {Wizard, WizardNav} from 'coral-ui'; import Layout from 'coral-admin/src/components/ui/Layout'; import InitialStep from './Steps/InitialStep'; import AddOrganizationName from './Steps/AddOrganizationName'; import CreateYourAccount from './Steps/CreateYourAccount'; import PermittedDomainsStep from './Steps/PermittedDomainsStep'; import FinalStep from './Steps/FinalStep'; export default class Install extends Component { handleDomainsChange = (value) => { this.props.updatePermittedDomains(value); }; handleSettingsChange = ({currentTarget: {name, value}}) => { this.props.updateSettingsFormData(name, value); }; handleUserChange = ({currentTarget: {name, value}}) => { this.props.updateUserFormData(name, value); }; handleSettingsSubmit = (e) => { e.preventDefault(); this.props.submitSettings(); }; handleUserSubmit = (e) => { e.preventDefault(); this.props.submitUser(); } render() { const {install} = this.props; return ( <Layout restricted={true}> <div className={styles.Install}> { !install.alreadyInstalled ? ( <div> <h2>Welcome to the Coral Project</h2> { install.step !== 0 ? <WizardNav items={install.navItems} currentStep={install.step} icon='check'/> : null } <Wizard currentStep={install.step} nextStep={this.props.nextStep} previousStep={this.props.previousStep} goToStep={this.props.goToStep} > <InitialStep/> <AddOrganizationName install={install} handleSettingsChange={this.handleSettingsChange} handleSettingsSubmit={this.handleSettingsSubmit} /> <CreateYourAccount install={install} handleUserChange={this.handleUserChange} handleUserSubmit={this.handleUserSubmit} /> <PermittedDomainsStep install={install} handleDomainsChange={this.handleDomainsChange} finishInstall={this.props.finishInstall} /> <FinalStep/> </Wizard> </div> ) : ( <div>Talk is already installed</div> ) } </div> </Layout> ); } }
import React from 'react'; import Playlist from '../../playlist/components/playlist'; import './category.css'; function Category(props) { return ( <div className="Category"> <p className="Category-description">{props.description}</p> <h2 className="Category-title">{props.title}</h2> <Playlist handleOpenModal={props.handleOpenModal} playlist={props.playlist}/> </div> ); } export default Category;
"use strict"; var util = require("util"); exports.gotoTypedef = gotoTypedef; exports.generatedDate = generatedDate; exports.formatAnchor = function( str ){ if( str ) str = str.toLowerCase().replace(/\./g, ""); return str; }; /** replaces {code} tags with markdown links in the suppied input text */ exports.formatDescription = function(text){ if (text){ text = text.replace(/\&lt;/g, '<').replace(/&gt;/g, '>'); //change code text = text.replace(/\<code\>/g, '`' ); text = text.replace(/\<\/code\>/g, '`' ); //remove break line text = text.replace(/\<br\/\>/g, '' ); text = text.replace(/\<br\>/g, '' ); //reformat local link //goto a method inside class //[MMTDrop.tools#mergeObjects](MMTDrop.tools#mergeObjects) //MMTDrop.reportFactory.createRealtimeReport ==> reportFactory#createRealtimeReport text = text.replace(/\]\(\#?MMTDrop\.(\w+)[\.\#](.+)\)/g, function(match, p1, p2){ return '](' + p1 + '#markdown-header-' + p2.toLowerCase() + ')'; }); //goto a class text = text.replace(/\#MMTDrop\./g, ''); //else start with # ==> goto typedef# text = text.replace(/\]\(\#(\w+)/g, function(match, p1){ return '](typedef#markdown-header-' + p1.toLowerCase(); }); } return text; }; function gotoTypedef( url ){ //start with #MMTDrop. ==> goto class if( url.indexOf("#MMTDrop.") == 0 || url.indexOf("MMTDrop.") == 0){ //goto a method inside class //MMTDrop.reportFactory.createRealtimeReport ==> reportFactory#createRealtimeReport url = url.replace(/\#?MMTDrop\.(\w+)[\.\#](.+)/g, function( match, p1, p2){ return p1 + "#markdown-header-" + p2.toLowerCase(); }); //go to class url = url.replace(/\#MMTDrop\./g, ''); return url; } //else start with # ==> goto typedef# url = url.toLowerCase().replace(/\#/, 'typedef#markdown-header-'); return url; } function generatedDate(){ return new Date().toUTCString(); };
var menu = require('../')({ width: 29, x: 4, y: 2 }); menu.reset(); menu.write('SERIOUS BUSINESS TERMINAL\n'); menu.write('-------------------------\n'); menu.add('ADD TRANSACTION INVOICE'); menu.add('BUSINESS INTELLIGENCE'); menu.add('ACCOUNTS PAYABLE'); menu.add('LEDGER BOOKINGS'); menu.add('INDICATOR CHART METRICS'); menu.add('BACKUP DATA TO FLOPPY DISK'); menu.add('RESTORE FROM FLOPPY DISK'); menu.add('EXIT'); menu.on('select', function (label) { menu.toggle(label); }); menu.createStream().pipe(process.stdout);
"use strict";(self.webpackChunk=self.webpackChunk||[]).push([[3529],{33529:M=>{M.exports=JSON.parse('{"locale":"hi","countries":{"AD":"अंडोरा","AE":"संयुक्त अरब अमीरात","AF":"अफगानिस्तान","AG":"एंटीगुआ और बारबूडा","AI":"अंग्विला","AL":"अल्बानिया","AM":"अर्मेनिया","AO":"अंगोला","AQ":"अंटार्टिका","AR":"अर्जेंटिना","AS":"अमेरिकान सामोआ","AT":"आस्ट्रिया","AU":"आस्ट्रेलिया","AW":"अरुबा","AX":"ऑलैण्ड द्वीपसमूह","AZ":"अजरबेजान","BA":"बोस्निया हर्जेगोविना","BB":"बार्बाडोस","BD":"बांग्लादेश","BE":"बेल्जियम","BF":"बुर्किना फासो","BG":"बल्गारिया","BH":"बहरीन","BI":"बुरुंडी","BJ":"बानिन","BL":"सेंट_बार्थेलेमी","BM":"बर्मूडा","BN":"ब्रुनेई","BO":"बोलिविया","BQ":"कैरिबियन नीदरलैंड","BR":"ब्राजील","BS":"बहामास","BT":"भूटान","BV":"बाउवेट","BW":"बोत्सवाना","BY":"बेलारुस","BZ":"बेलिजे","CA":"कनाडा","CC":"कोकोस (कीलिंग) द्वीप","CD":"कांगो लोकतान्त्रिक गणराज्य","CF":"सेंट्रल अफ्रीका गणतंत्र","CG":"कांगो","CH":"स्विट्जरलैंड","CI":"आइवरी कोस्ट","CK":"कुक द्वीप","CL":"चिली","CM":"कैमरून","CN":"चीन","CO":"कोलंबिया","CR":"कोस्टा रिका","CU":"क्यूबा","CV":"केप वर्दे","CW":"कुराकाओ","CX":"क्रिसमस द्वीप","CY":"साइप्रस","CZ":"चेक","DE":"जर्मनी","DJ":"जिबॉती","DK":"डैनमार्क","DM":"डोमिनिक","DO":"डोमिनिक गणतंत्र","DZ":"अल्जीरिया","EC":"इक्वाडोर","EE":"एस्तोनिया","EG":"मिस्र","EH":"पश्चिमी सहारा","ER":"एरिट्रेया","ES":"स्पेन","ET":"इथियोपिया","FI":"फिनलैंड","FJ":"फिजी","FK":"फाकलैंड द्वीप समूह (मालविनास)","FM":"माइक्रोनेशिया","FO":"फराओ द्वीप समूह","FR":"फ्रांस","GA":"गैबोन","GB":"ग्रेट ब्रिटेन","GD":"ग्रेनेडा","GE":"जॉर्जिया","GF":"फ्रेंच गुआना","GG":"ग्वेर्नसे","GH":"घाना","GI":"जिब्राल्टर","GL":"ग्रीनलैंड","GM":"जांबिया","GN":"गिनी","GP":"ग्वाडेलोप","GQ":"एक्वेटोरियल गिनी","GR":"यूनान","GS":"दक्षिण जॉर्जिया और दक्षिण सैंडविच द्वीप समूह","GT":"ग्वाटेमाला","GU":"ग्वाम","GW":"गिनी-बिसाउ","GY":"गुआना","HK":"हांग कांग","HM":"हर्ड एंड मैकडोनाल्ड द्वीपसमूह","HN":"होंडुरास","HR":"क्रोएशिया","HT":"हैती","HU":"हंगरी","ID":"इंडोनेशिया","IE":"आयरलैंड","IL":"इजराइल","IM":"आइसल ऑफ मैन","IN":"भारत","IO":"ब्रितानी हिंद महासागरीय क्षेत्र","IQ":"इराक","IR":"ईरान","IS":"आइसलैंड","IT":"इटली","JE":"जर्सी","JM":"जमैका","JO":"जॉर्डन","JP":"जापान","KE":"केन्या","KG":"किर्जिस्तान","KH":"कंबोडिया","KI":"किरिबिती","KM":"कोमोरोस","KN":"सेंट किट्स एंड नेविस","KP":"उत्तर कोरिया","KR":"दक्षिण कोरिया","KW":"कुवैत","KY":"केमैन आइसलैंड्स","KZ":"कज़ाखिस्तान","LA":"लाओस","LB":"लेबनान","LC":"सेंट लुसिया","LI":"लिक्टेनिस्टीन","LK":"श्री लंका","LR":"लाइबेरिया","LS":"लेसोथो","LT":"लिथुआनिया","LU":"लक्जमबर्ग","LV":"लात्विया","LY":"लीबिया","MA":"मोरक्को","MC":"मोनाको","MD":"मोलदोवा","ME":"मोंटेनेग्रो","MF":"सेंट मार्टिन की सामूहिकता","MG":"मैडागास्कर","MH":"मार्शल द्वीपसमूह","MK":"मकदूनिया","ML":"माली","MM":"म्यामांर (बर्मा)","MN":"मंगोलिया","MO":"मकाओ","MP":"उत्तर मैरिना द्वीपसमूह","MQ":"मार्टिनिक","MR":"मॉरितानिया","MS":"मोंटसेराट","MT":"माल्टा","MU":"मारीशस","MV":"मालदीव","MW":"मालावी","MX":"मेक्सिको","MY":"मलयेशिया","MZ":"मोजांबिक","NA":"नामीबिया","NC":"न्यू कैलेडोनिया","NE":"नाइजर","NF":"नोरफॉक द्वीप","NG":"नाइजीरिया","NI":"निकारागुआ","NL":"नीदरलैंड्स","NO":"नॉर्वे","NP":"नेपाल","NR":"नाउरू","NU":"नियू","NZ":"न्यूजीलैंड","OM":"ओमान","PA":"पनामा","PE":"पेरू","PF":"फ्रैंच गुआना","PG":"पापुआ न्यू गिनी","PH":"फिलीपींस","PK":"पाकिस्तान","PL":"पोलैंड","PM":"सेंट पिएरे एंड मिक्वेलॉन","PN":"पिटकैर्न द्वीपसमूह","PR":"पुएर्तो रिको","PS":"फिलिस्तीन राज्य","PT":"पुर्तगाल","PW":"पलाउ","PY":"पराग्वे","QA":"क़तार","RE":"रीयूनियन","RO":"रोमानिया","RS":"सर्बिया","RU":"रूस","RW":"रवांडा","SA":"सऊदी अरब","SB":"सोलोमन द्वीपसमूह","SC":"सेशेल्स","SD":"सूडान","SE":"स्वीडन","SG":"सिंगापुर","SH":"सेंट हेलेना","SI":"स्लोवानिया","SJ":"स्यालबार्ड (स्यालबार्ड एंड जन मावेम)","SK":"स्लोवाकिया","SL":"सियारा लिओन","SM":"सैन मारिनो","SN":"सेनेगल","SO":"सोमालिया","SR":"सूरीनाम","SS":"दक्षिण सूडान","ST":"साओ टॉम एंड प्रिंसिपी","SV":"सल्वाडोर","SX":"सिण्ट मार्टेन","SY":"सीरिया","SZ":"स्वाजीलैंड","TC":"तुर्क एंड कैकोस द्वीपसमूह","TD":"चाड","TF":"फ्रांसीसी दक्षिणी क्षेत्र","TG":"टोगो","TH":"थाईलैंड","TJ":"तज़ाकिस्तान","TK":"टोकेलू","TL":"पूर्वी तिमोर","TM":"तुर्कमेनिस्तान","TN":"ट्यूनीशिया","TO":"टोंगा","TR":"तुर्की","TT":"ट्रिनिडाड एंड टोबैगो","TV":"तुवालू","TW":"ताइवान","TZ":"तंजानिया","UA":"उक्रेन","UG":"उगांडा","UM":"यूएस माइनर आउटलाइंग द्वीपसमूह","US":"यूएसए (संयुक्त राज्य अमेरिका)","UY":"उरुग्वे","UZ":"उजबेकिस्तान","VA":"वेटिकन","VC":"सेंट विंसेंट एंड द ग्रेनेंडाइन्स","VE":"वेनेजुएला","VG":"ब्रितानी वर्जिन द्वीपसमूह","VI":"अमेरिकी वर्जिन द्वीपसमूह","VN":"विएतनाम","VU":"वनातू","WF":"वालीज एंड फुटुना","WS":"पश्चिमी सामोआ","XK":"कोसोवो","YE":"यमन","YT":"मायोते","ZA":"दक्षिण अफ्रीका","ZM":"जांबिया","ZW":"जिंबावे"}}')}}]);
Clazz.declarePackage ("J.shape"); Clazz.load (["J.shape.AtomShape", "java.util.Hashtable"], "J.shape.Labels", ["javajs.awt.Font", "JU.AU", "$.BS", "J.constant.EnumPalette", "J.modelset.LabelToken", "$.Text", "J.util.BSUtil", "$.C", "J.viewer.JC"], function () { c$ = Clazz.decorateAsClass (function () { this.strings = null; this.formats = null; this.bgcolixes = null; this.fids = null; this.offsets = null; this.atomLabels = null; this.text = null; this.labelBoxes = null; this.bsFontSet = null; this.bsBgColixSet = null; this.defaultOffset = 0; this.defaultAlignment = 0; this.defaultZPos = 0; this.defaultFontId = 0; this.defaultColix = 0; this.defaultBgcolix = 0; this.defaultPaletteID = 0; this.defaultPointer = 0; this.zeroFontId = 0; this.defaultsOnlyForNone = true; this.setDefaults = false; this.isScaled = false; this.scalePixelsPerMicron = 0; this.pickedAtom = -1; this.pickedOffset = 0; this.pickedX = 0; this.pickedY = 0; Clazz.instantialize (this, arguments); }, J.shape, "Labels", J.shape.AtomShape); Clazz.prepareFields (c$, function () { this.atomLabels = new java.util.Hashtable (); }); $_M(c$, "initShape", function () { Clazz.superCall (this, J.shape.Labels, "initShape", []); this.defaultFontId = this.zeroFontId = this.gdata.getFont3DFSS ("SansSerif", "Plain", 13).fid; this.defaultColix = 0; this.defaultBgcolix = 0; this.defaultOffset = J.shape.Labels.zeroOffset; this.defaultZPos = 0; this.translucentAllowed = false; }); $_V(c$, "setProperty", function (propertyName, value, bsSelected) { this.isActive = true; if ("setDefaults" === propertyName) { this.setDefaults = (value).booleanValue (); return; }if ("color" === propertyName) { var pid = J.constant.EnumPalette.pidOf (value); var colix = J.util.C.getColixO (value); if (!this.setDefaults) for (var i = bsSelected.nextSetBit (0); i >= 0 && i < this.atomCount; i = bsSelected.nextSetBit (i + 1)) this.setLabelColix (i, colix, pid); if (this.setDefaults || !this.defaultsOnlyForNone) { this.defaultColix = colix; this.defaultPaletteID = pid; }return; }if ("scalereference" === propertyName) { if (this.strings == null) return; var val = (value).floatValue (); var scalePixelsPerMicron = (val == 0 ? 0 : 10000 / val); for (var i = bsSelected.nextSetBit (0); i >= 0 && i < this.atomCount; i = bsSelected.nextSetBit (i + 1)) { if (this.strings.length <= i) continue; this.text = this.getLabel (i); if (this.text == null) { this.text = J.modelset.Text.newLabel (this.gdata, null, this.strings[i], 0, 0, 0, scalePixelsPerMicron, null); this.putLabel (i, this.text); } else { this.text.setScalePixelsPerMicron (scalePixelsPerMicron); }} return; }if ("label" === propertyName) { this.setScaling (); var strLabel = value; var tokens = (strLabel == null || strLabel.length == 0 ? J.shape.Labels.nullToken : [null]); for (var i = bsSelected.nextSetBit (0); i >= 0 && i < this.atomCount; i = bsSelected.nextSetBit (i + 1)) this.setLabel (tokens, strLabel, i); return; }if ("labels" === propertyName) { this.setScaling (); var labels = value; for (var i = bsSelected.nextSetBit (0), pt = 0; i >= 0 && i < this.atomCount; i = bsSelected.nextSetBit (i + 1)) { var strLabel = labels.get (pt++); var tokens = (strLabel == null || strLabel.length == 0 ? J.shape.Labels.nullToken : [null]); this.setLabel (tokens, strLabel, i); } return; }if ("clearBoxes" === propertyName) { this.labelBoxes = null; return; }if ("translucency" === propertyName || "bgtranslucency" === propertyName) { return; }if ("bgcolor" === propertyName) { this.isActive = true; if (this.bsBgColixSet == null) this.bsBgColixSet = new JU.BS (); var bgcolix = J.util.C.getColixO (value); if (!this.setDefaults) for (var i = bsSelected.nextSetBit (0); i >= 0 && i < this.atomCount; i = bsSelected.nextSetBit (i + 1)) this.setBgcolix (i, bgcolix); if (this.setDefaults || !this.defaultsOnlyForNone) this.defaultBgcolix = bgcolix; return; }if (this.bsFontSet == null) this.bsFontSet = new JU.BS (); if ("textLabels" === propertyName) { this.setScaling (); var labels = value; for (var i = bsSelected.nextSetBit (0); i >= 0 && i < this.atomCount; i = bsSelected.nextSetBit (i + 1)) this.setTextLabel (i, labels.get (Integer.$valueOf (i))); return; }if ("fontsize" === propertyName) { var fontsize = (value).intValue (); if (fontsize < 0) { this.fids = null; return; }var fid = this.gdata.getFontFid (fontsize); if (!this.setDefaults) for (var i = bsSelected.nextSetBit (0); i >= 0 && i < this.atomCount; i = bsSelected.nextSetBit (i + 1)) this.setFont (i, fid); if (this.setDefaults || !this.defaultsOnlyForNone) this.defaultFontId = fid; return; }if ("font" === propertyName) { var fid = (value).fid; if (!this.setDefaults) for (var i = bsSelected.nextSetBit (0); i >= 0 && i < this.atomCount; i = bsSelected.nextSetBit (i + 1)) this.setFont (i, fid); if (this.setDefaults || !this.defaultsOnlyForNone) this.defaultFontId = fid; return; }if ("offset" === propertyName || "offsetexact" === propertyName) { if (!(Clazz.instanceOf (value, Integer))) { if (!this.setDefaults) for (var i = bsSelected.nextSetBit (0); i >= 0 && i < this.atomCount; i = bsSelected.nextSetBit (i + 1)) this.setPymolOffset (i, value); return; }var offset = (value).intValue (); var isExact = (propertyName === "offsetexact"); if (offset == 0) offset = 32767; else if (offset == J.shape.Labels.zeroOffset) offset = 0; if (!this.setDefaults) for (var i = bsSelected.nextSetBit (0); i >= 0 && i < this.atomCount; i = bsSelected.nextSetBit (i + 1)) this.setOffsets (i, offset, isExact); if (this.setDefaults || !this.defaultsOnlyForNone) this.defaultOffset = offset; return; }if ("align" === propertyName) { var type = value; var alignment = 1; if (type.equalsIgnoreCase ("right")) alignment = 3; else if (type.equalsIgnoreCase ("center")) alignment = 2; for (var i = bsSelected.nextSetBit (0); i >= 0 && i < this.atomCount; i = bsSelected.nextSetBit (i + 1)) this.setAlignment (i, alignment); if (this.setDefaults || !this.defaultsOnlyForNone) this.defaultAlignment = alignment; return; }if ("pointer" === propertyName) { var pointer = (value).intValue (); if (!this.setDefaults) for (var i = bsSelected.nextSetBit (0); i >= 0 && i < this.atomCount; i = bsSelected.nextSetBit (i + 1)) this.setPointer (i, pointer); if (this.setDefaults || !this.defaultsOnlyForNone) this.defaultPointer = pointer; return; }if ("front" === propertyName) { var TF = (value).booleanValue (); if (!this.setDefaults) for (var i = bsSelected.nextSetBit (0); i >= 0 && i < this.atomCount; i = bsSelected.nextSetBit (i + 1)) this.setFront (i, TF); if (this.setDefaults || !this.defaultsOnlyForNone) this.defaultZPos = (TF ? 32 : 0); return; }if ("group" === propertyName) { var TF = (value).booleanValue (); if (!this.setDefaults) for (var i = bsSelected.nextSetBit (0); i >= 0 && i < this.atomCount; i = bsSelected.nextSetBit (i + 1)) this.setGroup (i, TF); if (this.setDefaults || !this.defaultsOnlyForNone) this.defaultZPos = (TF ? 16 : 0); return; }if ("display" === propertyName || "toggleLabel" === propertyName) { var mode = ("toggleLabel" === propertyName ? 0 : (value).booleanValue () ? 1 : -1); if (this.mads == null) this.mads = Clazz.newShortArray (this.atomCount, 0); var strLabelPDB = null; var tokensPDB = null; var strLabelUNK = null; var tokensUNK = null; var strLabel; var tokens; for (var i = bsSelected.nextSetBit (0); i >= 0 && i < this.atomCount; i = bsSelected.nextSetBit (i + 1)) { var atom = this.atoms[i]; if (this.formats == null || i >= this.formats.length) this.formats = JU.AU.ensureLengthS (this.formats, i + 1); if (this.strings != null && this.strings.length > i && this.strings[i] != null) { this.mads[i] = (mode == 0 && this.mads[i] < 0 || mode == 1 ? 1 : -1); } else { if (this.bsSizeSet == null) this.bsSizeSet = new JU.BS (); this.strings = JU.AU.ensureLengthS (this.strings, i + 1); if (atom.getGroup3 (false).equals ("UNK")) { if (strLabelUNK == null) { strLabelUNK = this.viewer.getStandardLabelFormat (1); tokensUNK = J.modelset.LabelToken.compile (this.viewer, strLabelUNK, '\0', null); }strLabel = strLabelUNK; tokens = tokensUNK; } else { if (strLabelPDB == null) { strLabelPDB = this.viewer.getStandardLabelFormat (2); tokensPDB = J.modelset.LabelToken.compile (this.viewer, strLabelPDB, '\0', null); }strLabel = strLabelPDB; tokens = tokensPDB; }this.strings[i] = J.modelset.LabelToken.formatLabelAtomArray (this.viewer, atom, tokens, '\0', null); this.formats[i] = strLabel; this.bsSizeSet.set (i); if ((this.bsBgColixSet == null || !this.bsBgColixSet.get (i)) && this.defaultBgcolix != 0) this.setBgcolix (i, this.defaultBgcolix); this.mads[i] = (mode >= 0 ? 1 : -1); }atom.setShapeVisibility (this.myVisibilityFlag, this.strings != null && i < this.strings.length && this.strings[i] != null && this.mads[i] >= 0); } return; }if (propertyName.startsWith ("label:")) { this.setScaling (); this.setLabel ( new Array (1), propertyName.substring (6), (value).intValue ()); return; }if (propertyName === "deleteModelAtoms") { this.labelBoxes = null; var firstAtomDeleted = ((value)[2])[1]; var nAtomsDeleted = ((value)[2])[2]; this.fids = JU.AU.deleteElements (this.fids, firstAtomDeleted, nAtomsDeleted); this.bgcolixes = JU.AU.deleteElements (this.bgcolixes, firstAtomDeleted, nAtomsDeleted); this.offsets = JU.AU.deleteElements (this.offsets, firstAtomDeleted, nAtomsDeleted); this.formats = JU.AU.deleteElements (this.formats, firstAtomDeleted, nAtomsDeleted); this.strings = JU.AU.deleteElements (this.strings, firstAtomDeleted, nAtomsDeleted); J.util.BSUtil.deleteBits (this.bsFontSet, bsSelected); J.util.BSUtil.deleteBits (this.bsBgColixSet, bsSelected); }this.setPropAS (propertyName, value, bsSelected); }, "~S,~O,JU.BS"); $_M(c$, "setPymolOffset", ($fz = function (i, value) { var text = this.getLabel (i); if (text == null) { var fid = (this.bsFontSet != null && this.bsFontSet.get (i) ? this.fids[i] : -1); if (fid < 0) this.setFont (i, fid = this.defaultFontId); var font = javajs.awt.Font.getFont3D (fid); var colix = this.getColix2 (i, this.atoms[i], false); text = J.modelset.Text.newLabel (this.gdata, font, this.strings[i], colix, this.getColix2 (i, this.atoms[i], true), 0, this.scalePixelsPerMicron, value); this.setTextLabel (i, text); } else { text.pymolOffset = value; }}, $fz.isPrivate = true, $fz), "~N,~A"); $_M(c$, "setScaling", ($fz = function () { this.isActive = true; if (this.bsSizeSet == null) this.bsSizeSet = new JU.BS (); this.isScaled = this.viewer.getBoolean (603979845); this.scalePixelsPerMicron = (this.isScaled ? this.viewer.getScalePixelsPerAngstrom (false) * 10000 : 0); }, $fz.isPrivate = true, $fz)); $_M(c$, "setTextLabel", ($fz = function (i, t) { if (t == null) return; var label = t.getText (); var atom = this.atoms[i]; this.addString (atom, i, label, label); atom.setShapeVisibility (this.myVisibilityFlag, true); if (t.colix >= 0) this.setLabelColix (i, t.colix, J.constant.EnumPalette.UNKNOWN.id); this.setFont (i, t.font.fid); this.putLabel (i, t); }, $fz.isPrivate = true, $fz), "~N,J.modelset.Text"); $_M(c$, "setLabel", ($fz = function (temp, strLabel, i) { var atom = this.atoms[i]; var tokens = temp[0]; if (tokens == null) tokens = temp[0] = J.modelset.LabelToken.compile (this.viewer, strLabel, '\0', null); var label = (tokens == null ? null : J.modelset.LabelToken.formatLabelAtomArray (this.viewer, atom, tokens, '\0', null)); this.addString (atom, i, label, strLabel); this.text = this.getLabel (i); if (this.isScaled) { this.text = J.modelset.Text.newLabel (this.gdata, null, label, 0, 0, 0, this.scalePixelsPerMicron, null); this.putLabel (i, this.text); } else if (this.text != null && label != null) { this.text.setText (label); }if (this.defaultOffset != J.shape.Labels.zeroOffset) this.setOffsets (i, this.defaultOffset, false); if (this.defaultAlignment != 1) this.setAlignment (i, this.defaultAlignment); if ((this.defaultZPos & 32) != 0) this.setFront (i, true); else if ((this.defaultZPos & 16) != 0) this.setGroup (i, true); if (this.defaultPointer != 0) this.setPointer (i, this.defaultPointer); if (this.defaultColix != 0 || this.defaultPaletteID != 0) this.setLabelColix (i, this.defaultColix, this.defaultPaletteID); if (this.defaultBgcolix != 0) this.setBgcolix (i, this.defaultBgcolix); if (this.defaultFontId != this.zeroFontId) this.setFont (i, this.defaultFontId); }, $fz.isPrivate = true, $fz), "~A,~S,~N"); $_M(c$, "addString", ($fz = function (atom, i, label, strLabel) { atom.setShapeVisibility (this.myVisibilityFlag, label != null); if (this.strings == null || i >= this.strings.length) this.strings = JU.AU.ensureLengthS (this.strings, i + 1); if (this.formats == null || i >= this.formats.length) this.formats = JU.AU.ensureLengthS (this.formats, i + 1); this.strings[i] = label; this.formats[i] = (strLabel != null && strLabel.indexOf ("%{") >= 0 ? label : strLabel); this.bsSizeSet.setBitTo (i, (strLabel != null)); }, $fz.isPrivate = true, $fz), "J.modelset.Atom,~N,~S,~S"); $_V(c$, "getProperty", function (property, index) { if (property.equals ("offsets")) return this.offsets; if (property.equals ("label")) return (this.strings != null && index < this.strings.length && this.strings[index] != null ? this.strings[index] : ""); return null; }, "~S,~N"); $_M(c$, "putLabel", function (i, text) { if (text == null) this.atomLabels.remove (Integer.$valueOf (i)); else this.atomLabels.put (Integer.$valueOf (i), text); }, "~N,J.modelset.Text"); $_M(c$, "getLabel", function (i) { return this.atomLabels.get (Integer.$valueOf (i)); }, "~N"); $_M(c$, "putBox", function (i, boxXY) { if (this.labelBoxes == null) this.labelBoxes = new java.util.Hashtable (); this.labelBoxes.put (Integer.$valueOf (i), boxXY); }, "~N,~A"); $_M(c$, "getBox", function (i) { if (this.labelBoxes == null) return null; return this.labelBoxes.get (Integer.$valueOf (i)); }, "~N"); $_M(c$, "setLabelColix", ($fz = function (i, colix, pid) { this.setColixAndPalette (colix, pid, i); if (this.colixes != null && ((this.text = this.getLabel (i)) != null)) this.text.setColix (this.colixes[i]); }, $fz.isPrivate = true, $fz), "~N,~N,~N"); $_M(c$, "setBgcolix", ($fz = function (i, bgcolix) { if (this.bgcolixes == null || i >= this.bgcolixes.length) { if (bgcolix == 0) return; this.bgcolixes = JU.AU.ensureLengthShort (this.bgcolixes, i + 1); }this.bgcolixes[i] = bgcolix; this.bsBgColixSet.setBitTo (i, bgcolix != 0); this.text = this.getLabel (i); if (this.text != null) this.text.setBgColix (bgcolix); }, $fz.isPrivate = true, $fz), "~N,~N"); $_M(c$, "setOffsets", ($fz = function (i, offset, isExact) { if (this.offsets == null || i >= this.offsets.length) { if (offset == 0) return; this.offsets = JU.AU.ensureLengthI (this.offsets, i + 1); }this.offsets[i] = (this.offsets[i] & 255) | (offset << 8); if (isExact) this.offsets[i] |= 128; this.text = this.getLabel (i); if (this.text != null) this.text.setOffset (offset); }, $fz.isPrivate = true, $fz), "~N,~N,~B"); $_M(c$, "setAlignment", ($fz = function (i, alignment) { if (this.offsets == null || i >= this.offsets.length) { if (alignment == 1) return; this.offsets = JU.AU.ensureLengthI (this.offsets, i + 1); }this.offsets[i] = (this.offsets[i] & -13) | (alignment << 2); this.text = this.getLabel (i); if (this.text != null) this.text.setAlignment (alignment); }, $fz.isPrivate = true, $fz), "~N,~N"); c$.getAlignment = $_M(c$, "getAlignment", function (offsetFull) { return (offsetFull & 12) >> 2; }, "~N"); $_M(c$, "setPointer", ($fz = function (i, pointer) { if (this.offsets == null || i >= this.offsets.length) { if (pointer == 0) return; this.offsets = JU.AU.ensureLengthI (this.offsets, i + 1); }this.offsets[i] = (this.offsets[i] & -4) + pointer; this.text = this.getLabel (i); if (this.text != null) this.text.setPointer (pointer); }, $fz.isPrivate = true, $fz), "~N,~N"); $_M(c$, "setFront", ($fz = function (i, TF) { if (this.offsets == null || i >= this.offsets.length) { if (!TF) return; this.offsets = JU.AU.ensureLengthI (this.offsets, i + 1); }this.offsets[i] = (this.offsets[i] & -49) + (TF ? 32 : 0); }, $fz.isPrivate = true, $fz), "~N,~B"); $_M(c$, "setGroup", ($fz = function (i, TF) { if (this.offsets == null || i >= this.offsets.length) { if (!TF) return; this.offsets = JU.AU.ensureLengthI (this.offsets, i + 1); }this.offsets[i] = (this.offsets[i] & -49) + (TF ? 16 : 0); }, $fz.isPrivate = true, $fz), "~N,~B"); $_M(c$, "setFont", ($fz = function (i, fid) { if (this.fids == null || i >= this.fids.length) { if (fid == this.zeroFontId) return; this.fids = JU.AU.ensureLengthByte (this.fids, i + 1); }this.fids[i] = fid; this.bsFontSet.set (i); this.text = this.getLabel (i); if (this.text != null) { this.text.setFontFromFid (fid); }}, $fz.isPrivate = true, $fz), "~N,~N"); $_V(c$, "setModelClickability", function () { if (this.strings == null) return; for (var i = this.strings.length; --i >= 0; ) { var label = this.strings[i]; if (label != null && this.modelSet.atoms.length > i && !this.modelSet.isAtomHidden (i)) this.modelSet.atoms[i].setClickable (this.myVisibilityFlag); } }); $_V(c$, "getShapeState", function () { if (!this.isActive || this.bsSizeSet == null) return ""; return this.viewer.getShapeState (this); }); $_V(c$, "checkObjectDragged", function (prevX, prevY, x, y, dragAction, bsVisible) { if (this.viewer.getPickingMode () != 2 || this.labelBoxes == null) return false; if (prevX == -2147483648) { var iAtom = this.findNearestLabel (x, y); if (iAtom >= 0) { this.pickedAtom = iAtom; this.pickedX = x; this.pickedY = y; this.pickedOffset = (this.offsets == null || this.pickedAtom >= this.offsets.length ? 0 : this.offsets[this.pickedAtom]) >> 8; return true; }return false; }if (prevX == 2147483647) { this.pickedAtom = -1; return false; }if (this.pickedAtom < 0) return false; this.move2D (this.pickedAtom, x, y); return true; }, "~N,~N,~N,~N,~N,JU.BS"); $_M(c$, "findNearestLabel", ($fz = function (x, y) { if (this.labelBoxes == null) return -1; var dmin = 3.4028235E38; var imin = -1; var zmin = 3.4028235E38; for (var entry, $entry = this.labelBoxes.entrySet ().iterator (); $entry.hasNext () && ((entry = $entry.next ()) || true);) { if (!this.atoms[entry.getKey ().intValue ()].isVisible (this.myVisibilityFlag)) continue; var boxXY = entry.getValue (); var dx = x - boxXY[0]; var dy = y - boxXY[1]; if (dx <= 0 || dy <= 0 || dx >= boxXY[2] || dy >= boxXY[3] || boxXY[4] > zmin) continue; zmin = boxXY[4]; var d = Math.min (Math.abs (dx - boxXY[2] / 2), Math.abs (dy - boxXY[3] / 2)); if (d <= dmin) { dmin = d; imin = entry.getKey ().intValue (); }} return imin; }, $fz.isPrivate = true, $fz), "~N,~N"); $_M(c$, "move2D", ($fz = function (pickedAtom, x, y) { var xOffset = J.viewer.JC.getXOffset (this.pickedOffset); var yOffset = -J.viewer.JC.getYOffset (this.pickedOffset); xOffset += x - this.pickedX; yOffset += this.pickedY - y; var offset = J.viewer.JC.getOffset (xOffset, yOffset); if (offset == 0) offset = 32767; else if (offset == J.shape.Labels.zeroOffset) offset = 0; this.setOffsets (pickedAtom, offset, true); }, $fz.isPrivate = true, $fz), "~N,~N,~N"); $_M(c$, "getColix2", function (i, atom, isBg) { var colix; if (isBg) { colix = (this.bgcolixes == null || i >= this.bgcolixes.length) ? 0 : this.bgcolixes[i]; } else { colix = (this.colixes == null || i >= this.colixes.length) ? 0 : this.colixes[i]; colix = J.util.C.getColixInherited (colix, atom.getColix ()); if (J.util.C.isColixTranslucent (colix)) colix = J.util.C.getColixTranslucent3 (colix, false, 0); }return colix; }, "~N,J.modelset.Atom,~B"); Clazz.defineStatics (c$, "zeroOffset", 1028); c$.nullToken = c$.prototype.nullToken = [null]; });
Meteor.methods({ validateAnswer: function(props) { return registerSignService({ props: props, templateName: "validateAnswer", success: getValidateAnswerJson }); } }); var getValidateAnswerJson = function(xml) { var isValidAnswer = xml.get("/soap:Envelope/soap:Body/ns2:ValidateAnswerResponse/validAnswer", { "soap": "http://www.w3.org/2003/05/soap-envelope", "ns2": "http://www.exchangenetwork.net/wsdl/register/sign/1" }).text(); console.log("is valid answer: " + isValidAnswer); return { isValidAnswer: isValidAnswer }; }
import { onBeforeUnmount } from '@vue/composition-api'; import userAppConfig from '@/core/app-config/useAppConfig'; /** * Collapse vertical menu when route is visited and restore the state on route leave */ export const useCollapseMenuOnVisit = () => { const { isVerticalMenuCollapsed } = userAppConfig(); const wasVerticalMenuCollapsed = isVerticalMenuCollapsed.value; if (!wasVerticalMenuCollapsed.value) { isVerticalMenuCollapsed.value = true; } // Restore the original collapse value onBeforeUnmount(() => { isVerticalMenuCollapsed.value = wasVerticalMenuCollapsed; }); }; export const _ = null;
/** * * TemplateNoAsync * */ import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { createStructuredSelector } from 'reselect'; import { compose } from 'redux'; import { useInjectReducer } from 'utils/injectReducer'; import makeSelectTemplateNoAsync from './selectors'; import reducer from './reducer'; export function TemplateNoAsync() { useInjectReducer({ key: 'templateNoAsync', reducer }); return <div />; } TemplateNoAsync.propTypes = { dispatch: PropTypes.func.isRequired, }; const mapStateToProps = createStructuredSelector({ templateNoAsync: makeSelectTemplateNoAsync(), }); function mapDispatchToProps(dispatch) { return { dispatch, }; } const withConnect = connect( mapStateToProps, mapDispatchToProps, ); export default compose(withConnect)(TemplateNoAsync);
var Tablet = { radiusFactor: 0.75, // the pen pressure acts on the tool's radius intensityFactor: 0.0, // the pen pressure acts on the tool's intensity pressure: 0.5 }; Tablet.getPressureIntensity = function () { return 1.0 + Tablet.intensityFactor * (Tablet.pressure * 2.0 - 1.0); }; Tablet.getPressureRadius = function () { return 1.0 + Tablet.radiusFactor * (Tablet.pressure * 2.0 - 1.0); }; export default Tablet;
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'bidi', 'en-ca', { ltr: 'Text direction from left to right', // MISSING rtl: 'Text direction from right to left' // MISSING } );
const { Model, DataTypes } = require('sequelize'); const bcrypt = require('bcrypt'); const sequelize = require('../config/connection'); class User extends Model { checkPassword(loginPw) { return bcrypt.compareSync(loginPw, this.password); } } User.init( { id: { type: DataTypes.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true, }, username: { type: DataTypes.STRING, allowNull: false, unique: true, }, email: { type: DataTypes.STRING, allowNull: true, validate: { isEmail: true, }, }, password: { type: DataTypes.STRING, allowNull: false, validate: { len: [4], }, }, }, { hooks: { beforeCreate: async (newUserData) => { newUserData.password = await bcrypt.hash(newUserData.password, 10); return newUserData; }, beforeUpdate: async (updatedUserData) => { updatedUserData.password = await bcrypt.hash( updatedUserData.password, 10 ); return updatedUserData; }, }, sequelize, timestamps: false, freezeTableName: true, underscored: true, modelName: 'user', } ); module.exports = User;
/** @jsx h */ import h from '../../helpers/h' export default function(value) { return value .change() .delete() .value.change() .undo().value } export const input = ( <value> <document> <paragraph> <b> on <anchor />e </b> <u> tw <focus />o </u> </paragraph> </document> </value> ) export const output = input
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var IdMap = { models: new Map(), insert: function insert(model) { var klass = model.constructor, id = model.id, map; if (!(map = this.models.get(klass))) { this.models.set(klass, map = new Map()); } if (map.get(id)) { throw new Error("IdMap.insert: model of type `" + klass + "` and id `" + id + "` has already been inserted"); } map.set(id, model); return this; }, get: function get(klass, id) { var map = this.models.get(klass); return map && map.get(id); }, delete: function _delete(model) { var map = this.models.get(model.constructor); if (!map) { return this; } map.delete(model.id); return this; }, clear: function clear() { this.models.clear();return this; } }; exports.default = IdMap; module.exports = exports["default"];
!function(t){var e={};function n(r){if(e[r])return e[r].exports;var o=e[r]={i:r,l:!1,exports:{}};return t[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}n.m=t,n.c=e,n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{configurable:!1,enumerable:!0,get:r})},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s=6)}([function(t,e){t.exports=function(t,e,n,r,o,i){var u,a=t=t||{},s=typeof t.default;"object"!==s&&"function"!==s||(u=t,a=t.default);var c,f="function"==typeof a?a.options:a;if(e&&(f.render=e.render,f.staticRenderFns=e.staticRenderFns,f._compiled=!0),n&&(f.functional=!0),o&&(f._scopeId=o),i?(c=function(t){(t=t||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext)||"undefined"==typeof __VUE_SSR_CONTEXT__||(t=__VUE_SSR_CONTEXT__),r&&r.call(this,t),t&&t._registeredComponents&&t._registeredComponents.add(i)},f._ssrRegister=c):r&&(c=r),c){var l=f.functional,p=l?f.render:f.beforeCreate;l?(f._injectStyles=c,f.render=function(t,e){return c.call(e),p(t,e)}):f.beforeCreate=p?[].concat(p,c):[c]}return{esModule:u,exports:a,options:f}}},function(t,e,n){"use strict";e.a={methods:{trans:function(t,e){return window.config.translations["nova-translation::"+t]?this.__("nova-translation::"+t,e):t}}}},function(t,e,n){"use strict";var r=function(){return function(t,e){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return function(t,e){var n=[],r=!0,o=!1,i=void 0;try{for(var u,a=t[Symbol.iterator]();!(r=(u=a.next()).done)&&(n.push(u.value),!e||n.length!==e);r=!0);}catch(t){o=!0,i=t}finally{try{!r&&a.return&&a.return()}finally{if(o)throw i}}return n}(t,e);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}();e.a={computed:{locale:function(){var t=_.findKey(this.locales,function(t){return t.iso===Nova.config.locale});return this.locales.hasOwnProperty(t)?this.locales[t]:null},locales:function(){return this.field&&this.field.locales?this.field.locales:{}},otherLocales:function(){var t=this;return _.pickBy(this.locales,function(e){return e.id!==t.translation.locale_id})},translation:function(){return this.field&&this.field.value?this.field.value:null},translations:function(){return this.field&&this.field.translations?Array.isArray(this.field.translations)?{}:this.field.translations:{}},isTranslated:function(){var t=this;return _.mapValues(this.locales,function(e){return!!t.translations.hasOwnProperty(e.id)||null!==t.translation&&t.translation.locale_id===e.id})},hasTranslation:function(){var t=!0,e=!1,n=void 0;try{for(var o,i=Object.entries(this.isTranslated)[Symbol.iterator]();!(t=(o=i.next()).done);t=!0){var u=o.value,a=r(u,2),s=a[0];if(!0===a[1]&&s!=this.locale.id)return!0}}catch(t){e=!0,n=t}finally{try{!t&&i.return&&i.return()}finally{if(e)throw n}}return!1}}}},function(t,e){t.exports=function(t){var e=[];return e.toString=function(){return this.map(function(e){var n=function(t,e){var n=t[1]||"",r=t[3];if(!r)return n;if(e&&"function"==typeof btoa){var o=(u=r,"/*# sourceMappingURL=data:application/json;charset=utf-8;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(u))))+" */"),i=r.sources.map(function(t){return"/*# sourceURL="+r.sourceRoot+t+" */"});return[n].concat(i).concat([o]).join("\n")}var u;return[n].join("\n")}(e,t);return e[2]?"@media "+e[2]+"{"+n+"}":n}).join("")},e.i=function(t,n){"string"==typeof t&&(t=[[null,t,""]]);for(var r={},o=0;o<this.length;o++){var i=this[o][0];"number"==typeof i&&(r[i]=!0)}for(o=0;o<t.length;o++){var u=t[o];"number"==typeof u[0]&&r[u[0]]||(n&&!u[2]?u[2]=n:n&&(u[2]="("+u[2]+") and ("+n+")"),e.push(u))}},e}},function(t,e,n){var r="undefined"!=typeof document;if("undefined"!=typeof DEBUG&&DEBUG&&!r)throw new Error("vue-style-loader cannot be used in a non-browser environment. Use { target: 'node' } in your Webpack config to indicate a server-rendering environment.");var o=n(11),i={},u=r&&(document.head||document.getElementsByTagName("head")[0]),a=null,s=0,c=!1,f=function(){},l=null,p="data-vue-ssr-id",h="undefined"!=typeof navigator&&/msie [6-9]\b/.test(navigator.userAgent.toLowerCase());function d(t){for(var e=0;e<t.length;e++){var n=t[e],r=i[n.id];if(r){r.refs++;for(var o=0;o<r.parts.length;o++)r.parts[o](n.parts[o]);for(;o<n.parts.length;o++)r.parts.push(g(n.parts[o]));r.parts.length>n.parts.length&&(r.parts.length=n.parts.length)}else{var u=[];for(o=0;o<n.parts.length;o++)u.push(g(n.parts[o]));i[n.id]={id:n.id,refs:1,parts:u}}}}function v(){var t=document.createElement("style");return t.type="text/css",u.appendChild(t),t}function g(t){var e,n,r=document.querySelector("style["+p+'~="'+t.id+'"]');if(r){if(c)return f;r.parentNode.removeChild(r)}if(h){var o=s++;r=a||(a=v()),e=_.bind(null,r,o,!1),n=_.bind(null,r,o,!0)}else r=v(),e=function(t,e){var n=e.css,r=e.media,o=e.sourceMap;r&&t.setAttribute("media",r);l.ssrId&&t.setAttribute(p,e.id);o&&(n+="\n/*# sourceURL="+o.sources[0]+" */",n+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(o))))+" */");if(t.styleSheet)t.styleSheet.cssText=n;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(n))}}.bind(null,r),n=function(){r.parentNode.removeChild(r)};return e(t),function(r){if(r){if(r.css===t.css&&r.media===t.media&&r.sourceMap===t.sourceMap)return;e(t=r)}else n()}}t.exports=function(t,e,n,r){c=n,l=r||{};var u=o(t,e);return d(u),function(e){for(var n=[],r=0;r<u.length;r++){var a=u[r];(s=i[a.id]).refs--,n.push(s)}e?d(u=o(t,e)):u=[];for(r=0;r<n.length;r++){var s;if(0===(s=n[r]).refs){for(var c=0;c<s.parts.length;c++)s.parts[c]();delete i[s.id]}}}};var y,m=(y=[],function(t,e){return y[t]=e,y.filter(Boolean).join("\n")});function _(t,e,n,r){var o=n?"":r.css;if(t.styleSheet)t.styleSheet.cssText=m(e,o);else{var i=document.createTextNode(o),u=t.childNodes;u[e]&&t.removeChild(u[e]),u.length?t.insertBefore(i,u[e]):t.appendChild(i)}}},function(t,e,n){var r=n(0)(n(27),n(28),!1,function(t){n(25)},"data-v-316f3aaf",null);t.exports=r.exports},function(t,e,n){n(7),t.exports=n(37)},function(t,e,n){Nova.booting(function(t,e,r){e.addRoutes([{name:"nova-translation",path:"/nova-translation",component:n(8)}]),t.component("index-nova-translation-field",n(21)),t.component("detail-nova-translation-field",n(30)),t.component("form-nova-translation-field",n(33))})},function(t,e,n){var r=n(0)(n(12),n(20),!1,function(t){n(9)},"data-v-09f0b7bf",null);t.exports=r.exports},function(t,e,n){var r=n(10);"string"==typeof r&&(r=[[t.i,r,""]]),r.locals&&(t.exports=r.locals);n(4)("67782773",r,!0,{})},function(t,e,n){(t.exports=n(3)(!1)).push([t.i,".modal[data-v-09f0b7bf]{background-color:rgba(0,0,0,.6)}.translation-matrix[data-v-09f0b7bf]{max-height:calc(95vh - 150px)}thead th.border-rb[data-v-09f0b7bf]{border-bottom:none}th.border-rb[data-v-09f0b7bf]{border-right:none;-webkit-box-shadow:2px 2px 0 0 var(--50);box-shadow:2px 2px 0 0 var(--50)}th.border-b[data-v-09f0b7bf]{border-bottom:none;-webkit-box-shadow:0 2px 0 0 var(--50);box-shadow:0 2px 0 0 var(--50)}th.no-uppercase[data-v-09f0b7bf]{text-transform:none!important}.table tbody tr td[data-v-09f0b7bf]:not(:last-child){min-width:20rem}",""])},function(t,e){t.exports=function(t,e){for(var n=[],r={},o=0;o<e.length;o++){var i=e[o],u=i[0],a={id:t+":"+o,css:i[1],media:i[2],sourceMap:i[3]};r[u]?r[u].parts.push(a):n.push(r[u]={id:u,parts:[a]})}return n}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(1),o=n(13),i=n.n(o);e.default={mixins:[r.a],components:{PromptKeyModal:n(14),CloudinaryUpload:n(17)},data:function(){return{labels:[],locales:[],loading:!0,currentEdit:{},cloudinaryWidget:null,promptKeyModalOpened:!1}},mounted:function(){this.hydrate()},methods:{hydrate:function(){var t=this;Nova.request().get("/nova-vendor/nova-translation/translation-matrix").then(function(e){t.setupCloudinaryWidget(e.data.cloudinary),t.labels=e.data.labels,t.locales=e.data.locales,t.loading=!1}).catch(function(t){console.error(t)})},updateLabel:function(t,e,n){for(var r=0;r<this.labels.length;r++)if(this.labels[r].key===t&&this.labels[r].locale_id===e){this.labels[r].value=n;break}},saveLabels:function(){var t=this;this.loading=!0,Nova.request().post("/nova-vendor/nova-translation/translation-matrix",{labels:this.labels}).then(function(e){t.labels=e.data.labels,t.$toasted.show(t.trans("The translations have been successfully saved!"),{type:"success"})}).catch(function(e){t.$toasted.show(t.trans("An error occurred while saving the translations!"),{type:"error"})}).finally(function(){t.loading=!1})},setCurrentEdit:function(t){this.currentEdit=t},setupCloudinaryWidget:function(t){var e=this;this.cloudinaryWidget=cloudinary.createMediaLibrary({api_key:t.api_key,multiple:!1,username:t.username,signature:t.signature,timestamp:t.timestamp,cloud_name:t.cloud_name},{insertHandler:function(t){t.assets.length>0&&e.updateLabel(e.currentEdit.localeKey,e.currentEdit.localeId,t.assets[0].public_id)}})},addKey:function(t){var e=this;this.promptKeyModalOpened=!1,this.keyExists(t.key)?this.$toasted.show(this.trans("The key you try to add already exists!"),{type:"error"}):this.addI18nKey(t.key,t.type),this.$nextTick(function(){var n=document.querySelector("#textarea__"+t.key+"__"+e.locales[0].id);n&&n.focus(),i()(document.querySelector("#tr__"+t.key),{speed:500})})},keyExists:function(t){for(var e=0;e<this.labels.length;e++)if(this.labels[e].key===t)return!0;return!1},addI18nKey:function(t,e){for(var n=0;n<this.locales.length;n++)this.labels.push({key:t,type:e,value:"",locale_id:this.locales[n].id})},deleteKey:function(t){for(var e=[],n=0;n<this.labels.length;n++)this.labels[n].key!==t&&e.push(this.labels[n]);this.labels=e}},computed:{matrix:function(){for(var t,e={},n=0;n<this.labels.length;n++)t=this.labels[n],void 0===e[t.key]&&(e[t.key]={}),e[t.key][t.locale_id]={type:t.type,value:t.value};var r={};return Object.keys(e).sort().forEach(function(t){r[t]=e[t]}),r}}}},function(t,e,n){"use strict";var r=this&&this.__assign||function(){return(r=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var o in e=arguments[n])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t}).apply(this,arguments)},o=this&&this.__awaiter||function(t,e,n,r){return new(n||(n=Promise))(function(o,i){function u(t){try{s(r.next(t))}catch(t){i(t)}}function a(t){try{s(r.throw(t))}catch(t){i(t)}}function s(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(u,a)}s((r=r.apply(t,e||[])).next())})},i=this&&this.__generator||function(t,e){var n,r,o,i,u={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(i){return function(a){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;u;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return u.label++,{value:i[1],done:!1};case 5:u.label++,r=i[1],i=[0];continue;case 7:i=u.ops.pop(),u.trys.pop();continue;default:if(!(o=(o=u.trys).length>0&&o[o.length-1])&&(6===i[0]||2===i[0])){u=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){u.label=i[1];break}if(6===i[0]&&u.label<o[1]){u.label=o[1],o=i;break}if(o&&u.label<o[2]){u.label=o[2],u.ops.push(i);break}o[2]&&u.ops.pop(),u.trys.pop();continue}i=e.call(t,u)}catch(t){i=[6,t],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,a])}}};function u(t){var e=0,n=0,r=t;do{e+=r.offsetTop||0,n+=r.offsetLeft||0,r=r.offsetParent}while(r);return{top:e,left:n}}Object.defineProperty(e,"__esModule",{value:!0});var a=function(){function t(t){this.element=t}return t.prototype.getHorizontalScroll=function(){return this.element.scrollLeft},t.prototype.getVerticalScroll=function(){return this.element.scrollTop},t.prototype.getMaxHorizontalScroll=function(){return this.element.scrollWidth-this.element.clientWidth},t.prototype.getMaxVerticalScroll=function(){return this.element.scrollHeight-this.element.clientHeight},t.prototype.getHorizontalElementScrollOffset=function(t,e){return u(t).left-u(e).left},t.prototype.getVerticalElementScrollOffset=function(t,e){return u(t).top-u(e).top},t.prototype.scrollTo=function(t,e){this.element.scrollLeft=t,this.element.scrollTop=e},t}(),s=function(){function t(){}return t.prototype.getHorizontalScroll=function(){return window.scrollX||document.documentElement.scrollLeft},t.prototype.getVerticalScroll=function(){return window.scrollY||document.documentElement.scrollTop},t.prototype.getMaxHorizontalScroll=function(){return Math.max(document.body.scrollWidth,document.documentElement.scrollWidth,document.body.offsetWidth,document.documentElement.offsetWidth,document.body.clientWidth,document.documentElement.clientWidth)-window.innerWidth},t.prototype.getMaxVerticalScroll=function(){return Math.max(document.body.scrollHeight,document.documentElement.scrollHeight,document.body.offsetHeight,document.documentElement.offsetHeight,document.body.clientHeight,document.documentElement.clientHeight)-window.innerHeight},t.prototype.getHorizontalElementScrollOffset=function(t){return(window.scrollX||document.documentElement.scrollLeft)+t.getBoundingClientRect().left},t.prototype.getVerticalElementScrollOffset=function(t){return(window.scrollY||document.documentElement.scrollTop)+t.getBoundingClientRect().top},t.prototype.scrollTo=function(t,e){window.scrollTo(t,e)},t}(),c={elements:[],cancelMethods:[],add:function(t,e){c.elements.push(t),c.cancelMethods.push(e)},remove:function(t,e){void 0===e&&(e=!0);var n=c.elements.indexOf(t);n>-1&&(e&&c.cancelMethods[n](),c.elements.splice(n,1),c.cancelMethods.splice(n,1))}},f="undefined"!=typeof window,l={cancelOnUserAction:!0,easing:function(t){return--t*t*t+1},elementToScroll:f?window:null,horizontalOffset:0,maxDuration:3e3,minDuration:250,speed:500,verticalOffset:0};e.default=function(t,e){return void 0===e&&(e={}),o(this,void 0,void 0,function(){var n,o,u,p,h,d,v,g,y,m,_,b,w,x,j,E,O;return i(this,function(i){if(!f)return[2,new Promise(function(t){t(!1)})];if(!window.Promise)throw"Browser doesn't support Promises, and animated-scroll-to depends on it, please provide a polyfill.";if(p=r(r({},l),e),h=p.elementToScroll===window,d=!!p.elementToScroll.nodeName,!h&&!d)throw"Element to scroll needs to be either window or DOM element.";if(v=h?document.documentElement:p.elementToScroll,"smooth"===getComputedStyle(v).getPropertyValue("scroll-behavior")&&console.warn(v.tagName+' has "scroll-behavior: smooth" which can mess up with animated-scroll-to\'s animations'),g=h?new s:new a(p.elementToScroll),t instanceof Element){if(u=t,d&&(!p.elementToScroll.contains(u)||p.elementToScroll.isSameNode(u)))throw"options.elementToScroll has to be a parent of scrollToElement";n=g.getHorizontalElementScrollOffset(u,p.elementToScroll),o=g.getVerticalElementScrollOffset(u,p.elementToScroll)}else if("number"==typeof t)n=g.getHorizontalScroll(),o=t;else{if(!Array.isArray(t)||2!==t.length)throw"Wrong function signature. Check documentation.\nAvailable method signatures are:\n animateScrollTo(y:number, options)\n animateScrollTo([x:number | null, y:number | null], options)\n animateScrollTo(scrollToElement:Element, options)";n=null===t[0]?g.getHorizontalScroll():t[0],o=null===t[1]?g.getVerticalScroll():t[1]}return n+=p.horizontalOffset,o+=p.verticalOffset,y=g.getMaxHorizontalScroll(),m=g.getHorizontalScroll(),n>y&&(n=y),_=n-m,b=g.getMaxVerticalScroll(),w=g.getVerticalScroll(),o>b&&(o=b),x=o-w,j=Math.abs(Math.round(_/1e3*p.speed)),E=Math.abs(Math.round(x/1e3*p.speed)),(O=j>E?j:E)<p.minDuration?O=p.minDuration:O>p.maxDuration&&(O=p.maxDuration),[2,new Promise(function(t,e){var r;0===_&&0===x&&t(!0),c.remove(p.elementToScroll,!0);var i=function(){f(),cancelAnimationFrame(r),t(!1)};c.add(p.elementToScroll,i);var u=p.cancelOnUserAction?i:function(t){return t.preventDefault()},a=p.cancelOnUserAction?{passive:!0}:{passive:!1},s=["wheel","touchstart","keydown","mousedown"],f=function(){s.forEach(function(t){p.elementToScroll.removeEventListener(t,u,a)})};s.forEach(function(t){p.elementToScroll.addEventListener(t,u,a)});var l=Date.now(),h=function(){var e=Date.now()-l,i=e/O,u=Math.round(m+_*p.easing(i)),a=Math.round(w+x*p.easing(i));e<O&&(u!==n||a!==o)?(g.scrollTo(u,a),r=requestAnimationFrame(h)):(g.scrollTo(n,o),cancelAnimationFrame(r),f(),c.remove(p.elementToScroll,!1),t(!0))};r=requestAnimationFrame(h)})]})})}},function(t,e,n){var r=n(0)(n(15),n(16),!1,null,null,null);t.exports=r.exports},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(1);e.default={mixins:[r.a],data:function(){return{newKey:"",newType:"text"}},mounted:function(){document.querySelectorAll(".modal input")[0].focus()},methods:{handleKeydown:function(t){-1===["Escape","Enter"].indexOf(t.key)&&t.stopPropagation()},handleConfirm:function(){""!==this.newKey.trim()&&this.$emit("confirm",{type:this.newType,key:this.newKey})},handleClose:function(){this.$emit("close")}}}},function(t,e){t.exports={render:function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("modal",{attrs:{role:"dialog"},on:{"modal-close":t.handleClose}},[n("form",{staticClass:"bg-white rounded-lg shadow-lg overflow-hidden w-action-fields",attrs:{autocomplete:"off"},on:{keydown:t.handleKeydown,submit:function(e){return e.preventDefault(),e.stopPropagation(),t.handleConfirm(e)}}},[n("div",[n("heading",{staticClass:"border-b border-40 py-8 px-8",attrs:{level:2}},[t._v(t._s(t.trans("Add a translation key")))]),t._v(" "),n("div",{staticClass:"m-8"},[n("div",{staticClass:"action"},[n("select",{directives:[{name:"model",rawName:"v-model",value:t.newType,expression:"newType"}],staticClass:"w-full form-control form-select",on:{change:function(e){var n=Array.prototype.filter.call(e.target.options,function(t){return t.selected}).map(function(t){return"_value"in t?t._value:t.value});t.newType=e.target.multiple?n:n[0]}}},[n("option",{attrs:{value:"text"}},[t._v(t._s(t.trans("Text")))]),t._v(" "),n("option",{attrs:{value:"upload"}},[t._v(t._s(t.trans("Upload")))])])]),t._v(" "),n("div",{staticClass:"mt-2 action"},[n("input",{directives:[{name:"model",rawName:"v-model",value:t.newKey,expression:"newKey"}],staticClass:"w-full form-control form-input form-input-bordered",attrs:{type:"text"},domProps:{value:t.newKey},on:{input:function(e){e.target.composing||(t.newKey=e.target.value)}}})])])],1),t._v(" "),n("div",{staticClass:"bg-30 px-6 py-3 flex"},[n("div",{staticClass:"flex items-center ml-auto"},[n("button",{staticClass:"btn btn-link dim cursor-pointer text-80 ml-auto mr-6",attrs:{type:"button"},on:{click:function(e){return e.preventDefault(),t.handleClose(e)}}},[t._v("\n "+t._s(t.trans("Close"))+"\n ")]),t._v(" "),n("button",{staticClass:"btn btn-default btn-primary",attrs:{type:"submit"}},[t._v("\n "+t._s(t.trans("Confirm"))+"\n ")])])])])])},staticRenderFns:[]}},function(t,e,n){var r=n(0)(n(18),n(19),!1,null,null,null);t.exports=r.exports},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(1);e.default={mixins:[r.a],props:{localeKey:{type:String,required:!0},localeId:{type:Number,required:!0},widget:{type:Object,required:!0},url:{type:String,default:""}},data:function(){return{}},methods:{openMediaLibrary:function(){this.$emit("edit",{localeId:this.localeId,localeKey:this.localeKey}),this.widget.show()}}}},function(t,e){t.exports={render:function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{staticClass:"w-full h-auto flex items-center form-control form-input form-input-bordered p-0"},[n("input",{staticClass:"flex-1 outline-none form-control form-input shadow-none px-3",attrs:{type:"text"},domProps:{value:t.url}}),t._v(" "),n("button",{staticClass:"btn btn-default btn-primary",attrs:{type:"button"},on:{click:function(e){return e.preventDefault(),t.openMediaLibrary()}}},[t._v("\n "+t._s(t.trans("Choose"))+"\n ")])])},staticRenderFns:[]}},function(t,e){t.exports={render:function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",[n("heading",[t._v(t._s(t.trans("Translations Matrix")))]),t._v(" "),t.loading?n("loading-view"):n("div",[n("div",{staticClass:"mb-6 text-right"},[n("button",{staticClass:"btn btn-link dim cursor-pointer text-80",on:{click:function(e){e.preventDefault(),t.promptKeyModalOpened=!0}}},[t._v(t._s(t.trans("Add key")))]),t._v(" "),n("button",{staticClass:"ml-3 btn btn-default btn-primary text-white cursor-pointer text-80",on:{click:t.saveLabels}},[t._v(t._s(t.trans("Save")))])]),t._v(" "),n("card",[n("div",{staticClass:"overflow-hidden overflow-x-scroll overflow-y-auto relative"},[n("div",{staticClass:"translation-matrix"},[n("table",{staticClass:"table relative w-full"},[n("thead",[n("tr",[n("th",{staticClass:"text-center sticky top-0 border-rb z-10"},[t._v(t._s(t.trans("Label")))]),t._v(" "),t._l(t.locales,function(e){return n("th",{key:e.id,staticClass:"text-center sticky top-0 border-b"},[t._v("\n "+t._s(e.label)+" ("+t._s(e.iso)+")\n ")])}),t._v(" "),n("th",{staticClass:"sticky top-0 border-b"},[t._v(" ")])],2)]),t._v(" "),n("tbody",t._l(t.matrix,function(e,r){return n("tr",{key:r,staticClass:"p-3",attrs:{id:"tr__"+r}},[n("th",{staticClass:"sticky left-0 border-rb no-uppercase"},[t._v(t._s(r))]),t._v(" "),t._l(t.locales,function(o){return n("td",{key:r+"__"+o.id},[e[o.id]&&"text"===e[o.id].type?n("div",{staticClass:"py-1"},[e[o.id]?n("textarea",{staticClass:"w-full h-auto form-control form-input form-input-bordered py-2",attrs:{rows:"2",cols:"3",id:"textarea__"+r+"__"+o.id},domProps:{innerHTML:t._s(e[o.id].value)},on:{input:function(e){return t.updateLabel(r,o.id,e.target.value)}}}):t._e()]):t._e(),t._v(" "),e[o.id]&&"upload"===e[o.id].type?n("div",[n("cloudinary-upload",{attrs:{widget:t.cloudinaryWidget,"locale-key":r,"locale-id":o.id,url:e[o.id].value,id:"upload__"+r+"__"+o.id},on:{edit:function(e){return t.setCurrentEdit(e)}}})],1):t._e()])}),t._v(" "),n("td",{staticClass:"td-fit text-right pr-6 align-middle"},[n("button",{directives:[{name:"tooltip",rawName:"v-tooltip.click",value:t.trans("Delete"),expression:"trans('Delete')",modifiers:{click:!0}}],staticClass:"inline-flex appearance-none cursor-pointer text-70 hover:text-primary mr-3",on:{click:function(e){return e.preventDefault(),t.deleteKey(r)}}},[n("icon")],1)])],2)}),0)])])])]),t._v(" "),n("div",{staticClass:"mt-6 text-right"},[n("button",{staticClass:"btn btn-link dim cursor-pointer text-80",on:{click:function(e){e.preventDefault(),t.promptKeyModalOpened=!0}}},[t._v(t._s(t.trans("Add key")))]),t._v(" "),n("button",{staticClass:"ml-3 btn btn-default btn-primary text-white cursor-pointer text-80",on:{click:t.saveLabels}},[t._v(t._s(t.trans("Save")))])])],1),t._v(" "),n("portal",{attrs:{to:"modals",transition:"fade-transition"}},[t.promptKeyModalOpened?n("prompt-key-modal",{on:{confirm:t.addKey,close:function(e){t.promptKeyModalOpened=!1}}}):t._e()],1)],1)},staticRenderFns:[]}},function(t,e,n){var r=n(0)(n(24),n(29),!1,function(t){n(22)},null,null);t.exports=r.exports},function(t,e,n){var r=n(23);"string"==typeof r&&(r=[[t.i,r,""]]),r.locals&&(t.exports=r.locals);n(4)("29eb8d98",r,!0,{})},function(t,e,n){(t.exports=n(3)(!1)).push([t.i,'.nova-translation-field_index{display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-align:center;-ms-flex-align:center;align-items:center}.nova-translation-field_index div{margin-left:.2rem}.nova-translation-field_index div:first-child{margin-left:0}.nova-translation-field_index div:not(:last-child):after{content:"|"}.nova-translation-field_index div a{text-decoration:none}',""])},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(1),o=n(2),i=n(5),u=n.n(i);e.default={components:{CreateTranslationLink:u.a},mixins:[r.a,o.a],props:["field","resourceName","resourceId"]}},function(t,e,n){var r=n(26);"string"==typeof r&&(r=[[t.i,r,""]]),r.locals&&(t.exports=r.locals);n(4)("42e2ae0b",r,!0,{})},function(t,e,n){(t.exports=n(3)(!1)).push([t.i,"",""])},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(1),o=n(2);e.default={mixins:[r.a,o.a],props:["resourceName","resourceId","targetLocale"],computed:{url:function(){return"/nova-vendor/nova-translation/translate/"+this.resourceName+"/"+this.resourceId+"/locale-"+this.targetLocale.id}}}},function(t,e){t.exports={render:function(){var t=this.$createElement,e=this._self._c||t;return e("a",{staticClass:"block p-3 cursor-pointer no-underline text-70 hover:bg-30",attrs:{href:this.url,title:this.__("Translate to "+this.targetLocale.label)}},[e("span",{staticClass:"nova-translation--flag"},[this._v("\n "+this._s(this.targetLocale.label)+"\n ")])])},staticRenderFns:[]}},function(t,e){t.exports={render:function(){var t=this,e=t.$createElement,n=t._self._c||e;return t.field.value?n("div",{staticClass:"nova-translation-field_index"},[t._l(t.otherLocales,function(e){return t.isTranslated[e.id]?n("div",{key:"translation_"+e.id},[t.isTranslated[e.id]?n("router-link",{staticClass:"no-underline dim text-primary font-semibold",attrs:{to:{name:"detail",params:{resourceName:t.resourceName,resourceId:t.translations[e.id].translatable_id}},title:t.__("View in "+e.label)}},[n("span",{staticClass:"nova-translation--flag"},[t._v("\n "+t._s(e.iso)+"\n ")])]):t._e()],1):t._e()}),t._v(" "),t.hasTranslation?t._e():n("span",[t._v("—")])],2):t._e()},staticRenderFns:[]}},function(t,e,n){var r=n(0)(n(31),n(32),!1,null,null,null);t.exports=r.exports},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(1),o=n(2),i=n(5),u=n.n(i);e.default={components:{CreateTranslationLink:u.a},mixins:[r.a,o.a],props:["field","resource","resourceId","resourceName"]}},function(t,e){t.exports={render:function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{staticClass:"flex border-b border-40"},[n("div",{staticClass:"w-1/4 py-4"},[n("h4",{staticClass:"font-normal text-80"},[t._v(t._s(t.trans("Language")))])]),t._v(" "),n("div",{staticClass:"w-3/4 py-4 break-words flex"},[n("p",{staticClass:"text-90 font-bold"},[t._v("\n "+t._s(t.field.locales[t.field.value.locale_id].label)+"\n ")]),t._v(" "),n("div",{staticClass:"flex items-center ml-auto"},[n("dropdown",{staticClass:"ml-auto h-6 flex items-center dropdown-right"},[n("dropdown-trigger",{staticClass:"h-6 flex items-center text-xs bg-40 px-2 rounded active:outline-none active:shadow-outline focus:outline-none focus:shadow-outline"},[n("span",{staticClass:"text-90"},[t._v(t._s(t.trans("Translations")))])]),t._v(" "),n("dropdown-menu",{attrs:{slot:"menu",width:"200",direction:"rtl"},slot:"menu"},[n("ul",{staticClass:"list-reset"},t._l(t.otherLocales,function(e){return n("li",{key:"locale_"+e.id},[t.isTranslated[e.id]?n("router-link",{staticClass:"block p-3 cursor-pointer no-underline text-90 hover:bg-30",attrs:{to:{name:"detail",params:{resourceName:t.resourceName,resourceId:t.translations[e.id].translatable_id}},title:t.__("View in "+e.label)}},[n("span",{staticClass:"nova-translation--flag"},[t._v("\n "+t._s(e.label)+"\n ")])]):n("create-translation-link",{attrs:{"resource-name":t.resourceName,"resource-id":t.resourceId,"target-locale":e}})],1)}),0)])],1)],1)])])},staticRenderFns:[]}},function(t,e,n){var r=n(0)(n(34),n(36),!1,null,null,null);t.exports=r.exports},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(1),o=n(2),i=n(5),u=n.n(i),a=n(35);n.n(a);e.default={components:{CreateTranslationLink:u.a},mixins:[r.a,o.a,a.FormField,a.HandlesValidationErrors],props:["field","resourceId","resourceName"],computed:{isCreate:function(){return this.$route&&this.$route.name&&"create"===this.$route.name}},methods:{setInitialValue:function(){this.value="",this.field.value&&(this.value=this.field.value.locale_id+"|"+this.field.value.translation_id)},fill:function(t){}}}},function(t,e,n){var r;r=function(){return function(t){var e={};function n(r){if(e[r])return e[r].exports;var o=e[r]={i:r,l:!1,exports:{}};return t[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=t,n.c=e,n.i=function(t){return t},n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{configurable:!1,enumerable:!0,get:r})},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s=40)}([function(t,e,n){"use strict";var r=n(39),o=n(152),i=Object.prototype.toString;function u(t){return"[object Array]"===i.call(t)}function a(t){return null!==t&&"object"==typeof t}function s(t){return"[object Function]"===i.call(t)}function c(t,e){if(null!==t&&void 0!==t)if("object"!=typeof t&&(t=[t]),u(t))for(var n=0,r=t.length;n<r;n++)e.call(null,t[n],n,t);else for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&e.call(null,t[o],o,t)}t.exports={isArray:u,isArrayBuffer:function(t){return"[object ArrayBuffer]"===i.call(t)},isBuffer:o,isFormData:function(t){return"undefined"!=typeof FormData&&t instanceof FormData},isArrayBufferView:function(t){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer&&t.buffer instanceof ArrayBuffer},isString:function(t){return"string"==typeof t},isNumber:function(t){return"number"==typeof t},isObject:a,isUndefined:function(t){return void 0===t},isDate:function(t){return"[object Date]"===i.call(t)},isFile:function(t){return"[object File]"===i.call(t)},isBlob:function(t){return"[object Blob]"===i.call(t)},isFunction:s,isStream:function(t){return a(t)&&s(t.pipe)},isURLSearchParams:function(t){return"undefined"!=typeof URLSearchParams&&t instanceof URLSearchParams},isStandardBrowserEnv:function(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product)&&"undefined"!=typeof window&&"undefined"!=typeof document},forEach:c,merge:function t(){var e={};function n(n,r){"object"==typeof e[r]&&"object"==typeof n?e[r]=t(e[r],n):e[r]=n}for(var r=0,o=arguments.length;r<o;r++)c(arguments[r],n);return e},extend:function(t,e,n){return c(e,function(e,o){t[o]=n&&"function"==typeof e?r(e,n):e}),t},trim:function(t){return t.replace(/^\s*/,"").replace(/\s*$/,"")}}},function(t,e){var n=t.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)},function(t,e,n){var r=n(53)("wks"),o=n(58),i=n(1).Symbol,u="function"==typeof i;(t.exports=function(t){return r[t]||(r[t]=u&&i[t]||(u?i:o)("Symbol."+t))}).store=r},function(t,e){var n=t.exports={version:"2.5.7"};"number"==typeof __e&&(__e=n)},function(t,e,n){var r=n(9);t.exports=function(t){if(!r(t))throw TypeError(t+" is not an object!");return t}},function(t,e,n){t.exports=!n(23)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(t,e,n){var r=n(1),o=n(3),i=n(14),u=n(7),a=n(15),s=function(t,e,n){var c,f,l,p=t&s.F,h=t&s.G,d=t&s.S,v=t&s.P,g=t&s.B,y=t&s.W,m=h?o:o[e]||(o[e]={}),_=m.prototype,b=h?r:d?r[e]:(r[e]||{}).prototype;for(c in h&&(n=e),n)(f=!p&&b&&void 0!==b[c])&&a(m,c)||(l=f?b[c]:n[c],m[c]=h&&"function"!=typeof b[c]?n[c]:g&&f?i(l,r):y&&b[c]==l?function(t){var e=function(e,n,r){if(this instanceof t){switch(arguments.length){case 0:return new t;case 1:return new t(e);case 2:return new t(e,n)}return new t(e,n,r)}return t.apply(this,arguments)};return e.prototype=t.prototype,e}(l):v&&"function"==typeof l?i(Function.call,l):l,v&&((m.virtual||(m.virtual={}))[c]=l,t&s.R&&_&&!_[c]&&u(_,c,l)))};s.F=1,s.G=2,s.S=4,s.P=8,s.B=16,s.W=32,s.U=64,s.R=128,t.exports=s},function(t,e,n){var r=n(11),o=n(52);t.exports=n(5)?function(t,e,n){return r.f(t,e,o(1,n))}:function(t,e,n){return t[e]=n,t}},function(t,e){t.exports=function(t){var e=typeof t;return null!=t&&("object"==e||"function"==e)}},function(t,e){t.exports=function(t){return"object"==typeof t?null!==t:"function"==typeof t}},function(t,e){t.exports={}},function(t,e,n){var r=n(4),o=n(118),i=n(138),u=Object.defineProperty;e.f=n(5)?Object.defineProperty:function(t,e,n){if(r(t),e=i(e,!0),r(n),o)try{return u(t,e,n)}catch(t){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(t[e]=n.value),t}},function(t,e){t.exports=function(t){if("function"!=typeof t)throw TypeError(t+" is not a function!");return t}},function(t,e){var n={}.toString;t.exports=function(t){return n.call(t).slice(8,-1)}},function(t,e,n){var r=n(12);t.exports=function(t,e,n){if(r(t),void 0===e)return t;switch(n){case 1:return function(n){return t.call(e,n)};case 2:return function(n,r){return t.call(e,n,r)};case 3:return function(n,r,o){return t.call(e,n,r,o)}}return function(){return t.apply(e,arguments)}}},function(t,e){var n={}.hasOwnProperty;t.exports=function(t,e){return n.call(t,e)}},function(t,e,n){var r=n(30),o=n(172),i=n(179),u="[object Null]",a="[object Undefined]",s=r?r.toStringTag:void 0;t.exports=function(t){return null==t?void 0===t?a:u:s&&s in Object(t)?o(t):i(t)}},function(t,e,n){var r=n(60),o="object"==typeof self&&self&&self.Object===Object&&self,i=r||o||Function("return this")();t.exports=i},function(t,e){t.exports=function(t){return null!=t&&"object"==typeof t}},function(t,e,n){"use strict";(function(e){var r=n(0),o=n(105),i={"Content-Type":"application/x-www-form-urlencoded"};function u(t,e){!r.isUndefined(t)&&r.isUndefined(t["Content-Type"])&&(t["Content-Type"]=e)}var a,s={adapter:("undefined"!=typeof XMLHttpRequest?a=n(35):void 0!==e&&(a=n(35)),a),transformRequest:[function(t,e){return o(e,"Content-Type"),r.isFormData(t)||r.isArrayBuffer(t)||r.isBuffer(t)||r.isStream(t)||r.isFile(t)||r.isBlob(t)?t:r.isArrayBufferView(t)?t.buffer:r.isURLSearchParams(t)?(u(e,"application/x-www-form-urlencoded;charset=utf-8"),t.toString()):r.isObject(t)?(u(e,"application/json;charset=utf-8"),JSON.stringify(t)):t}],transformResponse:[function(t){if("string"==typeof t)try{t=JSON.parse(t)}catch(t){}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,validateStatus:function(t){return t>=200&&t<300}};s.headers={common:{Accept:"application/json, text/plain, */*"}},r.forEach(["delete","get","head"],function(t){s.headers[t]={}}),r.forEach(["post","put","patch"],function(t){s.headers[t]=r.merge(i)}),t.exports=s}).call(e,n(70))},function(t,e,n){"use strict";e.__esModule=!0;var r,o=n(109),i=(r=o)&&r.__esModule?r:{default:r};e.default=function(t,e,n){return e in t?(0,i.default)(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}},function(t,e){t.exports=function(t){if(void 0==t)throw TypeError("Can't call method on "+t);return t}},function(t,e,n){var r=n(9),o=n(1).document,i=r(o)&&r(o.createElement);t.exports=function(t){return i?o.createElement(t):{}}},function(t,e){t.exports=function(t){try{return!!t()}catch(t){return!0}}},function(t,e){t.exports=!0},function(t,e,n){"use strict";var r=n(12);t.exports.f=function(t){return new function(t){var e,n;this.promise=new t(function(t,r){if(void 0!==e||void 0!==n)throw TypeError("Bad Promise constructor");e=t,n=r}),this.resolve=r(e),this.reject=r(n)}(t)}},function(t,e,n){var r=n(11).f,o=n(15),i=n(2)("toStringTag");t.exports=function(t,e,n){t&&!o(t=n?t:t.prototype,i)&&r(t,i,{configurable:!0,value:e})}},function(t,e,n){var r=n(53)("keys"),o=n(58);t.exports=function(t){return r[t]||(r[t]=o(t))}},function(t,e){var n=Math.ceil,r=Math.floor;t.exports=function(t){return isNaN(t=+t)?0:(t>0?r:n)(t)}},function(t,e,n){var r=n(47),o=n(21);t.exports=function(t){return r(o(t))}},function(t,e,n){var r=n(17).Symbol;t.exports=r},function(t,e){t.exports=function(t){return t.webpackPolyfill||(t.deprecate=function(){},t.paths=[],t.children||(t.children=[]),Object.defineProperty(t,"loaded",{enumerable:!0,get:function(){return t.l}}),Object.defineProperty(t,"id",{enumerable:!0,get:function(){return t.i}}),t.webpackPolyfill=1),t}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.mapProps=void 0;var r,o=n(193),i=(r=o)&&r.__esModule?r:{default:r};var u={showHelpText:{type:Boolean,default:!1},shownViaNewRelationModal:{type:Boolean,default:!1},resourceId:{type:[Number,String]},resourceName:{type:String},field:{type:Object,required:!0},viaResource:{type:String,required:!1},viaResourceId:{type:[String,Number],required:!1},viaRelationship:{type:String,required:!1},shouldOverrideMeta:{type:Boolean,default:!1}};e.mapProps=function(t){return i.default.pick(u,t)}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=["1/2","1/3","2/3","1/4","3/4","1/5","2/5","3/5","4/5","1/6","5/6"]},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(150);Object.defineProperty(e,"default",{enumerable:!0,get:function(){return i(r).default}}),Object.defineProperty(e,"Form",{enumerable:!0,get:function(){return i(r).default}});var o=n(59);function i(t){return t&&t.__esModule?t:{default:t}}Object.defineProperty(e,"Errors",{enumerable:!0,get:function(){return i(o).default}})},function(t,e,n){"use strict";(function(e){var r=n(0),o=n(97),i=n(100),u=n(106),a=n(104),s=n(38),c="undefined"!=typeof window&&window.btoa&&window.btoa.bind(window)||n(99);t.exports=function(t){return new Promise(function(f,l){var p=t.data,h=t.headers;r.isFormData(p)&&delete h["Content-Type"];var d=new XMLHttpRequest,v="onreadystatechange",g=!1;if("test"===e.env.NODE_ENV||"undefined"==typeof window||!window.XDomainRequest||"withCredentials"in d||a(t.url)||(d=new window.XDomainRequest,v="onload",g=!0,d.onprogress=function(){},d.ontimeout=function(){}),t.auth){var y=t.auth.username||"",m=t.auth.password||"";h.Authorization="Basic "+c(y+":"+m)}if(d.open(t.method.toUpperCase(),i(t.url,t.params,t.paramsSerializer),!0),d.timeout=t.timeout,d[v]=function(){if(d&&(4===d.readyState||g)&&(0!==d.status||d.responseURL&&0===d.responseURL.indexOf("file:"))){var e="getAllResponseHeaders"in d?u(d.getAllResponseHeaders()):null,n={data:t.responseType&&"text"!==t.responseType?d.response:d.responseText,status:1223===d.status?204:d.status,statusText:1223===d.status?"No Content":d.statusText,headers:e,config:t,request:d};o(f,l,n),d=null}},d.onerror=function(){l(s("Network Error",t,null,d)),d=null},d.ontimeout=function(){l(s("timeout of "+t.timeout+"ms exceeded",t,"ECONNABORTED",d)),d=null},r.isStandardBrowserEnv()){var _=n(102),b=(t.withCredentials||a(t.url))&&t.xsrfCookieName?_.read(t.xsrfCookieName):void 0;b&&(h[t.xsrfHeaderName]=b)}if("setRequestHeader"in d&&r.forEach(h,function(t,e){void 0===p&&"content-type"===e.toLowerCase()?delete h[e]:d.setRequestHeader(e,t)}),t.withCredentials&&(d.withCredentials=!0),t.responseType)try{d.responseType=t.responseType}catch(e){if("json"!==t.responseType)throw e}"function"==typeof t.onDownloadProgress&&d.addEventListener("progress",t.onDownloadProgress),"function"==typeof t.onUploadProgress&&d.upload&&d.upload.addEventListener("progress",t.onUploadProgress),t.cancelToken&&t.cancelToken.promise.then(function(t){d&&(d.abort(),l(t),d=null)}),void 0===p&&(p=null),d.send(p)})}}).call(e,n(70))},function(t,e,n){"use strict";function r(t){this.message=t}r.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},r.prototype.__CANCEL__=!0,t.exports=r},function(t,e,n){"use strict";t.exports=function(t){return!(!t||!t.__CANCEL__)}},function(t,e,n){"use strict";var r=n(96);t.exports=function(t,e,n,o,i){var u=new Error(t);return r(u,e,n,o,i)}},function(t,e,n){"use strict";t.exports=function(t,e){return function(){for(var n=new Array(arguments.length),r=0;r<n.length;r++)n[r]=arguments[r];return t.apply(e,n)}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.mapProps=e.CardSizes=e.SingularOrPlural=e.Minimum=e.Capitalize=e.Inflector=e.Errors=e.TogglesTrashed=e.PreventsFormAbandonment=e.PerPageable=e.PerformsSearches=e.Paginatable=e.InteractsWithResourceInformation=e.InteractsWithQueryString=e.InteractsWithDates=e.HasCards=e.HandlesValidationErrors=e.FormField=e.Filterable=e.Deletable=e.BehavesAsPanel=void 0;var r=E(n(72)),o=E(n(73)),i=E(n(74)),u=E(n(75)),a=E(n(76)),s=E(n(77)),c=E(n(78)),f=E(n(79)),l=E(n(80)),p=E(n(81)),h=E(n(83)),d=E(n(82)),v=E(n(84)),g=E(n(85)),y=E(n(89)),m=E(n(33)),_=E(n(86)),b=E(n(87)),w=n(34),x=E(n(88)),j=n(32);function E(t){return t&&t.__esModule?t:{default:t}}e.BehavesAsPanel=r.default,e.Deletable=o.default,e.Filterable=i.default,e.FormField=u.default,e.HandlesValidationErrors=a.default,e.HasCards=s.default,e.InteractsWithDates=c.default,e.InteractsWithQueryString=f.default,e.InteractsWithResourceInformation=l.default,e.Paginatable=p.default,e.PerformsSearches=h.default,e.PerPageable=d.default,e.PreventsFormAbandonment=v.default,e.TogglesTrashed=g.default,e.Errors=w.Errors,e.Inflector=y.default,e.Capitalize=_.default,e.Minimum=b.default,e.SingularOrPlural=x.default,e.CardSizes=m.default,e.mapProps=j.mapProps},function(t,e,n){t.exports={default:n(113),__esModule:!0}},function(t,e,n){"use strict";e.__esModule=!0;var r,o=n(41),i=(r=o)&&r.__esModule?r:{default:r};e.default=function(t){return function(){var e=t.apply(this,arguments);return new i.default(function(t,n){return function r(o,u){try{var a=e[o](u),s=a.value}catch(t){return void n(t)}if(!a.done)return i.default.resolve(s).then(function(t){r("next",t)},function(t){r("throw",t)});t(s)}("next")})}}},function(t,e,n){t.exports=n(199)},function(t,e,n){var r=n(13),o=n(2)("toStringTag"),i="Arguments"==r(function(){return arguments}());t.exports=function(t){var e,n,u;return void 0===t?"Undefined":null===t?"Null":"string"==typeof(n=function(t,e){try{return t[e]}catch(t){}}(e=Object(t),o))?n:i?r(e):"Object"==(u=r(e))&&"function"==typeof e.callee?"Arguments":u}},function(t,e){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(t,e,n){var r=n(1).document;t.exports=r&&r.documentElement},function(t,e,n){var r=n(13);t.exports=Object("z").propertyIsEnumerable(0)?Object:function(t){return"String"==r(t)?t.split(""):Object(t)}},function(t,e,n){"use strict";var r=n(24),o=n(6),i=n(134),u=n(7),a=n(10),s=n(122),c=n(26),f=n(130),l=n(2)("iterator"),p=!([].keys&&"next"in[].keys()),h=function(){return this};t.exports=function(t,e,n,d,v,g,y){s(n,e,d);var m,_,b,w=function(t){if(!p&&t in O)return O[t];switch(t){case"keys":case"values":return function(){return new n(this,t)}}return function(){return new n(this,t)}},x=e+" Iterator",j="values"==v,E=!1,O=t.prototype,S=O[l]||O["@@iterator"]||v&&O[v],R=S||w(v),T=v?j?w("entries"):R:void 0,k="Array"==e&&O.entries||S;if(k&&(b=f(k.call(new t)))!==Object.prototype&&b.next&&(c(b,x,!0),r||"function"==typeof b[l]||u(b,l,h)),j&&S&&"values"!==S.name&&(E=!0,R=function(){return S.call(this)}),r&&!y||!p&&!E&&O[l]||u(O,l,R),a[e]=R,a[x]=h,v)if(m={values:j?R:w("values"),keys:g?R:w("keys"),entries:T},y)for(_ in m)_ in O||i(O,_,m[_]);else o(o.P+o.F*(p||E),e,m);return m}},function(t,e,n){var r=n(131),o=n(45);t.exports=Object.keys||function(t){return r(t,o)}},function(t,e){t.exports=function(t){try{return{e:!1,v:t()}}catch(t){return{e:!0,v:t}}}},function(t,e,n){var r=n(4),o=n(9),i=n(25);t.exports=function(t,e){if(r(t),o(e)&&e.constructor===t)return e;var n=i.f(t);return(0,n.resolve)(e),n.promise}},function(t,e){t.exports=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}}},function(t,e,n){var r=n(3),o=n(1),i=o["__core-js_shared__"]||(o["__core-js_shared__"]={});(t.exports=function(t,e){return i[t]||(i[t]=void 0!==e?e:{})})("versions",[]).push({version:r.version,mode:n(24)?"pure":"global",copyright:"© 2018 Denis Pushkarev (zloirock.ru)"})},function(t,e,n){var r=n(4),o=n(12),i=n(2)("species");t.exports=function(t,e){var n,u=r(t).constructor;return void 0===u||void 0==(n=r(u)[i])?e:o(n)}},function(t,e,n){var r,o,i,u=n(14),a=n(119),s=n(46),c=n(22),f=n(1),l=f.process,p=f.setImmediate,h=f.clearImmediate,d=f.MessageChannel,v=f.Dispatch,g=0,y={},m=function(){var t=+this;if(y.hasOwnProperty(t)){var e=y[t];delete y[t],e()}},_=function(t){m.call(t.data)};p&&h||(p=function(t){for(var e=[],n=1;arguments.length>n;)e.push(arguments[n++]);return y[++g]=function(){a("function"==typeof t?t:Function(t),e)},r(g),g},h=function(t){delete y[t]},"process"==n(13)(l)?r=function(t){l.nextTick(u(m,t,1))}:v&&v.now?r=function(t){v.now(u(m,t,1))}:d?(i=(o=new d).port2,o.port1.onmessage=_,r=u(i.postMessage,i,1)):f.addEventListener&&"function"==typeof postMessage&&!f.importScripts?(r=function(t){f.postMessage(t+"","*")},f.addEventListener("message",_,!1)):r="onreadystatechange"in c("script")?function(t){s.appendChild(c("script")).onreadystatechange=function(){s.removeChild(this),m.call(t)}}:function(t){setTimeout(u(m,t,1),0)}),t.exports={set:p,clear:h}},function(t,e,n){var r=n(28),o=Math.min;t.exports=function(t){return t>0?o(r(t),9007199254740991):0}},function(t,e,n){var r=n(21);t.exports=function(t){return Object(r(t))}},function(t,e){var n=0,r=Math.random();t.exports=function(t){return"Symbol(".concat(void 0===t?"":t,")_",(++n+r).toString(36))}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}();var o=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.record(e)}return r(t,[{key:"all",value:function(){return this.errors}},{key:"has",value:function(t){var e=this.errors.hasOwnProperty(t);e||(e=Object.keys(this.errors).filter(function(e){return e.startsWith(t+".")||e.startsWith(t+"[")}).length>0);return e}},{key:"first",value:function(t){return this.get(t)[0]}},{key:"get",value:function(t){return this.errors[t]||[]}},{key:"any",value:function(){return Object.keys(this.errors).length>0}},{key:"record",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.errors=t}},{key:"clear",value:function(t){if(t){var e=Object.assign({},this.errors);Object.keys(e).filter(function(e){return e===t||e.startsWith(t+".")||e.startsWith(t+"[")}).forEach(function(t){return delete e[t]}),this.errors=e}else this.errors={}}}]),t}();e.default=o},function(t,e,n){(function(e){var n="object"==typeof e&&e&&e.Object===Object&&e;t.exports=n}).call(e,n(71))},function(t,e){var n=RegExp("[\\u200d\\ud800-\\udfff\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff\\ufe0e\\ufe0f]");t.exports=function(t){return n.test(t)}},function(t,e){var n=9007199254740991,r=/^(?:0|[1-9]\d*)$/;t.exports=function(t,e){var o=typeof t;return!!(e=null==e?n:e)&&("number"==o||"symbol"!=o&&r.test(t))&&t>-1&&t%1==0&&t<e}},function(t,e){t.exports=function(t,e){return t===e||t!=t&&e!=e}},function(t,e){t.exports=function(t){return t}},function(t,e){var n=Array.isArray;t.exports=n},function(t,e,n){var r=n(67),o=n(68);t.exports=function(t){return null!=t&&o(t.length)&&!r(t)}},function(t,e,n){var r=n(16),o=n(8),i="[object AsyncFunction]",u="[object Function]",a="[object GeneratorFunction]",s="[object Proxy]";t.exports=function(t){if(!o(t))return!1;var e=r(t);return e==u||e==a||e==i||e==s}},function(t,e){var n=9007199254740991;t.exports=function(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=n}},function(t,e,n){var r=n(16),o=n(18),i="[object Symbol]";t.exports=function(t){return"symbol"==typeof t||o(t)&&r(t)==i}},function(t,e){var n,r,o=t.exports={};function i(){throw new Error("setTimeout has not been defined")}function u(){throw new Error("clearTimeout has not been defined")}function a(t){if(n===setTimeout)return setTimeout(t,0);if((n===i||!n)&&setTimeout)return n=setTimeout,setTimeout(t,0);try{return n(t,0)}catch(e){try{return n.call(null,t,0)}catch(e){return n.call(this,t,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:i}catch(t){n=i}try{r="function"==typeof clearTimeout?clearTimeout:u}catch(t){r=u}}();var s,c=[],f=!1,l=-1;function p(){f&&s&&(f=!1,s.length?c=s.concat(c):l=-1,c.length&&h())}function h(){if(!f){var t=a(p);f=!0;for(var e=c.length;e;){for(s=c,c=[];++l<e;)s&&s[l].run();l=-1,e=c.length}s=null,f=!1,function(t){if(r===clearTimeout)return clearTimeout(t);if((r===u||!r)&&clearTimeout)return r=clearTimeout,clearTimeout(t);try{r(t)}catch(e){try{return r.call(null,t)}catch(e){return r.call(this,t)}}}(t)}}function d(t,e){this.fun=t,this.array=e}function v(){}o.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];c.push(new d(t,e)),1!==c.length||f||a(h)},d.prototype.run=function(){this.fun.apply(null,this.array)},o.title="browser",o.browser=!0,o.env={},o.argv=[],o.version="",o.versions={},o.on=v,o.addListener=v,o.once=v,o.off=v,o.removeListener=v,o.removeAllListeners=v,o.emit=v,o.prependListener=v,o.prependOnceListener=v,o.listeners=function(t){return[]},o.binding=function(t){throw new Error("process.binding is not supported")},o.cwd=function(){return"/"},o.chdir=function(t){throw new Error("process.chdir is not supported")},o.umask=function(){return 0}},function(t,e){var n;n=function(){return this}();try{n=n||Function("return this")()||(0,eval)("this")}catch(t){"object"==typeof window&&(n=window)}t.exports=n},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default={props:["resourceName","resourceId","resource","panel"],methods:{actionExecuted:function(){this.$emit("actionExecuted")}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,o=n(110),i=(r=o)&&r.__esModule?r:{default:r};function u(t){return _.map(t,function(t){return t.id.value})}e.default={methods:{openDeleteModal:function(){this.deleteModalOpen=!0},deleteResources:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;return this.viaManyToMany?this.detachResources(t):Nova.request({url:"/nova-api/"+this.resourceName,method:"delete",params:(0,i.default)({},this.queryString,{resources:u(t)})}).then(n||function(){e.deleteModalOpen=!1,e.getResources()})},deleteSelectedResources:function(){this.deleteResources(this.selectedResources)},deleteAllMatchingResources:function(){var t=this;return this.viaManyToMany?this.detachAllMatchingResources():Nova.request({url:this.deleteAllMatchingResourcesEndpoint,method:"delete",params:(0,i.default)({},this.queryString,{resources:"all"})}).then(function(){t.deleteModalOpen=!1,t.getResources()})},detachResources:function(t){var e=this;return Nova.request({url:"/nova-api/"+this.resourceName+"/detach",method:"delete",params:(0,i.default)({},this.queryString,{resources:u(t)},{pivots:function(t){return _.filter(_.map(t,function(t){return t.id.pivotValue}))}(t)})}).then(function(){e.deleteModalOpen=!1,e.getResources()})},detachAllMatchingResources:function(){var t=this;return Nova.request({url:"/nova-api/"+this.resourceName+"/detach",method:"delete",params:(0,i.default)({},this.queryString,{resources:"all"})}).then(function(){t.deleteModalOpen=!1,t.getResources()})},forceDeleteResources:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;return Nova.request({url:"/nova-api/"+this.resourceName+"/force",method:"delete",params:(0,i.default)({},this.queryString,{resources:u(t)})}).then(n||function(){e.deleteModalOpen=!1,e.getResources()})},forceDeleteSelectedResources:function(){this.forceDeleteResources(this.selectedResources)},forceDeleteAllMatchingResources:function(){var t=this;return Nova.request({url:this.forceDeleteSelectedResourcesEndpoint,method:"delete",params:(0,i.default)({},this.queryString,{resources:"all"})}).then(function(){t.deleteModalOpen=!1,t.getResources()})},restoreResources:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;return Nova.request({url:"/nova-api/"+this.resourceName+"/restore",method:"put",params:(0,i.default)({},this.queryString,{resources:u(t)})}).then(n||function(){e.restoreModalOpen=!1,e.getResources()})},restoreSelectedResources:function(){this.restoreResources(this.selectedResources)},restoreAllMatchingResources:function(){var t=this;return Nova.request({url:this.restoreAllMatchingResourcesEndpoint,method:"put",params:(0,i.default)({},this.queryString,{resources:"all"})}).then(function(){t.restoreModalOpen=!1,t.getResources()})}},computed:{deleteAllMatchingResourcesEndpoint:function(){return this.lens?"/nova-api/"+this.resourceName+"/lens/"+this.lens:"/nova-api/"+this.resourceName},forceDeleteSelectedResourcesEndpoint:function(){return this.lens?"/nova-api/"+this.resourceName+"/lens/"+this.lens+"/force":"/nova-api/"+this.resourceName+"/force"},restoreAllMatchingResourcesEndpoint:function(){return this.lens?"/nova-api/"+this.resourceName+"/lens/"+this.lens+"/restore":"/nova-api/"+this.resourceName+"/restore"},queryString:function(){return{search:this.currentSearch,filters:this.encodedFilters,trashed:this.currentTrashed,viaResource:this.viaResource,viaResourceId:this.viaResourceId,viaRelationship:this.viaRelationship}}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=u(n(43)),o=u(n(20)),i=u(n(42));function u(t){return t&&t.__esModule?t:{default:t}}e.default={methods:{clearSelectedFilters:function(){var t=(0,i.default)(r.default.mark(function t(e){var n;return r.default.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(!e){t.next=5;break}return t.next=3,this.$store.dispatch(this.resourceName+"/resetFilterState",{resourceName:this.resourceName,lens:e});case 3:t.next=7;break;case 5:return t.next=7,this.$store.dispatch(this.resourceName+"/resetFilterState",{resourceName:this.resourceName});case 7:this.updateQueryString((n={},(0,o.default)(n,this.pageParameter,1),(0,o.default)(n,this.filterParameter,""),n));case 8:case"end":return t.stop()}},t,this)}));return function(e){return t.apply(this,arguments)}}(),filterChanged:function(){var t;this.updateQueryString((t={},(0,o.default)(t,this.pageParameter,1),(0,o.default)(t,this.filterParameter,this.$store.getters[this.resourceName+"/currentEncodedFilters"]),t))},initializeFilters:function(){var t=(0,i.default)(r.default.mark(function t(e){return r.default.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return this.$store.commit(this.resourceName+"/clearFilters"),t.next=3,this.$store.dispatch(this.resourceName+"/fetchFilters",{resourceName:this.resourceName,viaResource:this.viaResource,viaResourceId:this.viaResourceId,viaRelationship:this.viaRelationship,lens:e});case 3:return t.next=5,this.initializeState(e);case 5:case"end":return t.stop()}},t,this)}));return function(e){return t.apply(this,arguments)}}(),initializeState:function(){var t=(0,i.default)(r.default.mark(function t(e){return r.default.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(!this.initialEncodedFilters){t.next=5;break}return t.next=3,this.$store.dispatch(this.resourceName+"/initializeCurrentFilterValuesFromQueryString",this.initialEncodedFilters);case 3:t.next=7;break;case 5:return t.next=7,this.$store.dispatch(this.resourceName+"/resetFilterState",{resourceName:this.resourceName,lens:e});case 7:case"end":return t.stop()}},t,this)}));return function(e){return t.apply(this,arguments)}}()},computed:{filterParameter:function(){return this.resourceName+"_filter"}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(32);e.default={props:(0,r.mapProps)(["shownViaNewRelationModal","field","viaResource","viaResourceId","viaRelationship","resourceName","showHelpText"]),data:function(){return{value:""}},mounted:function(){var t=this;this.setInitialValue(),this.field.fill=this.fill,Nova.$on(this.field.attribute+"-value",function(e){t.value=e})},destroyed:function(){Nova.$off(this.field.attribute+"-value")},methods:{setInitialValue:function(){this.value=void 0!==this.field.value&&null!==this.field.value?this.field.value:""},fill:function(t){t.append(this.field.attribute,String(this.value))},handleChange:function(t){this.value=t.target.value,this.field&&Nova.$emit(this.field.attribute+"-change",this.value)}},computed:{isReadonly:function(){return this.field.readonly||_.get(this.field,"extraAttributes.readonly")}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(34);e.default={props:{errors:{default:function(){return new r.Errors}}},data:function(){return{errorClass:"border-danger"}},computed:{errorClasses:function(){return this.hasError?[this.errorClass]:[]},fieldAttribute:function(){return this.field.attribute},validationKey:function(){return this.field.validationKey},hasError:function(){return this.errors.has(this.validationKey)},firstError:function(){if(this.hasError)return this.errors.first(this.validationKey)}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=u(n(43)),o=u(n(42)),i=u(n(33));function u(t){return t&&t.__esModule?t:{default:t}}e.default={props:{loadCards:{type:Boolean,default:!0}},data:function(){return{cards:[]}},created:function(){this.fetchCards()},watch:{cardsEndpoint:function(){this.fetchCards()}},methods:{fetchCards:function(){var t=(0,o.default)(r.default.mark(function t(){var e,n;return r.default.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(!this.loadCards){t.next=6;break}return t.next=3,Nova.request().get(this.cardsEndpoint,{params:this.extraCardParams});case 3:e=t.sent,n=e.data,this.cards=n;case 6:case"end":return t.stop()}},t,this)}));return function(){return t.apply(this,arguments)}}()},computed:{shouldShowCards:function(){return this.cards.length>0},smallCards:function(){return _.filter(this.cards,function(t){return-1!==i.default.indexOf(t.width)})},largeCards:function(){return _.filter(this.cards,function(t){return"full"==t.width})},extraCardParams:function(){return null}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default={methods:{toAppTimezone:function(t){return t?moment.tz(t,this.userTimezone).clone().tz(Nova.config.timezone).format("YYYY-MM-DD HH:mm:ss"):t},fromAppTimezone:function(t){return t?moment.tz(t,Nova.config.timezone).clone().tz(this.userTimezone).format("YYYY-MM-DD HH:mm:ss"):t},localizeDateTimeField:function(t){if(!t.value)return t.value;var e=moment.tz(t.value,Nova.config.timezone).clone().tz(this.userTimezone);return t.format?e.format(t.format):this.usesTwelveHourTime?e.format("YYYY-MM-DD h:mm:ss A"):e.format("YYYY-MM-DD HH:mm:ss")},localizeDateField:function(t){if(!t.value)return t.value;var e=moment.tz(t.value,Nova.config.timezone).clone().tz(this.userTimezone);return t.format?e.format(t.format):e.format("YYYY-MM-DD")}},computed:{userTimezone:function(){return Nova.config.userTimezone?Nova.config.userTimezone:moment.tz.guess()},usesTwelveHourTime:function(){return _.endsWith((new Date).toLocaleString(),"AM")||_.endsWith((new Date).toLocaleString(),"PM")}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,o=n(188),i=(r=o)&&r.__esModule?r:{default:r};e.default={methods:{updateQueryString:function(t){this.$router.push({query:(0,i.default)(t,this.$route.query)}).catch(function(t){if("NavigationDuplicated"!=t.name)throw t})}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default={computed:{resourceInformation:function(){var t=this;return _.find(Nova.config.resources,function(e){return e.uriKey==t.resourceName})},viaResourceInformation:function(){var t=this;if(this.viaResource)return _.find(Nova.config.resources,function(e){return e.uriKey==t.viaResource})},authorizedToCreate:function(){return this.resourceInformation.authorizedToCreate}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,o=n(20),i=(r=o)&&r.__esModule?r:{default:r};e.default={methods:{selectPreviousPage:function(){this.updateQueryString((0,i.default)({},this.pageParameter,this.currentPage-1))},selectNextPage:function(){this.updateQueryString((0,i.default)({},this.pageParameter,this.currentPage+1))}},computed:{currentPage:function(){return parseInt(this.$route.query[this.pageParameter]||1)}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,o=n(20),i=(r=o)&&r.__esModule?r:{default:r};e.default={data:function(){return{perPage:25}},methods:{initializePerPageFromQueryString:function(){this.perPage=this.currentPerPage},perPageChanged:function(){this.updateQueryString((0,i.default)({},this.perPageParameter,this.perPage))}},computed:{currentPerPage:function(){return this.$route.query[this.perPageParameter]||25}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,o=n(187),i=(r=o)&&r.__esModule?r:{default:r};e.default={data:function(){return{search:"",selectedResource:"",availableResources:[]}},methods:{selectResource:function(t){this.selectedResource=t,this.field&&Nova.$emit(this.field.attribute+"-change",this.selectedResource.value)},handleSearchCleared:function(){this.availableResources=[]},clearSelection:function(){this.selectedResource="",this.availableResources=[],this.field&&Nova.$emit(this.field.attribute+"-change",null)},performSearch:function(t){var e=this;this.search=t;var n=t.trim();""!=n&&this.debouncer(function(){e.getAvailableResources(n)},500)},debouncer:(0,i.default)(function(t){return t()},500)}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default={beforeRouteLeave:function(t,e,n){this.canLeave?n():window.confirm(this.__("Do you really want to leave? You have unsaved changes."))?n():n(!1)},data:function(){return{canLeave:!0}},methods:{updateFormStatus:function(){this.canLeave=!1}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default={data:function(){return{withTrashed:!1}},methods:{toggleWithTrashed:function(){this.withTrashed=!this.withTrashed},enableWithTrashed:function(){this.withTrashed=!0},disableWithTrashed:function(){this.withTrashed=!1}}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t){return(0,i.default)(t)};var r,o=n(198),i=(r=o)&&r.__esModule?r:{default:r}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,o=n(41),i=(r=o)&&r.__esModule?r:{default:r};e.default=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:100;return i.default.all([t,new i.default(function(t){setTimeout(function(){return t()},e)})]).then(function(t){return t[0]})}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=function(t,e){if(null==t.match(/^(.*)[A-Za-zÀ-ÖØ-öø-ÿ]$/))return t;if(t>1||0==t)return r.Inflector.pluralize(e);return r.Inflector.singularize(e)};var r=n(40)},function(t,e,n){"use strict";var r={uncountableWords:["equipment","information","rice","money","species","series","fish","sheep","moose","deer","news"],pluralRules:[[new RegExp("(m)an$","gi"),"$1en"],[new RegExp("(pe)rson$","gi"),"$1ople"],[new RegExp("(child)$","gi"),"$1ren"],[new RegExp("^(ox)$","gi"),"$1en"],[new RegExp("(ax|test)is$","gi"),"$1es"],[new RegExp("(octop|vir)us$","gi"),"$1i"],[new RegExp("(alias|status)$","gi"),"$1es"],[new RegExp("(bu)s$","gi"),"$1ses"],[new RegExp("(buffal|tomat|potat)o$","gi"),"$1oes"],[new RegExp("([ti])um$","gi"),"$1a"],[new RegExp("sis$","gi"),"ses"],[new RegExp("(?:([^f])fe|([lr])f)$","gi"),"$1$2ves"],[new RegExp("(hive)$","gi"),"$1s"],[new RegExp("([^aeiouy]|qu)y$","gi"),"$1ies"],[new RegExp("(x|ch|ss|sh)$","gi"),"$1es"],[new RegExp("(matr|vert|ind)ix|ex$","gi"),"$1ices"],[new RegExp("([m|l])ouse$","gi"),"$1ice"],[new RegExp("(quiz)$","gi"),"$1zes"],[new RegExp("s$","gi"),"s"],[new RegExp("$","gi"),"s"]],singularRules:[[new RegExp("(m)en$","gi"),"$1an"],[new RegExp("(pe)ople$","gi"),"$1rson"],[new RegExp("(child)ren$","gi"),"$1"],[new RegExp("([ti])a$","gi"),"$1um"],[new RegExp("((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$","gi"),"$1$2sis"],[new RegExp("(hive)s$","gi"),"$1"],[new RegExp("(tive)s$","gi"),"$1"],[new RegExp("(curve)s$","gi"),"$1"],[new RegExp("([lr])ves$","gi"),"$1f"],[new RegExp("([^fo])ves$","gi"),"$1fe"],[new RegExp("([^aeiouy]|qu)ies$","gi"),"$1y"],[new RegExp("(s)eries$","gi"),"$1eries"],[new RegExp("(m)ovies$","gi"),"$1ovie"],[new RegExp("(x|ch|ss|sh)es$","gi"),"$1"],[new RegExp("([m|l])ice$","gi"),"$1ouse"],[new RegExp("(bus)es$","gi"),"$1"],[new RegExp("(o)es$","gi"),"$1"],[new RegExp("(shoe)s$","gi"),"$1"],[new RegExp("(cris|ax|test)es$","gi"),"$1is"],[new RegExp("(octop|vir)i$","gi"),"$1us"],[new RegExp("(alias|status)es$","gi"),"$1"],[new RegExp("^(ox)en","gi"),"$1"],[new RegExp("(vert|ind)ices$","gi"),"$1ex"],[new RegExp("(matr)ices$","gi"),"$1ix"],[new RegExp("(quiz)zes$","gi"),"$1"],[new RegExp("s$","gi"),""]],nonTitlecasedWords:["and","or","nor","a","an","the","so","but","to","of","at","by","from","into","on","onto","off","out","in","over","with","for"],idSuffix:new RegExp("(_ids|_id)$","g"),underbar:new RegExp("_","g"),spaceOrUnderbar:new RegExp("[ _]","g"),uppercase:new RegExp("([A-Z])","g"),underbarPrefix:new RegExp("^_"),applyRules:function(t,e,n,r){if(r)t=r;else if(!(n.indexOf(t.toLowerCase())>-1))for(var o=0;o<e.length;o++)if(t.match(e[o][0])){t=t.replace(e[o][0],e[o][1]);break}return t},pluralize:function(t,e){return this.applyRules(t,this.pluralRules,this.uncountableWords,e)},singularize:function(t,e){return this.applyRules(t,this.singularRules,this.uncountableWords,e)},camelize:function(t,e){for(var n=t.split("/"),r=0;r<n.length;r++){for(var o=n[r].split("_"),i=e&&r+1===n.length?1:0;i<o.length;i++)o[i]=o[i].charAt(0).toUpperCase()+o[i].substring(1);n[r]=o.join("")}(t=n.join("::"),!0===e)&&(t=t.charAt(0).toLowerCase()+t.slice(1));return t},underscore:function(t){for(var e=t.split("::"),n=0;n<e.length;n++)e[n]=e[n].replace(this.uppercase,"_$1"),e[n]=e[n].replace(this.underbarPrefix,"");return t=e.join("/").toLowerCase()},humanize:function(t,e){return t=(t=(t=t.toLowerCase()).replace(this.idSuffix,"")).replace(this.underbar," "),e||(t=this.capitalize(t)),t},capitalize:function(t){return t=(t=t.toLowerCase()).substring(0,1).toUpperCase()+t.substring(1)},dasherize:function(t){return t=t.replace(this.spaceOrUnderbar,"-")},camel2words:function(t,e){!0===e?(t=this.camelize(t),t=this.underscore(t)):t=t.toLowerCase();for(var n=(t=t.replace(this.underbar," ")).split(" "),r=0;r<n.length;r++){for(var o=n[r].split("-"),i=0;i<o.length;i++)this.nonTitlecasedWords.indexOf(o[i].toLowerCase())<0&&(o[i]=this.capitalize(o[i]));n[r]=o.join("-")}return t=(t=n.join(" ")).substring(0,1).toUpperCase()+t.substring(1)},demodulize:function(t){var e=t.split("::");return t=e[e.length-1]},tableize:function(t){return t=this.pluralize(this.underscore(t))},classify:function(t){return t=this.singularize(this.camelize(t))},foreignKey:function(t,e){return t=this.underscore(this.demodulize(t))+(e?"":"_")+"id"},ordinalize:function(t){for(var e=t.split(" "),n=0;n<e.length;n++){if(NaN===parseInt(e[n])){var r=e[n].substring(e[n].length-2),o=e[n].substring(e[n].length-1),i="th";"11"!=r&&"12"!=r&&"13"!=r&&("1"===o?i="st":"2"===o?i="nd":"3"===o&&(i="rd")),e[n]+=i}}return t=e.join(" ")}};t.exports=r},function(t,e,n){t.exports=n(91)},function(t,e,n){"use strict";var r=n(0),o=n(39),i=n(93),u=n(19);function a(t){var e=new i(t),n=o(i.prototype.request,e);return r.extend(n,i.prototype,e),r.extend(n,e),n}var s=a(u);s.Axios=i,s.create=function(t){return a(r.merge(u,t))},s.Cancel=n(36),s.CancelToken=n(92),s.isCancel=n(37),s.all=function(t){return Promise.all(t)},s.spread=n(107),t.exports=s,t.exports.default=s},function(t,e,n){"use strict";var r=n(36);function o(t){if("function"!=typeof t)throw new TypeError("executor must be a function.");var e;this.promise=new Promise(function(t){e=t});var n=this;t(function(t){n.reason||(n.reason=new r(t),e(n.reason))})}o.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},o.source=function(){var t;return{token:new o(function(e){t=e}),cancel:t}},t.exports=o},function(t,e,n){"use strict";var r=n(19),o=n(0),i=n(94),u=n(95);function a(t){this.defaults=t,this.interceptors={request:new i,response:new i}}a.prototype.request=function(t){"string"==typeof t&&(t=o.merge({url:arguments[0]},arguments[1])),(t=o.merge(r,{method:"get"},this.defaults,t)).method=t.method.toLowerCase();var e=[u,void 0],n=Promise.resolve(t);for(this.interceptors.request.forEach(function(t){e.unshift(t.fulfilled,t.rejected)}),this.interceptors.response.forEach(function(t){e.push(t.fulfilled,t.rejected)});e.length;)n=n.then(e.shift(),e.shift());return n},o.forEach(["delete","get","head","options"],function(t){a.prototype[t]=function(e,n){return this.request(o.merge(n||{},{method:t,url:e}))}}),o.forEach(["post","put","patch"],function(t){a.prototype[t]=function(e,n,r){return this.request(o.merge(r||{},{method:t,url:e,data:n}))}}),t.exports=a},function(t,e,n){"use strict";var r=n(0);function o(){this.handlers=[]}o.prototype.use=function(t,e){return this.handlers.push({fulfilled:t,rejected:e}),this.handlers.length-1},o.prototype.eject=function(t){this.handlers[t]&&(this.handlers[t]=null)},o.prototype.forEach=function(t){r.forEach(this.handlers,function(e){null!==e&&t(e)})},t.exports=o},function(t,e,n){"use strict";var r=n(0),o=n(98),i=n(37),u=n(19),a=n(103),s=n(101);function c(t){t.cancelToken&&t.cancelToken.throwIfRequested()}t.exports=function(t){return c(t),t.baseURL&&!a(t.url)&&(t.url=s(t.baseURL,t.url)),t.headers=t.headers||{},t.data=o(t.data,t.headers,t.transformRequest),t.headers=r.merge(t.headers.common||{},t.headers[t.method]||{},t.headers||{}),r.forEach(["delete","get","head","post","put","patch","common"],function(e){delete t.headers[e]}),(t.adapter||u.adapter)(t).then(function(e){return c(t),e.data=o(e.data,e.headers,t.transformResponse),e},function(e){return i(e)||(c(t),e&&e.response&&(e.response.data=o(e.response.data,e.response.headers,t.transformResponse))),Promise.reject(e)})}},function(t,e,n){"use strict";t.exports=function(t,e,n,r,o){return t.config=e,n&&(t.code=n),t.request=r,t.response=o,t}},function(t,e,n){"use strict";var r=n(38);t.exports=function(t,e,n){var o=n.config.validateStatus;n.status&&o&&!o(n.status)?e(r("Request failed with status code "+n.status,n.config,null,n.request,n)):t(n)}},function(t,e,n){"use strict";var r=n(0);t.exports=function(t,e,n){return r.forEach(n,function(n){t=n(t,e)}),t}},function(t,e,n){"use strict";var r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function o(){this.message="String contains an invalid character"}o.prototype=new Error,o.prototype.code=5,o.prototype.name="InvalidCharacterError",t.exports=function(t){for(var e,n,i=String(t),u="",a=0,s=r;i.charAt(0|a)||(s="=",a%1);u+=s.charAt(63&e>>8-a%1*8)){if((n=i.charCodeAt(a+=.75))>255)throw new o;e=e<<8|n}return u}},function(t,e,n){"use strict";var r=n(0);function o(t){return encodeURIComponent(t).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}t.exports=function(t,e,n){if(!e)return t;var i;if(n)i=n(e);else if(r.isURLSearchParams(e))i=e.toString();else{var u=[];r.forEach(e,function(t,e){null!==t&&void 0!==t&&(r.isArray(t)?e+="[]":t=[t],r.forEach(t,function(t){r.isDate(t)?t=t.toISOString():r.isObject(t)&&(t=JSON.stringify(t)),u.push(o(e)+"="+o(t))}))}),i=u.join("&")}return i&&(t+=(-1===t.indexOf("?")?"?":"&")+i),t}},function(t,e,n){"use strict";t.exports=function(t,e){return e?t.replace(/\/+$/,"")+"/"+e.replace(/^\/+/,""):t}},function(t,e,n){"use strict";var r=n(0);t.exports=r.isStandardBrowserEnv()?{write:function(t,e,n,o,i,u){var a=[];a.push(t+"="+encodeURIComponent(e)),r.isNumber(n)&&a.push("expires="+new Date(n).toGMTString()),r.isString(o)&&a.push("path="+o),r.isString(i)&&a.push("domain="+i),!0===u&&a.push("secure"),document.cookie=a.join("; ")},read:function(t){var e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove:function(t){this.write(t,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}}},function(t,e,n){"use strict";t.exports=function(t){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(t)}},function(t,e,n){"use strict";var r=n(0);t.exports=r.isStandardBrowserEnv()?function(){var t,e=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");function o(t){var r=t;return e&&(n.setAttribute("href",r),r=n.href),n.setAttribute("href",r),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:"/"===n.pathname.charAt(0)?n.pathname:"/"+n.pathname}}return t=o(window.location.href),function(e){var n=r.isString(e)?o(e):e;return n.protocol===t.protocol&&n.host===t.host}}():function(){return!0}},function(t,e,n){"use strict";var r=n(0);t.exports=function(t,e){r.forEach(t,function(n,r){r!==e&&r.toUpperCase()===e.toUpperCase()&&(t[e]=n,delete t[r])})}},function(t,e,n){"use strict";var r=n(0),o=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"];t.exports=function(t){var e,n,i,u={};return t?(r.forEach(t.split("\n"),function(t){if(i=t.indexOf(":"),e=r.trim(t.substr(0,i)).toLowerCase(),n=r.trim(t.substr(i+1)),e){if(u[e]&&o.indexOf(e)>=0)return;u[e]="set-cookie"===e?(u[e]?u[e]:[]).concat([n]):u[e]?u[e]+", "+n:n}}),u):u}},function(t,e,n){"use strict";t.exports=function(t){return function(e){return t.apply(null,e)}}},function(t,e,n){t.exports={default:n(111),__esModule:!0}},function(t,e,n){t.exports={default:n(112),__esModule:!0}},function(t,e,n){"use strict";e.__esModule=!0;var r,o=n(108),i=(r=o)&&r.__esModule?r:{default:r};e.default=i.default||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t}},function(t,e,n){n(142),t.exports=n(3).Object.assign},function(t,e,n){n(143);var r=n(3).Object;t.exports=function(t,e,n){return r.defineProperty(t,e,n)}},function(t,e,n){n(144),n(146),n(149),n(145),n(147),n(148),t.exports=n(3).Promise},function(t,e){t.exports=function(){}},function(t,e){t.exports=function(t,e,n,r){if(!(t instanceof e)||void 0!==r&&r in t)throw TypeError(n+": incorrect invocation!");return t}},function(t,e,n){var r=n(29),o=n(56),i=n(137);t.exports=function(t){return function(e,n,u){var a,s=r(e),c=o(s.length),f=i(u,c);if(t&&n!=n){for(;c>f;)if((a=s[f++])!=a)return!0}else for(;c>f;f++)if((t||f in s)&&s[f]===n)return t||f||0;return!t&&-1}}},function(t,e,n){var r=n(14),o=n(121),i=n(120),u=n(4),a=n(56),s=n(140),c={},f={};(e=t.exports=function(t,e,n,l,p){var h,d,v,g,y=p?function(){return t}:s(t),m=r(n,l,e?2:1),_=0;if("function"!=typeof y)throw TypeError(t+" is not iterable!");if(i(y)){for(h=a(t.length);h>_;_++)if((g=e?m(u(d=t[_])[0],d[1]):m(t[_]))===c||g===f)return g}else for(v=y.call(t);!(d=v.next()).done;)if((g=o(v,m,d.value,e))===c||g===f)return g}).BREAK=c,e.RETURN=f},function(t,e,n){t.exports=!n(5)&&!n(23)(function(){return 7!=Object.defineProperty(n(22)("div"),"a",{get:function(){return 7}}).a})},function(t,e){t.exports=function(t,e,n){var r=void 0===n;switch(e.length){case 0:return r?t():t.call(n);case 1:return r?t(e[0]):t.call(n,e[0]);case 2:return r?t(e[0],e[1]):t.call(n,e[0],e[1]);case 3:return r?t(e[0],e[1],e[2]):t.call(n,e[0],e[1],e[2]);case 4:return r?t(e[0],e[1],e[2],e[3]):t.call(n,e[0],e[1],e[2],e[3])}return t.apply(n,e)}},function(t,e,n){var r=n(10),o=n(2)("iterator"),i=Array.prototype;t.exports=function(t){return void 0!==t&&(r.Array===t||i[o]===t)}},function(t,e,n){var r=n(4);t.exports=function(t,e,n,o){try{return o?e(r(n)[0],n[1]):e(n)}catch(e){var i=t.return;throw void 0!==i&&r(i.call(t)),e}}},function(t,e,n){"use strict";var r=n(127),o=n(52),i=n(26),u={};n(7)(u,n(2)("iterator"),function(){return this}),t.exports=function(t,e,n){t.prototype=r(u,{next:o(1,n)}),i(t,e+" Iterator")}},function(t,e,n){var r=n(2)("iterator"),o=!1;try{var i=[7][r]();i.return=function(){o=!0},Array.from(i,function(){throw 2})}catch(t){}t.exports=function(t,e){if(!e&&!o)return!1;var n=!1;try{var i=[7],u=i[r]();u.next=function(){return{done:n=!0}},i[r]=function(){return u},t(i)}catch(t){}return n}},function(t,e){t.exports=function(t,e){return{value:e,done:!!t}}},function(t,e,n){var r=n(1),o=n(55).set,i=r.MutationObserver||r.WebKitMutationObserver,u=r.process,a=r.Promise,s="process"==n(13)(u);t.exports=function(){var t,e,n,c=function(){var r,o;for(s&&(r=u.domain)&&r.exit();t;){o=t.fn,t=t.next;try{o()}catch(r){throw t?n():e=void 0,r}}e=void 0,r&&r.enter()};if(s)n=function(){u.nextTick(c)};else if(!i||r.navigator&&r.navigator.standalone)if(a&&a.resolve){var f=a.resolve(void 0);n=function(){f.then(c)}}else n=function(){o.call(r,c)};else{var l=!0,p=document.createTextNode("");new i(c).observe(p,{characterData:!0}),n=function(){p.data=l=!l}}return function(r){var o={fn:r,next:void 0};e&&(e.next=o),t||(t=o,n()),e=o}}},function(t,e,n){"use strict";var r=n(49),o=n(129),i=n(132),u=n(57),a=n(47),s=Object.assign;t.exports=!s||n(23)(function(){var t={},e={},n=Symbol(),r="abcdefghijklmnopqrst";return t[n]=7,r.split("").forEach(function(t){e[t]=t}),7!=s({},t)[n]||Object.keys(s({},e)).join("")!=r})?function(t,e){for(var n=u(t),s=arguments.length,c=1,f=o.f,l=i.f;s>c;)for(var p,h=a(arguments[c++]),d=f?r(h).concat(f(h)):r(h),v=d.length,g=0;v>g;)l.call(h,p=d[g++])&&(n[p]=h[p]);return n}:s},function(t,e,n){var r=n(4),o=n(128),i=n(45),u=n(27)("IE_PROTO"),a=function(){},s=function(){var t,e=n(22)("iframe"),r=i.length;for(e.style.display="none",n(46).appendChild(e),e.src="javascript:",(t=e.contentWindow.document).open(),t.write("<script>document.F=Object<\/script>"),t.close(),s=t.F;r--;)delete s.prototype[i[r]];return s()};t.exports=Object.create||function(t,e){var n;return null!==t?(a.prototype=r(t),n=new a,a.prototype=null,n[u]=t):n=s(),void 0===e?n:o(n,e)}},function(t,e,n){var r=n(11),o=n(4),i=n(49);t.exports=n(5)?Object.defineProperties:function(t,e){o(t);for(var n,u=i(e),a=u.length,s=0;a>s;)r.f(t,n=u[s++],e[n]);return t}},function(t,e){e.f=Object.getOwnPropertySymbols},function(t,e,n){var r=n(15),o=n(57),i=n(27)("IE_PROTO"),u=Object.prototype;t.exports=Object.getPrototypeOf||function(t){return t=o(t),r(t,i)?t[i]:"function"==typeof t.constructor&&t instanceof t.constructor?t.constructor.prototype:t instanceof Object?u:null}},function(t,e,n){var r=n(15),o=n(29),i=n(116)(!1),u=n(27)("IE_PROTO");t.exports=function(t,e){var n,a=o(t),s=0,c=[];for(n in a)n!=u&&r(a,n)&&c.push(n);for(;e.length>s;)r(a,n=e[s++])&&(~i(c,n)||c.push(n));return c}},function(t,e){e.f={}.propertyIsEnumerable},function(t,e,n){var r=n(7);t.exports=function(t,e,n){for(var o in e)n&&t[o]?t[o]=e[o]:r(t,o,e[o]);return t}},function(t,e,n){t.exports=n(7)},function(t,e,n){"use strict";var r=n(1),o=n(3),i=n(11),u=n(5),a=n(2)("species");t.exports=function(t){var e="function"==typeof o[t]?o[t]:r[t];u&&e&&!e[a]&&i.f(e,a,{configurable:!0,get:function(){return this}})}},function(t,e,n){var r=n(28),o=n(21);t.exports=function(t){return function(e,n){var i,u,a=String(o(e)),s=r(n),c=a.length;return s<0||s>=c?t?"":void 0:(i=a.charCodeAt(s))<55296||i>56319||s+1===c||(u=a.charCodeAt(s+1))<56320||u>57343?t?a.charAt(s):i:t?a.slice(s,s+2):u-56320+(i-55296<<10)+65536}}},function(t,e,n){var r=n(28),o=Math.max,i=Math.min;t.exports=function(t,e){return(t=r(t))<0?o(t+e,0):i(t,e)}},function(t,e,n){var r=n(9);t.exports=function(t,e){if(!r(t))return t;var n,o;if(e&&"function"==typeof(n=t.toString)&&!r(o=n.call(t)))return o;if("function"==typeof(n=t.valueOf)&&!r(o=n.call(t)))return o;if(!e&&"function"==typeof(n=t.toString)&&!r(o=n.call(t)))return o;throw TypeError("Can't convert object to primitive value")}},function(t,e,n){var r=n(1).navigator;t.exports=r&&r.userAgent||""},function(t,e,n){var r=n(44),o=n(2)("iterator"),i=n(10);t.exports=n(3).getIteratorMethod=function(t){if(void 0!=t)return t[o]||t["@@iterator"]||i[r(t)]}},function(t,e,n){"use strict";var r=n(114),o=n(124),i=n(10),u=n(29);t.exports=n(48)(Array,"Array",function(t,e){this._t=u(t),this._i=0,this._k=e},function(){var t=this._t,e=this._k,n=this._i++;return!t||n>=t.length?(this._t=void 0,o(1)):o(0,"keys"==e?n:"values"==e?t[n]:[n,t[n]])},"values"),i.Arguments=i.Array,r("keys"),r("values"),r("entries")},function(t,e,n){var r=n(6);r(r.S+r.F,"Object",{assign:n(126)})},function(t,e,n){var r=n(6);r(r.S+r.F*!n(5),"Object",{defineProperty:n(11).f})},function(t,e){},function(t,e,n){"use strict";var r,o,i,u,a=n(24),s=n(1),c=n(14),f=n(44),l=n(6),p=n(9),h=n(12),d=n(115),v=n(117),g=n(54),y=n(55).set,m=n(125)(),_=n(25),b=n(50),w=n(139),x=n(51),j=s.TypeError,E=s.process,O=E&&E.versions,S=O&&O.v8||"",R=s.Promise,T="process"==f(E),k=function(){},C=o=_.f,P=!!function(){try{var t=R.resolve(1),e=(t.constructor={})[n(2)("species")]=function(t){t(k,k)};return(T||"function"==typeof PromiseRejectionEvent)&&t.then(k)instanceof e&&0!==S.indexOf("6.6")&&-1===w.indexOf("Chrome/66")}catch(t){}}(),A=function(t){var e;return!(!p(t)||"function"!=typeof(e=t.then))&&e},M=function(t,e){if(!t._n){t._n=!0;var n=t._c;m(function(){for(var r=t._v,o=1==t._s,i=0,u=function(e){var n,i,u,a=o?e.ok:e.fail,s=e.resolve,c=e.reject,f=e.domain;try{a?(o||(2==t._h&&N(t),t._h=1),!0===a?n=r:(f&&f.enter(),n=a(r),f&&(f.exit(),u=!0)),n===e.promise?c(j("Promise-chain cycle")):(i=A(n))?i.call(n,s,c):s(n)):c(r)}catch(t){f&&!u&&f.exit(),c(t)}};n.length>i;)u(n[i++]);t._c=[],t._n=!1,e&&!t._h&&$(t)})}},$=function(t){y.call(s,function(){var e,n,r,o=t._v,i=L(t);if(i&&(e=b(function(){T?E.emit("unhandledRejection",o,t):(n=s.onunhandledrejection)?n({promise:t,reason:o}):(r=s.console)&&r.error&&r.error("Unhandled promise rejection",o)}),t._h=T||L(t)?2:1),t._a=void 0,i&&e.e)throw e.v})},L=function(t){return 1!==t._h&&0===(t._a||t._c).length},N=function(t){y.call(s,function(){var e;T?E.emit("rejectionHandled",t):(e=s.onrejectionhandled)&&e({promise:t,reason:t._v})})},z=function(t){var e=this;e._d||(e._d=!0,(e=e._w||e)._v=t,e._s=2,e._a||(e._a=e._c.slice()),M(e,!0))},I=function(t){var e,n=this;if(!n._d){n._d=!0,n=n._w||n;try{if(n===t)throw j("Promise can't be resolved itself");(e=A(t))?m(function(){var r={_w:n,_d:!1};try{e.call(t,c(I,r,1),c(z,r,1))}catch(t){z.call(r,t)}}):(n._v=t,n._s=1,M(n,!1))}catch(t){z.call({_w:n,_d:!1},t)}}};P||(R=function(t){d(this,R,"Promise","_h"),h(t),r.call(this);try{t(c(I,this,1),c(z,this,1))}catch(t){z.call(this,t)}},(r=function(t){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1}).prototype=n(133)(R.prototype,{then:function(t,e){var n=C(g(this,R));return n.ok="function"!=typeof t||t,n.fail="function"==typeof e&&e,n.domain=T?E.domain:void 0,this._c.push(n),this._a&&this._a.push(n),this._s&&M(this,!1),n.promise},catch:function(t){return this.then(void 0,t)}}),i=function(){var t=new r;this.promise=t,this.resolve=c(I,t,1),this.reject=c(z,t,1)},_.f=C=function(t){return t===R||t===u?new i(t):o(t)}),l(l.G+l.W+l.F*!P,{Promise:R}),n(26)(R,"Promise"),n(135)("Promise"),u=n(3).Promise,l(l.S+l.F*!P,"Promise",{reject:function(t){var e=C(this);return(0,e.reject)(t),e.promise}}),l(l.S+l.F*(a||!P),"Promise",{resolve:function(t){return x(a&&this===u?R:this,t)}}),l(l.S+l.F*!(P&&n(123)(function(t){R.all(t).catch(k)})),"Promise",{all:function(t){var e=this,n=C(e),r=n.resolve,o=n.reject,i=b(function(){var n=[],i=0,u=1;v(t,!1,function(t){var a=i++,s=!1;n.push(void 0),u++,e.resolve(t).then(function(t){s||(s=!0,n[a]=t,--u||r(n))},o)}),--u||r(n)});return i.e&&o(i.v),n.promise},race:function(t){var e=this,n=C(e),r=n.reject,o=b(function(){v(t,!1,function(t){e.resolve(t).then(n.resolve,r)})});return o.e&&r(o.v),n.promise}})},function(t,e,n){"use strict";var r=n(136)(!0);n(48)(String,"String",function(t){this._t=String(t),this._i=0},function(){var t,e=this._t,n=this._i;return n>=e.length?{value:void 0,done:!0}:(t=r(e,n),this._i+=t.length,{value:t,done:!1})})},function(t,e,n){"use strict";var r=n(6),o=n(3),i=n(1),u=n(54),a=n(51);r(r.P+r.R,"Promise",{finally:function(t){var e=u(this,o.Promise||i.Promise),n="function"==typeof t;return this.then(n?function(n){return a(e,t()).then(function(){return n})}:t,n?function(n){return a(e,t()).then(function(){throw n})}:t)}})},function(t,e,n){"use strict";var r=n(6),o=n(25),i=n(50);r(r.S,"Promise",{try:function(t){var e=o.f(this),n=i(t);return(n.e?e.reject:e.resolve)(n.v),e.promise}})},function(t,e,n){n(141);for(var r=n(1),o=n(7),i=n(10),u=n(2)("toStringTag"),a="CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,TextTrackList,TouchList".split(","),s=0;s<a.length;s++){var c=a[s],f=r[c],l=f&&f.prototype;l&&!l[u]&&o(l,u,c),i[c]=i.Array}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,o=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),i=n(59),u=(r=i)&&r.__esModule?r:{default:r},a=n(151);var s=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.processing=!1,this.successful=!1,this.withData(e).withOptions(n).withErrors({})}return o(t,[{key:"withData",value:function(t){for(var e in(0,a.isArray)(t)&&(t=t.reduce(function(t,e){return t[e]="",t},{})),this.setInitialValues(t),this.errors=new u.default,this.processing=!1,this.successful=!1,t)(0,a.guardAgainstReservedFieldName)(e),this[e]=t[e];return this}},{key:"withErrors",value:function(t){return this.errors=new u.default(t),this}},{key:"withOptions",value:function(t){if(this.__options={resetOnSuccess:!0},t.hasOwnProperty("resetOnSuccess")&&(this.__options.resetOnSuccess=t.resetOnSuccess),t.hasOwnProperty("onSuccess")&&(this.onSuccess=t.onSuccess),t.hasOwnProperty("onFail")&&(this.onFail=t.onFail),this.__http=t.http||window.axios||n(90),!this.__http)throw new Error("No http library provided. Either pass an http option, or install axios.");return this}},{key:"data",value:function(){var t={};for(var e in this.initial)t[e]=this[e];return t}},{key:"only",value:function(t){var e=this;return t.reduce(function(t,n){return t[n]=e[n],t},{})}},{key:"reset",value:function(){(0,a.merge)(this,this.initial),this.errors.clear()}},{key:"setInitialValues",value:function(t){this.initial={},(0,a.merge)(this.initial,t)}},{key:"populate",value:function(t){var e=this;return Object.keys(t).forEach(function(n){var r,o,i;(0,a.guardAgainstReservedFieldName)(n),e.hasOwnProperty(n)&&(0,a.merge)(e,(r={},o=n,i=t[n],o in r?Object.defineProperty(r,o,{value:i,enumerable:!0,configurable:!0,writable:!0}):r[o]=i,r))}),this}},{key:"clear",value:function(){for(var t in this.initial)this[t]="";this.errors.clear()}},{key:"post",value:function(t){return this.submit("post",t)}},{key:"put",value:function(t){return this.submit("put",t)}},{key:"patch",value:function(t){return this.submit("patch",t)}},{key:"delete",value:function(t){return this.submit("delete",t)}},{key:"submit",value:function(t,e){var n=this;return this.__validateRequestType(t),this.errors.clear(),this.processing=!0,this.successful=!1,new Promise(function(r,o){n.__http[t](e,n.hasFiles()?(0,a.objectToFormData)(n.data()):n.data()).then(function(t){n.processing=!1,n.onSuccess(t.data),r(t.data)}).catch(function(t){n.processing=!1,n.onFail(t),o(t)})})}},{key:"hasFiles",value:function(){for(var t in this.initial)if(this[t]instanceof File||this[t]instanceof FileList)return!0;return!1}},{key:"onSuccess",value:function(t){this.successful=!0,this.__options.resetOnSuccess&&this.reset()}},{key:"onFail",value:function(t){this.successful=!1,t.response&&t.response.data.errors&&this.errors.record(t.response.data.errors)}},{key:"hasError",value:function(t){return this.errors.has(t)}},{key:"getError",value:function(t){return this.errors.first(t)}},{key:"getErrors",value:function(t){return this.errors.get(t)}},{key:"__validateRequestType",value:function(t){var e=["get","delete","head","post","put","patch"];if(-1===e.indexOf(t))throw new Error("`"+t+"` is not a valid request type, must be one of: `"+e.join("`, `")+"`.")}}],[{key:"create",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return(new t).withData(e)}}]),t}();e.default=s},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};e.isArray=function(t){return"[object Array]"===Object.prototype.toString.call(t)},e.guardAgainstReservedFieldName=function(t){if(-1!==o.indexOf(t))throw new Error("Field name "+t+" isn't allowed to be used in a Form or Errors instance.")},e.merge=function(t,e){for(var n in e)t[n]=i(e[n])},e.cloneDeep=i,e.objectToFormData=u;var o=e.reservedFieldNames=["__http","__options","__validateRequestType","clear","data","delete","errors","getError","getErrors","hasError","initial","onFail","only","onSuccess","patch","populate","post","processing","successful","put","reset","submit","withData","withErrors","withOptions"];function i(t){if(null===t)return null;if(Array.isArray(t))return[].concat(function(t){if(Array.isArray(t)){for(var e=0,n=Array(t.length);e<t.length;e++)n[e]=t[e];return n}return Array.from(t)}(t));if("object"===(void 0===t?"undefined":r(t))){var e={};for(var n in t)e[n]=i(t[n]);return e}return t}function u(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:new FormData,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;for(var r in t)s(e,a(n,r),t[r]);return e}function a(t,e){return t?t+"["+e+"]":e}function s(t,e,n){return n instanceof Date?t.append(e,n.toISOString()):n instanceof File?t.append(e,n,n.name):"object"!==(void 0===n?"undefined":r(n))?t.append(e,n):void u(n,t,e)}},function(t,e){function n(t){return!!t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)}t.exports=function(t){return null!=t&&(n(t)||function(t){return"function"==typeof t.readFloatLE&&"function"==typeof t.slice&&n(t.slice(0,0))}(t)||!!t._isBuffer)}},function(t,e){t.exports=function(t,e,n){switch(n.length){case 0:return t.call(e);case 1:return t.call(e,n[0]);case 2:return t.call(e,n[0],n[1]);case 3:return t.call(e,n[0],n[1],n[2])}return t.apply(e,n)}},function(t,e,n){var r=n(164),o=n(189),i=n(65),u=n(190),a=n(62),s=n(191),c=Object.prototype.hasOwnProperty;t.exports=function(t,e){var n=i(t),f=!n&&o(t),l=!n&&!f&&u(t),p=!n&&!f&&!l&&s(t),h=n||f||l||p,d=h?r(t.length,String):[],v=d.length;for(var g in t)!e&&!c.call(t,g)||h&&("length"==g||l&&("offset"==g||"parent"==g)||p&&("buffer"==g||"byteLength"==g||"byteOffset"==g)||a(g,v))||d.push(g);return d}},function(t,e){t.exports=function(t,e){for(var n=-1,r=null==t?0:t.length,o=Array(r);++n<r;)o[n]=e(t[n],n,t);return o}},function(t,e){t.exports=function(t){return t.split("")}},function(t,e,n){var r=n(16),o=n(18),i="[object Arguments]";t.exports=function(t){return o(t)&&r(t)==i}},function(t,e,n){var r=n(67),o=n(175),i=n(8),u=n(184),a=/^\[object .+?Constructor\]$/,s=Function.prototype,c=Object.prototype,f=s.toString,l=c.hasOwnProperty,p=RegExp("^"+f.call(l).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");t.exports=function(t){return!(!i(t)||o(t))&&(r(t)?p:a).test(u(t))}},function(t,e,n){var r=n(16),o=n(68),i=n(18),u={};u["[object Float32Array]"]=u["[object Float64Array]"]=u["[object Int8Array]"]=u["[object Int16Array]"]=u["[object Int32Array]"]=u["[object Uint8Array]"]=u["[object Uint8ClampedArray]"]=u["[object Uint16Array]"]=u["[object Uint32Array]"]=!0,u["[object Arguments]"]=u["[object Array]"]=u["[object ArrayBuffer]"]=u["[object Boolean]"]=u["[object DataView]"]=u["[object Date]"]=u["[object Error]"]=u["[object Function]"]=u["[object Map]"]=u["[object Number]"]=u["[object Object]"]=u["[object RegExp]"]=u["[object Set]"]=u["[object String]"]=u["[object WeakMap]"]=!1,t.exports=function(t){return i(t)&&o(t.length)&&!!u[r(t)]}},function(t,e,n){var r=n(8),o=n(176),i=n(177),u=Object.prototype.hasOwnProperty;t.exports=function(t){if(!r(t))return i(t);var e=o(t),n=[];for(var a in t)("constructor"!=a||!e&&u.call(t,a))&&n.push(a);return n}},function(t,e,n){var r=n(64),o=n(180),i=n(181);t.exports=function(t,e){return i(o(t,e,r),t+"")}},function(t,e,n){var r=n(186),o=n(170),i=n(64),u=o?function(t,e){return o(t,"toString",{configurable:!0,enumerable:!1,value:r(e),writable:!0})}:i;t.exports=u},function(t,e){t.exports=function(t,e,n){var r=-1,o=t.length;e<0&&(e=-e>o?0:o+e),(n=n>o?o:n)<0&&(n+=o),o=e>n?0:n-e>>>0,e>>>=0;for(var i=Array(o);++r<o;)i[r]=t[r+e];return i}},function(t,e){t.exports=function(t,e){for(var n=-1,r=Array(t);++n<t;)r[n]=e(n);return r}},function(t,e,n){var r=n(30),o=n(155),i=n(65),u=n(69),a=1/0,s=r?r.prototype:void 0,c=s?s.toString:void 0;t.exports=function t(e){if("string"==typeof e)return e;if(i(e))return o(e,t)+"";if(u(e))return c?c.call(e):"";var n=e+"";return"0"==n&&1/e==-a?"-0":n}},function(t,e){t.exports=function(t){return function(e){return t(e)}}},function(t,e,n){var r=n(163);t.exports=function(t,e,n){var o=t.length;return n=void 0===n?o:n,!e&&n>=o?t:r(t,e,n)}},function(t,e,n){var r=n(17)["__core-js_shared__"];t.exports=r},function(t,e,n){var r=n(167),o=n(61),i=n(183),u=n(197);t.exports=function(t){return function(e){e=u(e);var n=o(e)?i(e):void 0,a=n?n[0]:e.charAt(0),s=n?r(n,1).join(""):e.slice(1);return a[t]()+s}}},function(t,e,n){var r=n(171),o=function(){try{var t=r(Object,"defineProperty");return t({},"",{}),t}catch(t){}}();t.exports=o},function(t,e,n){var r=n(158),o=n(173);t.exports=function(t,e){var n=o(t,e);return r(n)?n:void 0}},function(t,e,n){var r=n(30),o=Object.prototype,i=o.hasOwnProperty,u=o.toString,a=r?r.toStringTag:void 0;t.exports=function(t){var e=i.call(t,a),n=t[a];try{t[a]=void 0;var r=!0}catch(t){}var o=u.call(t);return r&&(e?t[a]=n:delete t[a]),o}},function(t,e){t.exports=function(t,e){return null==t?void 0:t[e]}},function(t,e,n){var r=n(63),o=n(66),i=n(62),u=n(8);t.exports=function(t,e,n){if(!u(n))return!1;var a=typeof e;return!!("number"==a?o(n)&&i(e,n.length):"string"==a&&e in n)&&r(n[e],t)}},function(t,e,n){var r,o=n(168),i=(r=/[^.]+$/.exec(o&&o.keys&&o.keys.IE_PROTO||""))?"Symbol(src)_1."+r:"";t.exports=function(t){return!!i&&i in t}},function(t,e){var n=Object.prototype;t.exports=function(t){var e=t&&t.constructor;return t===("function"==typeof e&&e.prototype||n)}},function(t,e){t.exports=function(t){var e=[];if(null!=t)for(var n in Object(t))e.push(n);return e}},function(t,e,n){(function(t){var r=n(60),o="object"==typeof e&&e&&!e.nodeType&&e,i=o&&"object"==typeof t&&t&&!t.nodeType&&t,u=i&&i.exports===o&&r.process,a=function(){try{var t=i&&i.require&&i.require("util").types;return t||u&&u.binding&&u.binding("util")}catch(t){}}();t.exports=a}).call(e,n(31)(t))},function(t,e){var n=Object.prototype.toString;t.exports=function(t){return n.call(t)}},function(t,e,n){var r=n(153),o=Math.max;t.exports=function(t,e,n){return e=o(void 0===e?t.length-1:e,0),function(){for(var i=arguments,u=-1,a=o(i.length-e,0),s=Array(a);++u<a;)s[u]=i[e+u];u=-1;for(var c=Array(e+1);++u<e;)c[u]=i[u];return c[e]=n(s),r(t,this,c)}}},function(t,e,n){var r=n(162),o=n(182)(r);t.exports=o},function(t,e){var n=800,r=16,o=Date.now;t.exports=function(t){var e=0,i=0;return function(){var u=o(),a=r-(u-i);if(i=u,a>0){if(++e>=n)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}},function(t,e,n){var r=n(156),o=n(61),i=n(185);t.exports=function(t){return o(t)?i(t):r(t)}},function(t,e){var n=Function.prototype.toString;t.exports=function(t){if(null!=t){try{return n.call(t)}catch(t){}try{return t+""}catch(t){}}return""}},function(t,e){var n="[\\ud800-\\udfff]",r="[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]",o="\\ud83c[\\udffb-\\udfff]",i="[^\\ud800-\\udfff]",u="(?:\\ud83c[\\udde6-\\uddff]){2}",a="[\\ud800-\\udbff][\\udc00-\\udfff]",s="(?:"+r+"|"+o+")"+"?",c="[\\ufe0e\\ufe0f]?"+s+("(?:\\u200d(?:"+[i,u,a].join("|")+")[\\ufe0e\\ufe0f]?"+s+")*"),f="(?:"+[i+r+"?",r,u,a,n].join("|")+")",l=RegExp(o+"(?="+o+")|"+f+c,"g");t.exports=function(t){return t.match(l)||[]}},function(t,e){t.exports=function(t){return function(){return t}}},function(t,e,n){var r=n(8),o=n(194),i=n(196),u="Expected a function",a=Math.max,s=Math.min;t.exports=function(t,e,n){var c,f,l,p,h,d,v=0,g=!1,y=!1,m=!0;if("function"!=typeof t)throw new TypeError(u);function _(e){var n=c,r=f;return c=f=void 0,v=e,p=t.apply(r,n)}function b(t){var n=t-d;return void 0===d||n>=e||n<0||y&&t-v>=l}function w(){var t=o();if(b(t))return x(t);h=setTimeout(w,function(t){var n=e-(t-d);return y?s(n,l-(t-v)):n}(t))}function x(t){return h=void 0,m&&c?_(t):(c=f=void 0,p)}function j(){var t=o(),n=b(t);if(c=arguments,f=this,d=t,n){if(void 0===h)return function(t){return v=t,h=setTimeout(w,e),g?_(t):p}(d);if(y)return clearTimeout(h),h=setTimeout(w,e),_(d)}return void 0===h&&(h=setTimeout(w,e)),p}return e=i(e)||0,r(n)&&(g=!!n.leading,l=(y="maxWait"in n)?a(i(n.maxWait)||0,e):l,m="trailing"in n?!!n.trailing:m),j.cancel=function(){void 0!==h&&clearTimeout(h),v=0,c=d=f=h=void 0},j.flush=function(){return void 0===h?p:x(o())},j}},function(t,e,n){var r=n(161),o=n(63),i=n(174),u=n(192),a=Object.prototype,s=a.hasOwnProperty,c=r(function(t,e){t=Object(t);var n=-1,r=e.length,c=r>2?e[2]:void 0;for(c&&i(e[0],e[1],c)&&(r=1);++n<r;)for(var f=e[n],l=u(f),p=-1,h=l.length;++p<h;){var d=l[p],v=t[d];(void 0===v||o(v,a[d])&&!s.call(t,d))&&(t[d]=f[d])}return t});t.exports=c},function(t,e,n){var r=n(157),o=n(18),i=Object.prototype,u=i.hasOwnProperty,a=i.propertyIsEnumerable,s=r(function(){return arguments}())?r:function(t){return o(t)&&u.call(t,"callee")&&!a.call(t,"callee")};t.exports=s},function(t,e,n){(function(t){var r=n(17),o=n(195),i="object"==typeof e&&e&&!e.nodeType&&e,u=i&&"object"==typeof t&&t&&!t.nodeType&&t,a=u&&u.exports===i?r.Buffer:void 0,s=(a?a.isBuffer:void 0)||o;t.exports=s}).call(e,n(31)(t))},function(t,e,n){var r=n(159),o=n(166),i=n(178),u=i&&i.isTypedArray,a=u?o(u):r;t.exports=a},function(t,e,n){var r=n(154),o=n(160),i=n(66);t.exports=function(t){return i(t)?r(t,!0):o(t)}},function(t,e,n){(function(t,r){var o;(function(){var i,u=200,a="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",s="Expected a function",c="__lodash_hash_undefined__",f=500,l="__lodash_placeholder__",p=1,h=2,d=4,v=1,g=2,y=1,m=2,_=4,b=8,w=16,x=32,j=64,E=128,O=256,S=512,R=30,T="...",k=800,C=16,P=1,A=2,M=1/0,$=9007199254740991,L=1.7976931348623157e308,N=NaN,z=4294967295,I=z-1,F=z>>>1,D=[["ary",E],["bind",y],["bindKey",m],["curry",b],["curryRight",w],["flip",S],["partial",x],["partialRight",j],["rearg",O]],q="[object Arguments]",U="[object Array]",W="[object AsyncFunction]",B="[object Boolean]",H="[object Date]",V="[object DOMException]",K="[object Error]",Y="[object Function]",G="[object GeneratorFunction]",Z="[object Map]",X="[object Number]",Q="[object Null]",J="[object Object]",tt="[object Proxy]",et="[object RegExp]",nt="[object Set]",rt="[object String]",ot="[object Symbol]",it="[object Undefined]",ut="[object WeakMap]",at="[object WeakSet]",st="[object ArrayBuffer]",ct="[object DataView]",ft="[object Float32Array]",lt="[object Float64Array]",pt="[object Int8Array]",ht="[object Int16Array]",dt="[object Int32Array]",vt="[object Uint8Array]",gt="[object Uint8ClampedArray]",yt="[object Uint16Array]",mt="[object Uint32Array]",_t=/\b__p \+= '';/g,bt=/\b(__p \+=) '' \+/g,wt=/(__e\(.*?\)|\b__t\)) \+\n'';/g,xt=/&(?:amp|lt|gt|quot|#39);/g,jt=/[&<>"']/g,Et=RegExp(xt.source),Ot=RegExp(jt.source),St=/<%-([\s\S]+?)%>/g,Rt=/<%([\s\S]+?)%>/g,Tt=/<%=([\s\S]+?)%>/g,kt=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Ct=/^\w*$/,Pt=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,At=/[\\^$.*+?()[\]{}|]/g,Mt=RegExp(At.source),$t=/^\s+|\s+$/g,Lt=/^\s+/,Nt=/\s+$/,zt=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,It=/\{\n\/\* \[wrapped with (.+)\] \*/,Ft=/,? & /,Dt=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,qt=/\\(\\)?/g,Ut=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,Wt=/\w*$/,Bt=/^[-+]0x[0-9a-f]+$/i,Ht=/^0b[01]+$/i,Vt=/^\[object .+?Constructor\]$/,Kt=/^0o[0-7]+$/i,Yt=/^(?:0|[1-9]\d*)$/,Gt=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,Zt=/($^)/,Xt=/['\n\r\u2028\u2029\\]/g,Qt="\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff",Jt="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",te="[\\ud800-\\udfff]",ee="["+Jt+"]",ne="["+Qt+"]",re="\\d+",oe="[\\u2700-\\u27bf]",ie="[a-z\\xdf-\\xf6\\xf8-\\xff]",ue="[^\\ud800-\\udfff"+Jt+re+"\\u2700-\\u27bfa-z\\xdf-\\xf6\\xf8-\\xffA-Z\\xc0-\\xd6\\xd8-\\xde]",ae="\\ud83c[\\udffb-\\udfff]",se="[^\\ud800-\\udfff]",ce="(?:\\ud83c[\\udde6-\\uddff]){2}",fe="[\\ud800-\\udbff][\\udc00-\\udfff]",le="[A-Z\\xc0-\\xd6\\xd8-\\xde]",pe="(?:"+ie+"|"+ue+")",he="(?:"+le+"|"+ue+")",de="(?:"+ne+"|"+ae+")"+"?",ve="[\\ufe0e\\ufe0f]?"+de+("(?:\\u200d(?:"+[se,ce,fe].join("|")+")[\\ufe0e\\ufe0f]?"+de+")*"),ge="(?:"+[oe,ce,fe].join("|")+")"+ve,ye="(?:"+[se+ne+"?",ne,ce,fe,te].join("|")+")",me=RegExp("['’]","g"),_e=RegExp(ne,"g"),be=RegExp(ae+"(?="+ae+")|"+ye+ve,"g"),we=RegExp([le+"?"+ie+"+(?:['’](?:d|ll|m|re|s|t|ve))?(?="+[ee,le,"$"].join("|")+")",he+"+(?:['’](?:D|LL|M|RE|S|T|VE))?(?="+[ee,le+pe,"$"].join("|")+")",le+"?"+pe+"+(?:['’](?:d|ll|m|re|s|t|ve))?",le+"+(?:['’](?:D|LL|M|RE|S|T|VE))?","\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])","\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",re,ge].join("|"),"g"),xe=RegExp("[\\u200d\\ud800-\\udfff"+Qt+"\\ufe0e\\ufe0f]"),je=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,Ee=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],Oe=-1,Se={};Se[ft]=Se[lt]=Se[pt]=Se[ht]=Se[dt]=Se[vt]=Se[gt]=Se[yt]=Se[mt]=!0,Se[q]=Se[U]=Se[st]=Se[B]=Se[ct]=Se[H]=Se[K]=Se[Y]=Se[Z]=Se[X]=Se[J]=Se[et]=Se[nt]=Se[rt]=Se[ut]=!1;var Re={};Re[q]=Re[U]=Re[st]=Re[ct]=Re[B]=Re[H]=Re[ft]=Re[lt]=Re[pt]=Re[ht]=Re[dt]=Re[Z]=Re[X]=Re[J]=Re[et]=Re[nt]=Re[rt]=Re[ot]=Re[vt]=Re[gt]=Re[yt]=Re[mt]=!0,Re[K]=Re[Y]=Re[ut]=!1;var Te={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},ke=parseFloat,Ce=parseInt,Pe="object"==typeof t&&t&&t.Object===Object&&t,Ae="object"==typeof self&&self&&self.Object===Object&&self,Me=Pe||Ae||Function("return this")(),$e="object"==typeof e&&e&&!e.nodeType&&e,Le=$e&&"object"==typeof r&&r&&!r.nodeType&&r,Ne=Le&&Le.exports===$e,ze=Ne&&Pe.process,Ie=function(){try{var t=Le&&Le.require&&Le.require("util").types;return t||ze&&ze.binding&&ze.binding("util")}catch(t){}}(),Fe=Ie&&Ie.isArrayBuffer,De=Ie&&Ie.isDate,qe=Ie&&Ie.isMap,Ue=Ie&&Ie.isRegExp,We=Ie&&Ie.isSet,Be=Ie&&Ie.isTypedArray;function He(t,e,n){switch(n.length){case 0:return t.call(e);case 1:return t.call(e,n[0]);case 2:return t.call(e,n[0],n[1]);case 3:return t.call(e,n[0],n[1],n[2])}return t.apply(e,n)}function Ve(t,e,n,r){for(var o=-1,i=null==t?0:t.length;++o<i;){var u=t[o];e(r,u,n(u),t)}return r}function Ke(t,e){for(var n=-1,r=null==t?0:t.length;++n<r&&!1!==e(t[n],n,t););return t}function Ye(t,e){for(var n=null==t?0:t.length;n--&&!1!==e(t[n],n,t););return t}function Ge(t,e){for(var n=-1,r=null==t?0:t.length;++n<r;)if(!e(t[n],n,t))return!1;return!0}function Ze(t,e){for(var n=-1,r=null==t?0:t.length,o=0,i=[];++n<r;){var u=t[n];e(u,n,t)&&(i[o++]=u)}return i}function Xe(t,e){return!!(null==t?0:t.length)&&sn(t,e,0)>-1}function Qe(t,e,n){for(var r=-1,o=null==t?0:t.length;++r<o;)if(n(e,t[r]))return!0;return!1}function Je(t,e){for(var n=-1,r=null==t?0:t.length,o=Array(r);++n<r;)o[n]=e(t[n],n,t);return o}function tn(t,e){for(var n=-1,r=e.length,o=t.length;++n<r;)t[o+n]=e[n];return t}function en(t,e,n,r){var o=-1,i=null==t?0:t.length;for(r&&i&&(n=t[++o]);++o<i;)n=e(n,t[o],o,t);return n}function nn(t,e,n,r){var o=null==t?0:t.length;for(r&&o&&(n=t[--o]);o--;)n=e(n,t[o],o,t);return n}function rn(t,e){for(var n=-1,r=null==t?0:t.length;++n<r;)if(e(t[n],n,t))return!0;return!1}var on=pn("length");function un(t,e,n){var r;return n(t,function(t,n,o){if(e(t,n,o))return r=n,!1}),r}function an(t,e,n,r){for(var o=t.length,i=n+(r?1:-1);r?i--:++i<o;)if(e(t[i],i,t))return i;return-1}function sn(t,e,n){return e==e?function(t,e,n){var r=n-1,o=t.length;for(;++r<o;)if(t[r]===e)return r;return-1}(t,e,n):an(t,fn,n)}function cn(t,e,n,r){for(var o=n-1,i=t.length;++o<i;)if(r(t[o],e))return o;return-1}function fn(t){return t!=t}function ln(t,e){var n=null==t?0:t.length;return n?vn(t,e)/n:N}function pn(t){return function(e){return null==e?i:e[t]}}function hn(t){return function(e){return null==t?i:t[e]}}function dn(t,e,n,r,o){return o(t,function(t,o,i){n=r?(r=!1,t):e(n,t,o,i)}),n}function vn(t,e){for(var n,r=-1,o=t.length;++r<o;){var u=e(t[r]);u!==i&&(n=n===i?u:n+u)}return n}function gn(t,e){for(var n=-1,r=Array(t);++n<t;)r[n]=e(n);return r}function yn(t){return function(e){return t(e)}}function mn(t,e){return Je(e,function(e){return t[e]})}function _n(t,e){return t.has(e)}function bn(t,e){for(var n=-1,r=t.length;++n<r&&sn(e,t[n],0)>-1;);return n}function wn(t,e){for(var n=t.length;n--&&sn(e,t[n],0)>-1;);return n}var xn=hn({"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"}),jn=hn({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"});function En(t){return"\\"+Te[t]}function On(t){return xe.test(t)}function Sn(t){var e=-1,n=Array(t.size);return t.forEach(function(t,r){n[++e]=[r,t]}),n}function Rn(t,e){return function(n){return t(e(n))}}function Tn(t,e){for(var n=-1,r=t.length,o=0,i=[];++n<r;){var u=t[n];u!==e&&u!==l||(t[n]=l,i[o++]=n)}return i}function kn(t){var e=-1,n=Array(t.size);return t.forEach(function(t){n[++e]=t}),n}function Cn(t){var e=-1,n=Array(t.size);return t.forEach(function(t){n[++e]=[t,t]}),n}function Pn(t){return On(t)?function(t){var e=be.lastIndex=0;for(;be.test(t);)++e;return e}(t):on(t)}function An(t){return On(t)?function(t){return t.match(be)||[]}(t):function(t){return t.split("")}(t)}var Mn=hn({"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'"});var $n=function t(e){var n,r=(e=null==e?Me:$n.defaults(Me.Object(),e,$n.pick(Me,Ee))).Array,o=e.Date,Qt=e.Error,Jt=e.Function,te=e.Math,ee=e.Object,ne=e.RegExp,re=e.String,oe=e.TypeError,ie=r.prototype,ue=Jt.prototype,ae=ee.prototype,se=e["__core-js_shared__"],ce=ue.toString,fe=ae.hasOwnProperty,le=0,pe=(n=/[^.]+$/.exec(se&&se.keys&&se.keys.IE_PROTO||""))?"Symbol(src)_1."+n:"",he=ae.toString,de=ce.call(ee),ve=Me._,ge=ne("^"+ce.call(fe).replace(At,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),ye=Ne?e.Buffer:i,be=e.Symbol,xe=e.Uint8Array,Te=ye?ye.allocUnsafe:i,Pe=Rn(ee.getPrototypeOf,ee),Ae=ee.create,$e=ae.propertyIsEnumerable,Le=ie.splice,ze=be?be.isConcatSpreadable:i,Ie=be?be.iterator:i,on=be?be.toStringTag:i,hn=function(){try{var t=Fi(ee,"defineProperty");return t({},"",{}),t}catch(t){}}(),Ln=e.clearTimeout!==Me.clearTimeout&&e.clearTimeout,Nn=o&&o.now!==Me.Date.now&&o.now,zn=e.setTimeout!==Me.setTimeout&&e.setTimeout,In=te.ceil,Fn=te.floor,Dn=ee.getOwnPropertySymbols,qn=ye?ye.isBuffer:i,Un=e.isFinite,Wn=ie.join,Bn=Rn(ee.keys,ee),Hn=te.max,Vn=te.min,Kn=o.now,Yn=e.parseInt,Gn=te.random,Zn=ie.reverse,Xn=Fi(e,"DataView"),Qn=Fi(e,"Map"),Jn=Fi(e,"Promise"),tr=Fi(e,"Set"),er=Fi(e,"WeakMap"),nr=Fi(ee,"create"),rr=er&&new er,or={},ir=lu(Xn),ur=lu(Qn),ar=lu(Jn),sr=lu(tr),cr=lu(er),fr=be?be.prototype:i,lr=fr?fr.valueOf:i,pr=fr?fr.toString:i;function hr(t){if(Ta(t)&&!ya(t)&&!(t instanceof yr)){if(t instanceof gr)return t;if(fe.call(t,"__wrapped__"))return pu(t)}return new gr(t)}var dr=function(){function t(){}return function(e){if(!Ra(e))return{};if(Ae)return Ae(e);t.prototype=e;var n=new t;return t.prototype=i,n}}();function vr(){}function gr(t,e){this.__wrapped__=t,this.__actions__=[],this.__chain__=!!e,this.__index__=0,this.__values__=i}function yr(t){this.__wrapped__=t,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=z,this.__views__=[]}function mr(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}function _r(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}function br(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}function wr(t){var e=-1,n=null==t?0:t.length;for(this.__data__=new br;++e<n;)this.add(t[e])}function xr(t){var e=this.__data__=new _r(t);this.size=e.size}function jr(t,e){var n=ya(t),r=!n&&ga(t),o=!n&&!r&&wa(t),i=!n&&!r&&!o&&Na(t),u=n||r||o||i,a=u?gn(t.length,re):[],s=a.length;for(var c in t)!e&&!fe.call(t,c)||u&&("length"==c||o&&("offset"==c||"parent"==c)||i&&("buffer"==c||"byteLength"==c||"byteOffset"==c)||Vi(c,s))||a.push(c);return a}function Er(t){var e=t.length;return e?t[xo(0,e-1)]:i}function Or(t,e){return su(ri(t),$r(e,0,t.length))}function Sr(t){return su(ri(t))}function Rr(t,e,n){(n===i||ha(t[e],n))&&(n!==i||e in t)||Ar(t,e,n)}function Tr(t,e,n){var r=t[e];fe.call(t,e)&&ha(r,n)&&(n!==i||e in t)||Ar(t,e,n)}function kr(t,e){for(var n=t.length;n--;)if(ha(t[n][0],e))return n;return-1}function Cr(t,e,n,r){return Fr(t,function(t,o,i){e(r,t,n(t),i)}),r}function Pr(t,e){return t&&oi(e,os(e),t)}function Ar(t,e,n){"__proto__"==e&&hn?hn(t,e,{configurable:!0,enumerable:!0,value:n,writable:!0}):t[e]=n}function Mr(t,e){for(var n=-1,o=e.length,u=r(o),a=null==t;++n<o;)u[n]=a?i:Ja(t,e[n]);return u}function $r(t,e,n){return t==t&&(n!==i&&(t=t<=n?t:n),e!==i&&(t=t>=e?t:e)),t}function Lr(t,e,n,r,o,u){var a,s=e&p,c=e&h,f=e&d;if(n&&(a=o?n(t,r,o,u):n(t)),a!==i)return a;if(!Ra(t))return t;var l=ya(t);if(l){if(a=function(t){var e=t.length,n=new t.constructor(e);return e&&"string"==typeof t[0]&&fe.call(t,"index")&&(n.index=t.index,n.input=t.input),n}(t),!s)return ri(t,a)}else{var v=Ui(t),g=v==Y||v==G;if(wa(t))return Xo(t,s);if(v==J||v==q||g&&!o){if(a=c||g?{}:Bi(t),!s)return c?function(t,e){return oi(t,qi(t),e)}(t,function(t,e){return t&&oi(e,is(e),t)}(a,t)):function(t,e){return oi(t,Di(t),e)}(t,Pr(a,t))}else{if(!Re[v])return o?t:{};a=function(t,e,n){var r,o,i,u=t.constructor;switch(e){case st:return Qo(t);case B:case H:return new u(+t);case ct:return function(t,e){var n=e?Qo(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.byteLength)}(t,n);case ft:case lt:case pt:case ht:case dt:case vt:case gt:case yt:case mt:return Jo(t,n);case Z:return new u;case X:case rt:return new u(t);case et:return(i=new(o=t).constructor(o.source,Wt.exec(o))).lastIndex=o.lastIndex,i;case nt:return new u;case ot:return r=t,lr?ee(lr.call(r)):{}}}(t,v,s)}}u||(u=new xr);var y=u.get(t);if(y)return y;u.set(t,a),Ma(t)?t.forEach(function(r){a.add(Lr(r,e,n,r,t,u))}):ka(t)&&t.forEach(function(r,o){a.set(o,Lr(r,e,n,o,t,u))});var m=l?i:(f?c?Ai:Pi:c?is:os)(t);return Ke(m||t,function(r,o){m&&(r=t[o=r]),Tr(a,o,Lr(r,e,n,o,t,u))}),a}function Nr(t,e,n){var r=n.length;if(null==t)return!r;for(t=ee(t);r--;){var o=n[r],u=e[o],a=t[o];if(a===i&&!(o in t)||!u(a))return!1}return!0}function zr(t,e,n){if("function"!=typeof t)throw new oe(s);return ou(function(){t.apply(i,n)},e)}function Ir(t,e,n,r){var o=-1,i=Xe,a=!0,s=t.length,c=[],f=e.length;if(!s)return c;n&&(e=Je(e,yn(n))),r?(i=Qe,a=!1):e.length>=u&&(i=_n,a=!1,e=new wr(e));t:for(;++o<s;){var l=t[o],p=null==n?l:n(l);if(l=r||0!==l?l:0,a&&p==p){for(var h=f;h--;)if(e[h]===p)continue t;c.push(l)}else i(e,p,r)||c.push(l)}return c}hr.templateSettings={escape:St,evaluate:Rt,interpolate:Tt,variable:"",imports:{_:hr}},hr.prototype=vr.prototype,hr.prototype.constructor=hr,gr.prototype=dr(vr.prototype),gr.prototype.constructor=gr,yr.prototype=dr(vr.prototype),yr.prototype.constructor=yr,mr.prototype.clear=function(){this.__data__=nr?nr(null):{},this.size=0},mr.prototype.delete=function(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e},mr.prototype.get=function(t){var e=this.__data__;if(nr){var n=e[t];return n===c?i:n}return fe.call(e,t)?e[t]:i},mr.prototype.has=function(t){var e=this.__data__;return nr?e[t]!==i:fe.call(e,t)},mr.prototype.set=function(t,e){var n=this.__data__;return this.size+=this.has(t)?0:1,n[t]=nr&&e===i?c:e,this},_r.prototype.clear=function(){this.__data__=[],this.size=0},_r.prototype.delete=function(t){var e=this.__data__,n=kr(e,t);return!(n<0||(n==e.length-1?e.pop():Le.call(e,n,1),--this.size,0))},_r.prototype.get=function(t){var e=this.__data__,n=kr(e,t);return n<0?i:e[n][1]},_r.prototype.has=function(t){return kr(this.__data__,t)>-1},_r.prototype.set=function(t,e){var n=this.__data__,r=kr(n,t);return r<0?(++this.size,n.push([t,e])):n[r][1]=e,this},br.prototype.clear=function(){this.size=0,this.__data__={hash:new mr,map:new(Qn||_r),string:new mr}},br.prototype.delete=function(t){var e=zi(this,t).delete(t);return this.size-=e?1:0,e},br.prototype.get=function(t){return zi(this,t).get(t)},br.prototype.has=function(t){return zi(this,t).has(t)},br.prototype.set=function(t,e){var n=zi(this,t),r=n.size;return n.set(t,e),this.size+=n.size==r?0:1,this},wr.prototype.add=wr.prototype.push=function(t){return this.__data__.set(t,c),this},wr.prototype.has=function(t){return this.__data__.has(t)},xr.prototype.clear=function(){this.__data__=new _r,this.size=0},xr.prototype.delete=function(t){var e=this.__data__,n=e.delete(t);return this.size=e.size,n},xr.prototype.get=function(t){return this.__data__.get(t)},xr.prototype.has=function(t){return this.__data__.has(t)},xr.prototype.set=function(t,e){var n=this.__data__;if(n instanceof _r){var r=n.__data__;if(!Qn||r.length<u-1)return r.push([t,e]),this.size=++n.size,this;n=this.__data__=new br(r)}return n.set(t,e),this.size=n.size,this};var Fr=ai(Kr),Dr=ai(Yr,!0);function qr(t,e){var n=!0;return Fr(t,function(t,r,o){return n=!!e(t,r,o)}),n}function Ur(t,e,n){for(var r=-1,o=t.length;++r<o;){var u=t[r],a=e(u);if(null!=a&&(s===i?a==a&&!La(a):n(a,s)))var s=a,c=u}return c}function Wr(t,e){var n=[];return Fr(t,function(t,r,o){e(t,r,o)&&n.push(t)}),n}function Br(t,e,n,r,o){var i=-1,u=t.length;for(n||(n=Hi),o||(o=[]);++i<u;){var a=t[i];e>0&&n(a)?e>1?Br(a,e-1,n,r,o):tn(o,a):r||(o[o.length]=a)}return o}var Hr=si(),Vr=si(!0);function Kr(t,e){return t&&Hr(t,e,os)}function Yr(t,e){return t&&Vr(t,e,os)}function Gr(t,e){return Ze(e,function(e){return Ea(t[e])})}function Zr(t,e){for(var n=0,r=(e=Ko(e,t)).length;null!=t&&n<r;)t=t[fu(e[n++])];return n&&n==r?t:i}function Xr(t,e,n){var r=e(t);return ya(t)?r:tn(r,n(t))}function Qr(t){return null==t?t===i?it:Q:on&&on in ee(t)?function(t){var e=fe.call(t,on),n=t[on];try{t[on]=i;var r=!0}catch(t){}var o=he.call(t);return r&&(e?t[on]=n:delete t[on]),o}(t):function(t){return he.call(t)}(t)}function Jr(t,e){return t>e}function to(t,e){return null!=t&&fe.call(t,e)}function eo(t,e){return null!=t&&e in ee(t)}function no(t,e,n){for(var o=n?Qe:Xe,u=t[0].length,a=t.length,s=a,c=r(a),f=1/0,l=[];s--;){var p=t[s];s&&e&&(p=Je(p,yn(e))),f=Vn(p.length,f),c[s]=!n&&(e||u>=120&&p.length>=120)?new wr(s&&p):i}p=t[0];var h=-1,d=c[0];t:for(;++h<u&&l.length<f;){var v=p[h],g=e?e(v):v;if(v=n||0!==v?v:0,!(d?_n(d,g):o(l,g,n))){for(s=a;--s;){var y=c[s];if(!(y?_n(y,g):o(t[s],g,n)))continue t}d&&d.push(g),l.push(v)}}return l}function ro(t,e,n){var r=null==(t=eu(t,e=Ko(e,t)))?t:t[fu(ju(e))];return null==r?i:He(r,t,n)}function oo(t){return Ta(t)&&Qr(t)==q}function io(t,e,n,r,o){return t===e||(null==t||null==e||!Ta(t)&&!Ta(e)?t!=t&&e!=e:function(t,e,n,r,o,u){var a=ya(t),s=ya(e),c=a?U:Ui(t),f=s?U:Ui(e),l=(c=c==q?J:c)==J,p=(f=f==q?J:f)==J,h=c==f;if(h&&wa(t)){if(!wa(e))return!1;a=!0,l=!1}if(h&&!l)return u||(u=new xr),a||Na(t)?ki(t,e,n,r,o,u):function(t,e,n,r,o,i,u){switch(n){case ct:if(t.byteLength!=e.byteLength||t.byteOffset!=e.byteOffset)return!1;t=t.buffer,e=e.buffer;case st:return!(t.byteLength!=e.byteLength||!i(new xe(t),new xe(e)));case B:case H:case X:return ha(+t,+e);case K:return t.name==e.name&&t.message==e.message;case et:case rt:return t==e+"";case Z:var a=Sn;case nt:var s=r&v;if(a||(a=kn),t.size!=e.size&&!s)return!1;var c=u.get(t);if(c)return c==e;r|=g,u.set(t,e);var f=ki(a(t),a(e),r,o,i,u);return u.delete(t),f;case ot:if(lr)return lr.call(t)==lr.call(e)}return!1}(t,e,c,n,r,o,u);if(!(n&v)){var d=l&&fe.call(t,"__wrapped__"),y=p&&fe.call(e,"__wrapped__");if(d||y){var m=d?t.value():t,_=y?e.value():e;return u||(u=new xr),o(m,_,n,r,u)}}return!!h&&(u||(u=new xr),function(t,e,n,r,o,u){var a=n&v,s=Pi(t),c=s.length,f=Pi(e).length;if(c!=f&&!a)return!1;for(var l=c;l--;){var p=s[l];if(!(a?p in e:fe.call(e,p)))return!1}var h=u.get(t),d=u.get(e);if(h&&d)return h==e&&d==t;var g=!0;u.set(t,e),u.set(e,t);for(var y=a;++l<c;){p=s[l];var m=t[p],_=e[p];if(r)var b=a?r(_,m,p,e,t,u):r(m,_,p,t,e,u);if(!(b===i?m===_||o(m,_,n,r,u):b)){g=!1;break}y||(y="constructor"==p)}if(g&&!y){var w=t.constructor,x=e.constructor;w!=x&&"constructor"in t&&"constructor"in e&&!("function"==typeof w&&w instanceof w&&"function"==typeof x&&x instanceof x)&&(g=!1)}return u.delete(t),u.delete(e),g}(t,e,n,r,o,u))}(t,e,n,r,io,o))}function uo(t,e,n,r){var o=n.length,u=o,a=!r;if(null==t)return!u;for(t=ee(t);o--;){var s=n[o];if(a&&s[2]?s[1]!==t[s[0]]:!(s[0]in t))return!1}for(;++o<u;){var c=(s=n[o])[0],f=t[c],l=s[1];if(a&&s[2]){if(f===i&&!(c in t))return!1}else{var p=new xr;if(r)var h=r(f,l,c,t,e,p);if(!(h===i?io(l,f,v|g,r,p):h))return!1}}return!0}function ao(t){return!(!Ra(t)||pe&&pe in t)&&(Ea(t)?ge:Vt).test(lu(t))}function so(t){return"function"==typeof t?t:null==t?Cs:"object"==typeof t?ya(t)?vo(t[0],t[1]):ho(t):Fs(t)}function co(t){if(!Xi(t))return Bn(t);var e=[];for(var n in ee(t))fe.call(t,n)&&"constructor"!=n&&e.push(n);return e}function fo(t){if(!Ra(t))return function(t){var e=[];if(null!=t)for(var n in ee(t))e.push(n);return e}(t);var e=Xi(t),n=[];for(var r in t)("constructor"!=r||!e&&fe.call(t,r))&&n.push(r);return n}function lo(t,e){return t<e}function po(t,e){var n=-1,o=_a(t)?r(t.length):[];return Fr(t,function(t,r,i){o[++n]=e(t,r,i)}),o}function ho(t){var e=Ii(t);return 1==e.length&&e[0][2]?Ji(e[0][0],e[0][1]):function(n){return n===t||uo(n,t,e)}}function vo(t,e){return Yi(t)&&Qi(e)?Ji(fu(t),e):function(n){var r=Ja(n,t);return r===i&&r===e?ts(n,t):io(e,r,v|g)}}function go(t,e,n,r,o){t!==e&&Hr(e,function(u,a){if(o||(o=new xr),Ra(u))!function(t,e,n,r,o,u,a){var s=nu(t,n),c=nu(e,n),f=a.get(c);if(f)Rr(t,n,f);else{var l=u?u(s,c,n+"",t,e,a):i,p=l===i;if(p){var h=ya(c),d=!h&&wa(c),v=!h&&!d&&Na(c);l=c,h||d||v?ya(s)?l=s:ba(s)?l=ri(s):d?(p=!1,l=Xo(c,!0)):v?(p=!1,l=Jo(c,!0)):l=[]:Pa(c)||ga(c)?(l=s,ga(s)?l=Ba(s):Ra(s)&&!Ea(s)||(l=Bi(c))):p=!1}p&&(a.set(c,l),o(l,c,r,u,a),a.delete(c)),Rr(t,n,l)}}(t,e,a,n,go,r,o);else{var s=r?r(nu(t,a),u,a+"",t,e,o):i;s===i&&(s=u),Rr(t,a,s)}},is)}function yo(t,e){var n=t.length;if(n)return Vi(e+=e<0?n:0,n)?t[e]:i}function mo(t,e,n){var r=-1;return e=Je(e=e.length?Je(e,function(t){return ya(t)?function(e){return Zr(e,1===t.length?t[0]:t)}:t}):[Cs],yn(Ni())),function(t,e){var n=t.length;for(t.sort(e);n--;)t[n]=t[n].value;return t}(po(t,function(t,n,o){return{criteria:Je(e,function(e){return e(t)}),index:++r,value:t}}),function(t,e){return function(t,e,n){for(var r=-1,o=t.criteria,i=e.criteria,u=o.length,a=n.length;++r<u;){var s=ti(o[r],i[r]);if(s){if(r>=a)return s;var c=n[r];return s*("desc"==c?-1:1)}}return t.index-e.index}(t,e,n)})}function _o(t,e,n){for(var r=-1,o=e.length,i={};++r<o;){var u=e[r],a=Zr(t,u);n(a,u)&&Ro(i,Ko(u,t),a)}return i}function bo(t,e,n,r){var o=r?cn:sn,i=-1,u=e.length,a=t;for(t===e&&(e=ri(e)),n&&(a=Je(t,yn(n)));++i<u;)for(var s=0,c=e[i],f=n?n(c):c;(s=o(a,f,s,r))>-1;)a!==t&&Le.call(a,s,1),Le.call(t,s,1);return t}function wo(t,e){for(var n=t?e.length:0,r=n-1;n--;){var o=e[n];if(n==r||o!==i){var i=o;Vi(o)?Le.call(t,o,1):Fo(t,o)}}return t}function xo(t,e){return t+Fn(Gn()*(e-t+1))}function jo(t,e){var n="";if(!t||e<1||e>$)return n;do{e%2&&(n+=t),(e=Fn(e/2))&&(t+=t)}while(e);return n}function Eo(t,e){return iu(tu(t,e,Cs),t+"")}function Oo(t){return Er(hs(t))}function So(t,e){var n=hs(t);return su(n,$r(e,0,n.length))}function Ro(t,e,n,r){if(!Ra(t))return t;for(var o=-1,u=(e=Ko(e,t)).length,a=u-1,s=t;null!=s&&++o<u;){var c=fu(e[o]),f=n;if("__proto__"===c||"constructor"===c||"prototype"===c)return t;if(o!=a){var l=s[c];(f=r?r(l,c,s):i)===i&&(f=Ra(l)?l:Vi(e[o+1])?[]:{})}Tr(s,c,f),s=s[c]}return t}var To=rr?function(t,e){return rr.set(t,e),t}:Cs,ko=hn?function(t,e){return hn(t,"toString",{configurable:!0,enumerable:!1,value:Rs(e),writable:!0})}:Cs;function Co(t){return su(hs(t))}function Po(t,e,n){var o=-1,i=t.length;e<0&&(e=-e>i?0:i+e),(n=n>i?i:n)<0&&(n+=i),i=e>n?0:n-e>>>0,e>>>=0;for(var u=r(i);++o<i;)u[o]=t[o+e];return u}function Ao(t,e){var n;return Fr(t,function(t,r,o){return!(n=e(t,r,o))}),!!n}function Mo(t,e,n){var r=0,o=null==t?r:t.length;if("number"==typeof e&&e==e&&o<=F){for(;r<o;){var i=r+o>>>1,u=t[i];null!==u&&!La(u)&&(n?u<=e:u<e)?r=i+1:o=i}return o}return $o(t,e,Cs,n)}function $o(t,e,n,r){var o=0,u=null==t?0:t.length;if(0===u)return 0;for(var a=(e=n(e))!=e,s=null===e,c=La(e),f=e===i;o<u;){var l=Fn((o+u)/2),p=n(t[l]),h=p!==i,d=null===p,v=p==p,g=La(p);if(a)var y=r||v;else y=f?v&&(r||h):s?v&&h&&(r||!d):c?v&&h&&!d&&(r||!g):!d&&!g&&(r?p<=e:p<e);y?o=l+1:u=l}return Vn(u,I)}function Lo(t,e){for(var n=-1,r=t.length,o=0,i=[];++n<r;){var u=t[n],a=e?e(u):u;if(!n||!ha(a,s)){var s=a;i[o++]=0===u?0:u}}return i}function No(t){return"number"==typeof t?t:La(t)?N:+t}function zo(t){if("string"==typeof t)return t;if(ya(t))return Je(t,zo)+"";if(La(t))return pr?pr.call(t):"";var e=t+"";return"0"==e&&1/t==-M?"-0":e}function Io(t,e,n){var r=-1,o=Xe,i=t.length,a=!0,s=[],c=s;if(n)a=!1,o=Qe;else if(i>=u){var f=e?null:ji(t);if(f)return kn(f);a=!1,o=_n,c=new wr}else c=e?[]:s;t:for(;++r<i;){var l=t[r],p=e?e(l):l;if(l=n||0!==l?l:0,a&&p==p){for(var h=c.length;h--;)if(c[h]===p)continue t;e&&c.push(p),s.push(l)}else o(c,p,n)||(c!==s&&c.push(p),s.push(l))}return s}function Fo(t,e){return null==(t=eu(t,e=Ko(e,t)))||delete t[fu(ju(e))]}function Do(t,e,n,r){return Ro(t,e,n(Zr(t,e)),r)}function qo(t,e,n,r){for(var o=t.length,i=r?o:-1;(r?i--:++i<o)&&e(t[i],i,t););return n?Po(t,r?0:i,r?i+1:o):Po(t,r?i+1:0,r?o:i)}function Uo(t,e){var n=t;return n instanceof yr&&(n=n.value()),en(e,function(t,e){return e.func.apply(e.thisArg,tn([t],e.args))},n)}function Wo(t,e,n){var o=t.length;if(o<2)return o?Io(t[0]):[];for(var i=-1,u=r(o);++i<o;)for(var a=t[i],s=-1;++s<o;)s!=i&&(u[i]=Ir(u[i]||a,t[s],e,n));return Io(Br(u,1),e,n)}function Bo(t,e,n){for(var r=-1,o=t.length,u=e.length,a={};++r<o;){var s=r<u?e[r]:i;n(a,t[r],s)}return a}function Ho(t){return ba(t)?t:[]}function Vo(t){return"function"==typeof t?t:Cs}function Ko(t,e){return ya(t)?t:Yi(t,e)?[t]:cu(Ha(t))}var Yo=Eo;function Go(t,e,n){var r=t.length;return n=n===i?r:n,!e&&n>=r?t:Po(t,e,n)}var Zo=Ln||function(t){return Me.clearTimeout(t)};function Xo(t,e){if(e)return t.slice();var n=t.length,r=Te?Te(n):new t.constructor(n);return t.copy(r),r}function Qo(t){var e=new t.constructor(t.byteLength);return new xe(e).set(new xe(t)),e}function Jo(t,e){var n=e?Qo(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.length)}function ti(t,e){if(t!==e){var n=t!==i,r=null===t,o=t==t,u=La(t),a=e!==i,s=null===e,c=e==e,f=La(e);if(!s&&!f&&!u&&t>e||u&&a&&c&&!s&&!f||r&&a&&c||!n&&c||!o)return 1;if(!r&&!u&&!f&&t<e||f&&n&&o&&!r&&!u||s&&n&&o||!a&&o||!c)return-1}return 0}function ei(t,e,n,o){for(var i=-1,u=t.length,a=n.length,s=-1,c=e.length,f=Hn(u-a,0),l=r(c+f),p=!o;++s<c;)l[s]=e[s];for(;++i<a;)(p||i<u)&&(l[n[i]]=t[i]);for(;f--;)l[s++]=t[i++];return l}function ni(t,e,n,o){for(var i=-1,u=t.length,a=-1,s=n.length,c=-1,f=e.length,l=Hn(u-s,0),p=r(l+f),h=!o;++i<l;)p[i]=t[i];for(var d=i;++c<f;)p[d+c]=e[c];for(;++a<s;)(h||i<u)&&(p[d+n[a]]=t[i++]);return p}function ri(t,e){var n=-1,o=t.length;for(e||(e=r(o));++n<o;)e[n]=t[n];return e}function oi(t,e,n,r){var o=!n;n||(n={});for(var u=-1,a=e.length;++u<a;){var s=e[u],c=r?r(n[s],t[s],s,n,t):i;c===i&&(c=t[s]),o?Ar(n,s,c):Tr(n,s,c)}return n}function ii(t,e){return function(n,r){var o=ya(n)?Ve:Cr,i=e?e():{};return o(n,t,Ni(r,2),i)}}function ui(t){return Eo(function(e,n){var r=-1,o=n.length,u=o>1?n[o-1]:i,a=o>2?n[2]:i;for(u=t.length>3&&"function"==typeof u?(o--,u):i,a&&Ki(n[0],n[1],a)&&(u=o<3?i:u,o=1),e=ee(e);++r<o;){var s=n[r];s&&t(e,s,r,u)}return e})}function ai(t,e){return function(n,r){if(null==n)return n;if(!_a(n))return t(n,r);for(var o=n.length,i=e?o:-1,u=ee(n);(e?i--:++i<o)&&!1!==r(u[i],i,u););return n}}function si(t){return function(e,n,r){for(var o=-1,i=ee(e),u=r(e),a=u.length;a--;){var s=u[t?a:++o];if(!1===n(i[s],s,i))break}return e}}function ci(t){return function(e){var n=On(e=Ha(e))?An(e):i,r=n?n[0]:e.charAt(0),o=n?Go(n,1).join(""):e.slice(1);return r[t]()+o}}function fi(t){return function(e){return en(Es(gs(e).replace(me,"")),t,"")}}function li(t){return function(){var e=arguments;switch(e.length){case 0:return new t;case 1:return new t(e[0]);case 2:return new t(e[0],e[1]);case 3:return new t(e[0],e[1],e[2]);case 4:return new t(e[0],e[1],e[2],e[3]);case 5:return new t(e[0],e[1],e[2],e[3],e[4]);case 6:return new t(e[0],e[1],e[2],e[3],e[4],e[5]);case 7:return new t(e[0],e[1],e[2],e[3],e[4],e[5],e[6])}var n=dr(t.prototype),r=t.apply(n,e);return Ra(r)?r:n}}function pi(t){return function(e,n,r){var o=ee(e);if(!_a(e)){var u=Ni(n,3);e=os(e),n=function(t){return u(o[t],t,o)}}var a=t(e,n,r);return a>-1?o[u?e[a]:a]:i}}function hi(t){return Ci(function(e){var n=e.length,r=n,o=gr.prototype.thru;for(t&&e.reverse();r--;){var u=e[r];if("function"!=typeof u)throw new oe(s);if(o&&!a&&"wrapper"==$i(u))var a=new gr([],!0)}for(r=a?r:n;++r<n;){var c=$i(u=e[r]),f="wrapper"==c?Mi(u):i;a=f&&Gi(f[0])&&f[1]==(E|b|x|O)&&!f[4].length&&1==f[9]?a[$i(f[0])].apply(a,f[3]):1==u.length&&Gi(u)?a[c]():a.thru(u)}return function(){var t=arguments,r=t[0];if(a&&1==t.length&&ya(r))return a.plant(r).value();for(var o=0,i=n?e[o].apply(this,t):r;++o<n;)i=e[o].call(this,i);return i}})}function di(t,e,n,o,u,a,s,c,f,l){var p=e&E,h=e&y,d=e&m,v=e&(b|w),g=e&S,_=d?i:li(t);return function y(){for(var m=arguments.length,b=r(m),w=m;w--;)b[w]=arguments[w];if(v)var x=Li(y),j=function(t,e){for(var n=t.length,r=0;n--;)t[n]===e&&++r;return r}(b,x);if(o&&(b=ei(b,o,u,v)),a&&(b=ni(b,a,s,v)),m-=j,v&&m<l){var E=Tn(b,x);return wi(t,e,di,y.placeholder,n,b,E,c,f,l-m)}var O=h?n:this,S=d?O[t]:t;return m=b.length,c?b=function(t,e){for(var n=t.length,r=Vn(e.length,n),o=ri(t);r--;){var u=e[r];t[r]=Vi(u,n)?o[u]:i}return t}(b,c):g&&m>1&&b.reverse(),p&&f<m&&(b.length=f),this&&this!==Me&&this instanceof y&&(S=_||li(S)),S.apply(O,b)}}function vi(t,e){return function(n,r){return function(t,e,n,r){return Kr(t,function(t,o,i){e(r,n(t),o,i)}),r}(n,t,e(r),{})}}function gi(t,e){return function(n,r){var o;if(n===i&&r===i)return e;if(n!==i&&(o=n),r!==i){if(o===i)return r;"string"==typeof n||"string"==typeof r?(n=zo(n),r=zo(r)):(n=No(n),r=No(r)),o=t(n,r)}return o}}function yi(t){return Ci(function(e){return e=Je(e,yn(Ni())),Eo(function(n){var r=this;return t(e,function(t){return He(t,r,n)})})})}function mi(t,e){var n=(e=e===i?" ":zo(e)).length;if(n<2)return n?jo(e,t):e;var r=jo(e,In(t/Pn(e)));return On(e)?Go(An(r),0,t).join(""):r.slice(0,t)}function _i(t){return function(e,n,o){return o&&"number"!=typeof o&&Ki(e,n,o)&&(n=o=i),e=Da(e),n===i?(n=e,e=0):n=Da(n),function(t,e,n,o){for(var i=-1,u=Hn(In((e-t)/(n||1)),0),a=r(u);u--;)a[o?u:++i]=t,t+=n;return a}(e,n,o=o===i?e<n?1:-1:Da(o),t)}}function bi(t){return function(e,n){return"string"==typeof e&&"string"==typeof n||(e=Wa(e),n=Wa(n)),t(e,n)}}function wi(t,e,n,r,o,u,a,s,c,f){var l=e&b;e|=l?x:j,(e&=~(l?j:x))&_||(e&=~(y|m));var p=[t,e,o,l?u:i,l?a:i,l?i:u,l?i:a,s,c,f],h=n.apply(i,p);return Gi(t)&&ru(h,p),h.placeholder=r,uu(h,t,e)}function xi(t){var e=te[t];return function(t,n){if(t=Wa(t),(n=null==n?0:Vn(qa(n),292))&&Un(t)){var r=(Ha(t)+"e").split("e");return+((r=(Ha(e(r[0]+"e"+(+r[1]+n)))+"e").split("e"))[0]+"e"+(+r[1]-n))}return e(t)}}var ji=tr&&1/kn(new tr([,-0]))[1]==M?function(t){return new tr(t)}:Ls;function Ei(t){return function(e){var n=Ui(e);return n==Z?Sn(e):n==nt?Cn(e):function(t,e){return Je(e,function(e){return[e,t[e]]})}(e,t(e))}}function Oi(t,e,n,o,u,a,c,f){var p=e&m;if(!p&&"function"!=typeof t)throw new oe(s);var h=o?o.length:0;if(h||(e&=~(x|j),o=u=i),c=c===i?c:Hn(qa(c),0),f=f===i?f:qa(f),h-=u?u.length:0,e&j){var d=o,v=u;o=u=i}var g=p?i:Mi(t),S=[t,e,n,o,u,d,v,a,c,f];if(g&&function(t,e){var n=t[1],r=e[1],o=n|r,i=o<(y|m|E),u=r==E&&n==b||r==E&&n==O&&t[7].length<=e[8]||r==(E|O)&&e[7].length<=e[8]&&n==b;if(!i&&!u)return t;r&y&&(t[2]=e[2],o|=n&y?0:_);var a=e[3];if(a){var s=t[3];t[3]=s?ei(s,a,e[4]):a,t[4]=s?Tn(t[3],l):e[4]}(a=e[5])&&(s=t[5],t[5]=s?ni(s,a,e[6]):a,t[6]=s?Tn(t[5],l):e[6]),(a=e[7])&&(t[7]=a),r&E&&(t[8]=null==t[8]?e[8]:Vn(t[8],e[8])),null==t[9]&&(t[9]=e[9]),t[0]=e[0],t[1]=o}(S,g),t=S[0],e=S[1],n=S[2],o=S[3],u=S[4],!(f=S[9]=S[9]===i?p?0:t.length:Hn(S[9]-h,0))&&e&(b|w)&&(e&=~(b|w)),e&&e!=y)R=e==b||e==w?function(t,e,n){var o=li(t);return function u(){for(var a=arguments.length,s=r(a),c=a,f=Li(u);c--;)s[c]=arguments[c];var l=a<3&&s[0]!==f&&s[a-1]!==f?[]:Tn(s,f);return(a-=l.length)<n?wi(t,e,di,u.placeholder,i,s,l,i,i,n-a):He(this&&this!==Me&&this instanceof u?o:t,this,s)}}(t,e,f):e!=x&&e!=(y|x)||u.length?di.apply(i,S):function(t,e,n,o){var i=e&y,u=li(t);return function e(){for(var a=-1,s=arguments.length,c=-1,f=o.length,l=r(f+s),p=this&&this!==Me&&this instanceof e?u:t;++c<f;)l[c]=o[c];for(;s--;)l[c++]=arguments[++a];return He(p,i?n:this,l)}}(t,e,n,o);else var R=function(t,e,n){var r=e&y,o=li(t);return function e(){return(this&&this!==Me&&this instanceof e?o:t).apply(r?n:this,arguments)}}(t,e,n);return uu((g?To:ru)(R,S),t,e)}function Si(t,e,n,r){return t===i||ha(t,ae[n])&&!fe.call(r,n)?e:t}function Ri(t,e,n,r,o,u){return Ra(t)&&Ra(e)&&(u.set(e,t),go(t,e,i,Ri,u),u.delete(e)),t}function Ti(t){return Pa(t)?i:t}function ki(t,e,n,r,o,u){var a=n&v,s=t.length,c=e.length;if(s!=c&&!(a&&c>s))return!1;var f=u.get(t),l=u.get(e);if(f&&l)return f==e&&l==t;var p=-1,h=!0,d=n&g?new wr:i;for(u.set(t,e),u.set(e,t);++p<s;){var y=t[p],m=e[p];if(r)var _=a?r(m,y,p,e,t,u):r(y,m,p,t,e,u);if(_!==i){if(_)continue;h=!1;break}if(d){if(!rn(e,function(t,e){if(!_n(d,e)&&(y===t||o(y,t,n,r,u)))return d.push(e)})){h=!1;break}}else if(y!==m&&!o(y,m,n,r,u)){h=!1;break}}return u.delete(t),u.delete(e),h}function Ci(t){return iu(tu(t,i,mu),t+"")}function Pi(t){return Xr(t,os,Di)}function Ai(t){return Xr(t,is,qi)}var Mi=rr?function(t){return rr.get(t)}:Ls;function $i(t){for(var e=t.name+"",n=or[e],r=fe.call(or,e)?n.length:0;r--;){var o=n[r],i=o.func;if(null==i||i==t)return o.name}return e}function Li(t){return(fe.call(hr,"placeholder")?hr:t).placeholder}function Ni(){var t=hr.iteratee||Ps;return t=t===Ps?so:t,arguments.length?t(arguments[0],arguments[1]):t}function zi(t,e){var n,r,o=t.__data__;return("string"==(r=typeof(n=e))||"number"==r||"symbol"==r||"boolean"==r?"__proto__"!==n:null===n)?o["string"==typeof e?"string":"hash"]:o.map}function Ii(t){for(var e=os(t),n=e.length;n--;){var r=e[n],o=t[r];e[n]=[r,o,Qi(o)]}return e}function Fi(t,e){var n=function(t,e){return null==t?i:t[e]}(t,e);return ao(n)?n:i}var Di=Dn?function(t){return null==t?[]:(t=ee(t),Ze(Dn(t),function(e){return $e.call(t,e)}))}:Us,qi=Dn?function(t){for(var e=[];t;)tn(e,Di(t)),t=Pe(t);return e}:Us,Ui=Qr;function Wi(t,e,n){for(var r=-1,o=(e=Ko(e,t)).length,i=!1;++r<o;){var u=fu(e[r]);if(!(i=null!=t&&n(t,u)))break;t=t[u]}return i||++r!=o?i:!!(o=null==t?0:t.length)&&Sa(o)&&Vi(u,o)&&(ya(t)||ga(t))}function Bi(t){return"function"!=typeof t.constructor||Xi(t)?{}:dr(Pe(t))}function Hi(t){return ya(t)||ga(t)||!!(ze&&t&&t[ze])}function Vi(t,e){var n=typeof t;return!!(e=null==e?$:e)&&("number"==n||"symbol"!=n&&Yt.test(t))&&t>-1&&t%1==0&&t<e}function Ki(t,e,n){if(!Ra(n))return!1;var r=typeof e;return!!("number"==r?_a(n)&&Vi(e,n.length):"string"==r&&e in n)&&ha(n[e],t)}function Yi(t,e){if(ya(t))return!1;var n=typeof t;return!("number"!=n&&"symbol"!=n&&"boolean"!=n&&null!=t&&!La(t))||Ct.test(t)||!kt.test(t)||null!=e&&t in ee(e)}function Gi(t){var e=$i(t),n=hr[e];if("function"!=typeof n||!(e in yr.prototype))return!1;if(t===n)return!0;var r=Mi(n);return!!r&&t===r[0]}(Xn&&Ui(new Xn(new ArrayBuffer(1)))!=ct||Qn&&Ui(new Qn)!=Z||Jn&&"[object Promise]"!=Ui(Jn.resolve())||tr&&Ui(new tr)!=nt||er&&Ui(new er)!=ut)&&(Ui=function(t){var e=Qr(t),n=e==J?t.constructor:i,r=n?lu(n):"";if(r)switch(r){case ir:return ct;case ur:return Z;case ar:return"[object Promise]";case sr:return nt;case cr:return ut}return e});var Zi=se?Ea:Ws;function Xi(t){var e=t&&t.constructor;return t===("function"==typeof e&&e.prototype||ae)}function Qi(t){return t==t&&!Ra(t)}function Ji(t,e){return function(n){return null!=n&&n[t]===e&&(e!==i||t in ee(n))}}function tu(t,e,n){return e=Hn(e===i?t.length-1:e,0),function(){for(var o=arguments,i=-1,u=Hn(o.length-e,0),a=r(u);++i<u;)a[i]=o[e+i];i=-1;for(var s=r(e+1);++i<e;)s[i]=o[i];return s[e]=n(a),He(t,this,s)}}function eu(t,e){return e.length<2?t:Zr(t,Po(e,0,-1))}function nu(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var ru=au(To),ou=zn||function(t,e){return Me.setTimeout(t,e)},iu=au(ko);function uu(t,e,n){var r=e+"";return iu(t,function(t,e){var n=e.length;if(!n)return t;var r=n-1;return e[r]=(n>1?"& ":"")+e[r],e=e.join(n>2?", ":" "),t.replace(zt,"{\n/* [wrapped with "+e+"] */\n")}(r,function(t,e){return Ke(D,function(n){var r="_."+n[0];e&n[1]&&!Xe(t,r)&&t.push(r)}),t.sort()}(function(t){var e=t.match(It);return e?e[1].split(Ft):[]}(r),n)))}function au(t){var e=0,n=0;return function(){var r=Kn(),o=C-(r-n);if(n=r,o>0){if(++e>=k)return arguments[0]}else e=0;return t.apply(i,arguments)}}function su(t,e){var n=-1,r=t.length,o=r-1;for(e=e===i?r:e;++n<e;){var u=xo(n,o),a=t[u];t[u]=t[n],t[n]=a}return t.length=e,t}var cu=function(t){var e=aa(t,function(t){return n.size===f&&n.clear(),t}),n=e.cache;return e}(function(t){var e=[];return 46===t.charCodeAt(0)&&e.push(""),t.replace(Pt,function(t,n,r,o){e.push(r?o.replace(qt,"$1"):n||t)}),e});function fu(t){if("string"==typeof t||La(t))return t;var e=t+"";return"0"==e&&1/t==-M?"-0":e}function lu(t){if(null!=t){try{return ce.call(t)}catch(t){}try{return t+""}catch(t){}}return""}function pu(t){if(t instanceof yr)return t.clone();var e=new gr(t.__wrapped__,t.__chain__);return e.__actions__=ri(t.__actions__),e.__index__=t.__index__,e.__values__=t.__values__,e}var hu=Eo(function(t,e){return ba(t)?Ir(t,Br(e,1,ba,!0)):[]}),du=Eo(function(t,e){var n=ju(e);return ba(n)&&(n=i),ba(t)?Ir(t,Br(e,1,ba,!0),Ni(n,2)):[]}),vu=Eo(function(t,e){var n=ju(e);return ba(n)&&(n=i),ba(t)?Ir(t,Br(e,1,ba,!0),i,n):[]});function gu(t,e,n){var r=null==t?0:t.length;if(!r)return-1;var o=null==n?0:qa(n);return o<0&&(o=Hn(r+o,0)),an(t,Ni(e,3),o)}function yu(t,e,n){var r=null==t?0:t.length;if(!r)return-1;var o=r-1;return n!==i&&(o=qa(n),o=n<0?Hn(r+o,0):Vn(o,r-1)),an(t,Ni(e,3),o,!0)}function mu(t){return null!=t&&t.length?Br(t,1):[]}function _u(t){return t&&t.length?t[0]:i}var bu=Eo(function(t){var e=Je(t,Ho);return e.length&&e[0]===t[0]?no(e):[]}),wu=Eo(function(t){var e=ju(t),n=Je(t,Ho);return e===ju(n)?e=i:n.pop(),n.length&&n[0]===t[0]?no(n,Ni(e,2)):[]}),xu=Eo(function(t){var e=ju(t),n=Je(t,Ho);return(e="function"==typeof e?e:i)&&n.pop(),n.length&&n[0]===t[0]?no(n,i,e):[]});function ju(t){var e=null==t?0:t.length;return e?t[e-1]:i}var Eu=Eo(Ou);function Ou(t,e){return t&&t.length&&e&&e.length?bo(t,e):t}var Su=Ci(function(t,e){var n=null==t?0:t.length,r=Mr(t,e);return wo(t,Je(e,function(t){return Vi(t,n)?+t:t}).sort(ti)),r});function Ru(t){return null==t?t:Zn.call(t)}var Tu=Eo(function(t){return Io(Br(t,1,ba,!0))}),ku=Eo(function(t){var e=ju(t);return ba(e)&&(e=i),Io(Br(t,1,ba,!0),Ni(e,2))}),Cu=Eo(function(t){var e=ju(t);return e="function"==typeof e?e:i,Io(Br(t,1,ba,!0),i,e)});function Pu(t){if(!t||!t.length)return[];var e=0;return t=Ze(t,function(t){if(ba(t))return e=Hn(t.length,e),!0}),gn(e,function(e){return Je(t,pn(e))})}function Au(t,e){if(!t||!t.length)return[];var n=Pu(t);return null==e?n:Je(n,function(t){return He(e,i,t)})}var Mu=Eo(function(t,e){return ba(t)?Ir(t,e):[]}),$u=Eo(function(t){return Wo(Ze(t,ba))}),Lu=Eo(function(t){var e=ju(t);return ba(e)&&(e=i),Wo(Ze(t,ba),Ni(e,2))}),Nu=Eo(function(t){var e=ju(t);return e="function"==typeof e?e:i,Wo(Ze(t,ba),i,e)}),zu=Eo(Pu);var Iu=Eo(function(t){var e=t.length,n=e>1?t[e-1]:i;return Au(t,n="function"==typeof n?(t.pop(),n):i)});function Fu(t){var e=hr(t);return e.__chain__=!0,e}function Du(t,e){return e(t)}var qu=Ci(function(t){var e=t.length,n=e?t[0]:0,r=this.__wrapped__,o=function(e){return Mr(e,t)};return!(e>1||this.__actions__.length)&&r instanceof yr&&Vi(n)?((r=r.slice(n,+n+(e?1:0))).__actions__.push({func:Du,args:[o],thisArg:i}),new gr(r,this.__chain__).thru(function(t){return e&&!t.length&&t.push(i),t})):this.thru(o)});var Uu=ii(function(t,e,n){fe.call(t,n)?++t[n]:Ar(t,n,1)});var Wu=pi(gu),Bu=pi(yu);function Hu(t,e){return(ya(t)?Ke:Fr)(t,Ni(e,3))}function Vu(t,e){return(ya(t)?Ye:Dr)(t,Ni(e,3))}var Ku=ii(function(t,e,n){fe.call(t,n)?t[n].push(e):Ar(t,n,[e])});var Yu=Eo(function(t,e,n){var o=-1,i="function"==typeof e,u=_a(t)?r(t.length):[];return Fr(t,function(t){u[++o]=i?He(e,t,n):ro(t,e,n)}),u}),Gu=ii(function(t,e,n){Ar(t,n,e)});function Zu(t,e){return(ya(t)?Je:po)(t,Ni(e,3))}var Xu=ii(function(t,e,n){t[n?0:1].push(e)},function(){return[[],[]]});var Qu=Eo(function(t,e){if(null==t)return[];var n=e.length;return n>1&&Ki(t,e[0],e[1])?e=[]:n>2&&Ki(e[0],e[1],e[2])&&(e=[e[0]]),mo(t,Br(e,1),[])}),Ju=Nn||function(){return Me.Date.now()};function ta(t,e,n){return e=n?i:e,e=t&&null==e?t.length:e,Oi(t,E,i,i,i,i,e)}function ea(t,e){var n;if("function"!=typeof e)throw new oe(s);return t=qa(t),function(){return--t>0&&(n=e.apply(this,arguments)),t<=1&&(e=i),n}}var na=Eo(function(t,e,n){var r=y;if(n.length){var o=Tn(n,Li(na));r|=x}return Oi(t,r,e,n,o)}),ra=Eo(function(t,e,n){var r=y|m;if(n.length){var o=Tn(n,Li(ra));r|=x}return Oi(e,r,t,n,o)});function oa(t,e,n){var r,o,u,a,c,f,l=0,p=!1,h=!1,d=!0;if("function"!=typeof t)throw new oe(s);function v(e){var n=r,u=o;return r=o=i,l=e,a=t.apply(u,n)}function g(t){var n=t-f;return f===i||n>=e||n<0||h&&t-l>=u}function y(){var t=Ju();if(g(t))return m(t);c=ou(y,function(t){var n=e-(t-f);return h?Vn(n,u-(t-l)):n}(t))}function m(t){return c=i,d&&r?v(t):(r=o=i,a)}function _(){var t=Ju(),n=g(t);if(r=arguments,o=this,f=t,n){if(c===i)return function(t){return l=t,c=ou(y,e),p?v(t):a}(f);if(h)return Zo(c),c=ou(y,e),v(f)}return c===i&&(c=ou(y,e)),a}return e=Wa(e)||0,Ra(n)&&(p=!!n.leading,u=(h="maxWait"in n)?Hn(Wa(n.maxWait)||0,e):u,d="trailing"in n?!!n.trailing:d),_.cancel=function(){c!==i&&Zo(c),l=0,r=f=o=c=i},_.flush=function(){return c===i?a:m(Ju())},_}var ia=Eo(function(t,e){return zr(t,1,e)}),ua=Eo(function(t,e,n){return zr(t,Wa(e)||0,n)});function aa(t,e){if("function"!=typeof t||null!=e&&"function"!=typeof e)throw new oe(s);var n=function(){var r=arguments,o=e?e.apply(this,r):r[0],i=n.cache;if(i.has(o))return i.get(o);var u=t.apply(this,r);return n.cache=i.set(o,u)||i,u};return n.cache=new(aa.Cache||br),n}function sa(t){if("function"!=typeof t)throw new oe(s);return function(){var e=arguments;switch(e.length){case 0:return!t.call(this);case 1:return!t.call(this,e[0]);case 2:return!t.call(this,e[0],e[1]);case 3:return!t.call(this,e[0],e[1],e[2])}return!t.apply(this,e)}}aa.Cache=br;var ca=Yo(function(t,e){var n=(e=1==e.length&&ya(e[0])?Je(e[0],yn(Ni())):Je(Br(e,1),yn(Ni()))).length;return Eo(function(r){for(var o=-1,i=Vn(r.length,n);++o<i;)r[o]=e[o].call(this,r[o]);return He(t,this,r)})}),fa=Eo(function(t,e){var n=Tn(e,Li(fa));return Oi(t,x,i,e,n)}),la=Eo(function(t,e){var n=Tn(e,Li(la));return Oi(t,j,i,e,n)}),pa=Ci(function(t,e){return Oi(t,O,i,i,i,e)});function ha(t,e){return t===e||t!=t&&e!=e}var da=bi(Jr),va=bi(function(t,e){return t>=e}),ga=oo(function(){return arguments}())?oo:function(t){return Ta(t)&&fe.call(t,"callee")&&!$e.call(t,"callee")},ya=r.isArray,ma=Fe?yn(Fe):function(t){return Ta(t)&&Qr(t)==st};function _a(t){return null!=t&&Sa(t.length)&&!Ea(t)}function ba(t){return Ta(t)&&_a(t)}var wa=qn||Ws,xa=De?yn(De):function(t){return Ta(t)&&Qr(t)==H};function ja(t){if(!Ta(t))return!1;var e=Qr(t);return e==K||e==V||"string"==typeof t.message&&"string"==typeof t.name&&!Pa(t)}function Ea(t){if(!Ra(t))return!1;var e=Qr(t);return e==Y||e==G||e==W||e==tt}function Oa(t){return"number"==typeof t&&t==qa(t)}function Sa(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=$}function Ra(t){var e=typeof t;return null!=t&&("object"==e||"function"==e)}function Ta(t){return null!=t&&"object"==typeof t}var ka=qe?yn(qe):function(t){return Ta(t)&&Ui(t)==Z};function Ca(t){return"number"==typeof t||Ta(t)&&Qr(t)==X}function Pa(t){if(!Ta(t)||Qr(t)!=J)return!1;var e=Pe(t);if(null===e)return!0;var n=fe.call(e,"constructor")&&e.constructor;return"function"==typeof n&&n instanceof n&&ce.call(n)==de}var Aa=Ue?yn(Ue):function(t){return Ta(t)&&Qr(t)==et};var Ma=We?yn(We):function(t){return Ta(t)&&Ui(t)==nt};function $a(t){return"string"==typeof t||!ya(t)&&Ta(t)&&Qr(t)==rt}function La(t){return"symbol"==typeof t||Ta(t)&&Qr(t)==ot}var Na=Be?yn(Be):function(t){return Ta(t)&&Sa(t.length)&&!!Se[Qr(t)]};var za=bi(lo),Ia=bi(function(t,e){return t<=e});function Fa(t){if(!t)return[];if(_a(t))return $a(t)?An(t):ri(t);if(Ie&&t[Ie])return function(t){for(var e,n=[];!(e=t.next()).done;)n.push(e.value);return n}(t[Ie]());var e=Ui(t);return(e==Z?Sn:e==nt?kn:hs)(t)}function Da(t){return t?(t=Wa(t))===M||t===-M?(t<0?-1:1)*L:t==t?t:0:0===t?t:0}function qa(t){var e=Da(t),n=e%1;return e==e?n?e-n:e:0}function Ua(t){return t?$r(qa(t),0,z):0}function Wa(t){if("number"==typeof t)return t;if(La(t))return N;if(Ra(t)){var e="function"==typeof t.valueOf?t.valueOf():t;t=Ra(e)?e+"":e}if("string"!=typeof t)return 0===t?t:+t;t=t.replace($t,"");var n=Ht.test(t);return n||Kt.test(t)?Ce(t.slice(2),n?2:8):Bt.test(t)?N:+t}function Ba(t){return oi(t,is(t))}function Ha(t){return null==t?"":zo(t)}var Va=ui(function(t,e){if(Xi(e)||_a(e))oi(e,os(e),t);else for(var n in e)fe.call(e,n)&&Tr(t,n,e[n])}),Ka=ui(function(t,e){oi(e,is(e),t)}),Ya=ui(function(t,e,n,r){oi(e,is(e),t,r)}),Ga=ui(function(t,e,n,r){oi(e,os(e),t,r)}),Za=Ci(Mr);var Xa=Eo(function(t,e){t=ee(t);var n=-1,r=e.length,o=r>2?e[2]:i;for(o&&Ki(e[0],e[1],o)&&(r=1);++n<r;)for(var u=e[n],a=is(u),s=-1,c=a.length;++s<c;){var f=a[s],l=t[f];(l===i||ha(l,ae[f])&&!fe.call(t,f))&&(t[f]=u[f])}return t}),Qa=Eo(function(t){return t.push(i,Ri),He(as,i,t)});function Ja(t,e,n){var r=null==t?i:Zr(t,e);return r===i?n:r}function ts(t,e){return null!=t&&Wi(t,e,eo)}var es=vi(function(t,e,n){null!=e&&"function"!=typeof e.toString&&(e=he.call(e)),t[e]=n},Rs(Cs)),ns=vi(function(t,e,n){null!=e&&"function"!=typeof e.toString&&(e=he.call(e)),fe.call(t,e)?t[e].push(n):t[e]=[n]},Ni),rs=Eo(ro);function os(t){return _a(t)?jr(t):co(t)}function is(t){return _a(t)?jr(t,!0):fo(t)}var us=ui(function(t,e,n){go(t,e,n)}),as=ui(function(t,e,n,r){go(t,e,n,r)}),ss=Ci(function(t,e){var n={};if(null==t)return n;var r=!1;e=Je(e,function(e){return e=Ko(e,t),r||(r=e.length>1),e}),oi(t,Ai(t),n),r&&(n=Lr(n,p|h|d,Ti));for(var o=e.length;o--;)Fo(n,e[o]);return n});var cs=Ci(function(t,e){return null==t?{}:function(t,e){return _o(t,e,function(e,n){return ts(t,n)})}(t,e)});function fs(t,e){if(null==t)return{};var n=Je(Ai(t),function(t){return[t]});return e=Ni(e),_o(t,n,function(t,n){return e(t,n[0])})}var ls=Ei(os),ps=Ei(is);function hs(t){return null==t?[]:mn(t,os(t))}var ds=fi(function(t,e,n){return e=e.toLowerCase(),t+(n?vs(e):e)});function vs(t){return js(Ha(t).toLowerCase())}function gs(t){return(t=Ha(t))&&t.replace(Gt,xn).replace(_e,"")}var ys=fi(function(t,e,n){return t+(n?"-":"")+e.toLowerCase()}),ms=fi(function(t,e,n){return t+(n?" ":"")+e.toLowerCase()}),_s=ci("toLowerCase");var bs=fi(function(t,e,n){return t+(n?"_":"")+e.toLowerCase()});var ws=fi(function(t,e,n){return t+(n?" ":"")+js(e)});var xs=fi(function(t,e,n){return t+(n?" ":"")+e.toUpperCase()}),js=ci("toUpperCase");function Es(t,e,n){return t=Ha(t),(e=n?i:e)===i?function(t){return je.test(t)}(t)?function(t){return t.match(we)||[]}(t):function(t){return t.match(Dt)||[]}(t):t.match(e)||[]}var Os=Eo(function(t,e){try{return He(t,i,e)}catch(t){return ja(t)?t:new Qt(t)}}),Ss=Ci(function(t,e){return Ke(e,function(e){e=fu(e),Ar(t,e,na(t[e],t))}),t});function Rs(t){return function(){return t}}var Ts=hi(),ks=hi(!0);function Cs(t){return t}function Ps(t){return so("function"==typeof t?t:Lr(t,p))}var As=Eo(function(t,e){return function(n){return ro(n,t,e)}}),Ms=Eo(function(t,e){return function(n){return ro(t,n,e)}});function $s(t,e,n){var r=os(e),o=Gr(e,r);null!=n||Ra(e)&&(o.length||!r.length)||(n=e,e=t,t=this,o=Gr(e,os(e)));var i=!(Ra(n)&&"chain"in n&&!n.chain),u=Ea(t);return Ke(o,function(n){var r=e[n];t[n]=r,u&&(t.prototype[n]=function(){var e=this.__chain__;if(i||e){var n=t(this.__wrapped__);return(n.__actions__=ri(this.__actions__)).push({func:r,args:arguments,thisArg:t}),n.__chain__=e,n}return r.apply(t,tn([this.value()],arguments))})}),t}function Ls(){}var Ns=yi(Je),zs=yi(Ge),Is=yi(rn);function Fs(t){return Yi(t)?pn(fu(t)):function(t){return function(e){return Zr(e,t)}}(t)}var Ds=_i(),qs=_i(!0);function Us(){return[]}function Ws(){return!1}var Bs=gi(function(t,e){return t+e},0),Hs=xi("ceil"),Vs=gi(function(t,e){return t/e},1),Ks=xi("floor");var Ys,Gs=gi(function(t,e){return t*e},1),Zs=xi("round"),Xs=gi(function(t,e){return t-e},0);return hr.after=function(t,e){if("function"!=typeof e)throw new oe(s);return t=qa(t),function(){if(--t<1)return e.apply(this,arguments)}},hr.ary=ta,hr.assign=Va,hr.assignIn=Ka,hr.assignInWith=Ya,hr.assignWith=Ga,hr.at=Za,hr.before=ea,hr.bind=na,hr.bindAll=Ss,hr.bindKey=ra,hr.castArray=function(){if(!arguments.length)return[];var t=arguments[0];return ya(t)?t:[t]},hr.chain=Fu,hr.chunk=function(t,e,n){e=(n?Ki(t,e,n):e===i)?1:Hn(qa(e),0);var o=null==t?0:t.length;if(!o||e<1)return[];for(var u=0,a=0,s=r(In(o/e));u<o;)s[a++]=Po(t,u,u+=e);return s},hr.compact=function(t){for(var e=-1,n=null==t?0:t.length,r=0,o=[];++e<n;){var i=t[e];i&&(o[r++]=i)}return o},hr.concat=function(){var t=arguments.length;if(!t)return[];for(var e=r(t-1),n=arguments[0],o=t;o--;)e[o-1]=arguments[o];return tn(ya(n)?ri(n):[n],Br(e,1))},hr.cond=function(t){var e=null==t?0:t.length,n=Ni();return t=e?Je(t,function(t){if("function"!=typeof t[1])throw new oe(s);return[n(t[0]),t[1]]}):[],Eo(function(n){for(var r=-1;++r<e;){var o=t[r];if(He(o[0],this,n))return He(o[1],this,n)}})},hr.conforms=function(t){return function(t){var e=os(t);return function(n){return Nr(n,t,e)}}(Lr(t,p))},hr.constant=Rs,hr.countBy=Uu,hr.create=function(t,e){var n=dr(t);return null==e?n:Pr(n,e)},hr.curry=function t(e,n,r){var o=Oi(e,b,i,i,i,i,i,n=r?i:n);return o.placeholder=t.placeholder,o},hr.curryRight=function t(e,n,r){var o=Oi(e,w,i,i,i,i,i,n=r?i:n);return o.placeholder=t.placeholder,o},hr.debounce=oa,hr.defaults=Xa,hr.defaultsDeep=Qa,hr.defer=ia,hr.delay=ua,hr.difference=hu,hr.differenceBy=du,hr.differenceWith=vu,hr.drop=function(t,e,n){var r=null==t?0:t.length;return r?Po(t,(e=n||e===i?1:qa(e))<0?0:e,r):[]},hr.dropRight=function(t,e,n){var r=null==t?0:t.length;return r?Po(t,0,(e=r-(e=n||e===i?1:qa(e)))<0?0:e):[]},hr.dropRightWhile=function(t,e){return t&&t.length?qo(t,Ni(e,3),!0,!0):[]},hr.dropWhile=function(t,e){return t&&t.length?qo(t,Ni(e,3),!0):[]},hr.fill=function(t,e,n,r){var o=null==t?0:t.length;return o?(n&&"number"!=typeof n&&Ki(t,e,n)&&(n=0,r=o),function(t,e,n,r){var o=t.length;for((n=qa(n))<0&&(n=-n>o?0:o+n),(r=r===i||r>o?o:qa(r))<0&&(r+=o),r=n>r?0:Ua(r);n<r;)t[n++]=e;return t}(t,e,n,r)):[]},hr.filter=function(t,e){return(ya(t)?Ze:Wr)(t,Ni(e,3))},hr.flatMap=function(t,e){return Br(Zu(t,e),1)},hr.flatMapDeep=function(t,e){return Br(Zu(t,e),M)},hr.flatMapDepth=function(t,e,n){return n=n===i?1:qa(n),Br(Zu(t,e),n)},hr.flatten=mu,hr.flattenDeep=function(t){return null!=t&&t.length?Br(t,M):[]},hr.flattenDepth=function(t,e){return null!=t&&t.length?Br(t,e=e===i?1:qa(e)):[]},hr.flip=function(t){return Oi(t,S)},hr.flow=Ts,hr.flowRight=ks,hr.fromPairs=function(t){for(var e=-1,n=null==t?0:t.length,r={};++e<n;){var o=t[e];r[o[0]]=o[1]}return r},hr.functions=function(t){return null==t?[]:Gr(t,os(t))},hr.functionsIn=function(t){return null==t?[]:Gr(t,is(t))},hr.groupBy=Ku,hr.initial=function(t){return null!=t&&t.length?Po(t,0,-1):[]},hr.intersection=bu,hr.intersectionBy=wu,hr.intersectionWith=xu,hr.invert=es,hr.invertBy=ns,hr.invokeMap=Yu,hr.iteratee=Ps,hr.keyBy=Gu,hr.keys=os,hr.keysIn=is,hr.map=Zu,hr.mapKeys=function(t,e){var n={};return e=Ni(e,3),Kr(t,function(t,r,o){Ar(n,e(t,r,o),t)}),n},hr.mapValues=function(t,e){var n={};return e=Ni(e,3),Kr(t,function(t,r,o){Ar(n,r,e(t,r,o))}),n},hr.matches=function(t){return ho(Lr(t,p))},hr.matchesProperty=function(t,e){return vo(t,Lr(e,p))},hr.memoize=aa,hr.merge=us,hr.mergeWith=as,hr.method=As,hr.methodOf=Ms,hr.mixin=$s,hr.negate=sa,hr.nthArg=function(t){return t=qa(t),Eo(function(e){return yo(e,t)})},hr.omit=ss,hr.omitBy=function(t,e){return fs(t,sa(Ni(e)))},hr.once=function(t){return ea(2,t)},hr.orderBy=function(t,e,n,r){return null==t?[]:(ya(e)||(e=null==e?[]:[e]),ya(n=r?i:n)||(n=null==n?[]:[n]),mo(t,e,n))},hr.over=Ns,hr.overArgs=ca,hr.overEvery=zs,hr.overSome=Is,hr.partial=fa,hr.partialRight=la,hr.partition=Xu,hr.pick=cs,hr.pickBy=fs,hr.property=Fs,hr.propertyOf=function(t){return function(e){return null==t?i:Zr(t,e)}},hr.pull=Eu,hr.pullAll=Ou,hr.pullAllBy=function(t,e,n){return t&&t.length&&e&&e.length?bo(t,e,Ni(n,2)):t},hr.pullAllWith=function(t,e,n){return t&&t.length&&e&&e.length?bo(t,e,i,n):t},hr.pullAt=Su,hr.range=Ds,hr.rangeRight=qs,hr.rearg=pa,hr.reject=function(t,e){return(ya(t)?Ze:Wr)(t,sa(Ni(e,3)))},hr.remove=function(t,e){var n=[];if(!t||!t.length)return n;var r=-1,o=[],i=t.length;for(e=Ni(e,3);++r<i;){var u=t[r];e(u,r,t)&&(n.push(u),o.push(r))}return wo(t,o),n},hr.rest=function(t,e){if("function"!=typeof t)throw new oe(s);return Eo(t,e=e===i?e:qa(e))},hr.reverse=Ru,hr.sampleSize=function(t,e,n){return e=(n?Ki(t,e,n):e===i)?1:qa(e),(ya(t)?Or:So)(t,e)},hr.set=function(t,e,n){return null==t?t:Ro(t,e,n)},hr.setWith=function(t,e,n,r){return r="function"==typeof r?r:i,null==t?t:Ro(t,e,n,r)},hr.shuffle=function(t){return(ya(t)?Sr:Co)(t)},hr.slice=function(t,e,n){var r=null==t?0:t.length;return r?(n&&"number"!=typeof n&&Ki(t,e,n)?(e=0,n=r):(e=null==e?0:qa(e),n=n===i?r:qa(n)),Po(t,e,n)):[]},hr.sortBy=Qu,hr.sortedUniq=function(t){return t&&t.length?Lo(t):[]},hr.sortedUniqBy=function(t,e){return t&&t.length?Lo(t,Ni(e,2)):[]},hr.split=function(t,e,n){return n&&"number"!=typeof n&&Ki(t,e,n)&&(e=n=i),(n=n===i?z:n>>>0)?(t=Ha(t))&&("string"==typeof e||null!=e&&!Aa(e))&&!(e=zo(e))&&On(t)?Go(An(t),0,n):t.split(e,n):[]},hr.spread=function(t,e){if("function"!=typeof t)throw new oe(s);return e=null==e?0:Hn(qa(e),0),Eo(function(n){var r=n[e],o=Go(n,0,e);return r&&tn(o,r),He(t,this,o)})},hr.tail=function(t){var e=null==t?0:t.length;return e?Po(t,1,e):[]},hr.take=function(t,e,n){return t&&t.length?Po(t,0,(e=n||e===i?1:qa(e))<0?0:e):[]},hr.takeRight=function(t,e,n){var r=null==t?0:t.length;return r?Po(t,(e=r-(e=n||e===i?1:qa(e)))<0?0:e,r):[]},hr.takeRightWhile=function(t,e){return t&&t.length?qo(t,Ni(e,3),!1,!0):[]},hr.takeWhile=function(t,e){return t&&t.length?qo(t,Ni(e,3)):[]},hr.tap=function(t,e){return e(t),t},hr.throttle=function(t,e,n){var r=!0,o=!0;if("function"!=typeof t)throw new oe(s);return Ra(n)&&(r="leading"in n?!!n.leading:r,o="trailing"in n?!!n.trailing:o),oa(t,e,{leading:r,maxWait:e,trailing:o})},hr.thru=Du,hr.toArray=Fa,hr.toPairs=ls,hr.toPairsIn=ps,hr.toPath=function(t){return ya(t)?Je(t,fu):La(t)?[t]:ri(cu(Ha(t)))},hr.toPlainObject=Ba,hr.transform=function(t,e,n){var r=ya(t),o=r||wa(t)||Na(t);if(e=Ni(e,4),null==n){var i=t&&t.constructor;n=o?r?new i:[]:Ra(t)&&Ea(i)?dr(Pe(t)):{}}return(o?Ke:Kr)(t,function(t,r,o){return e(n,t,r,o)}),n},hr.unary=function(t){return ta(t,1)},hr.union=Tu,hr.unionBy=ku,hr.unionWith=Cu,hr.uniq=function(t){return t&&t.length?Io(t):[]},hr.uniqBy=function(t,e){return t&&t.length?Io(t,Ni(e,2)):[]},hr.uniqWith=function(t,e){return e="function"==typeof e?e:i,t&&t.length?Io(t,i,e):[]},hr.unset=function(t,e){return null==t||Fo(t,e)},hr.unzip=Pu,hr.unzipWith=Au,hr.update=function(t,e,n){return null==t?t:Do(t,e,Vo(n))},hr.updateWith=function(t,e,n,r){return r="function"==typeof r?r:i,null==t?t:Do(t,e,Vo(n),r)},hr.values=hs,hr.valuesIn=function(t){return null==t?[]:mn(t,is(t))},hr.without=Mu,hr.words=Es,hr.wrap=function(t,e){return fa(Vo(e),t)},hr.xor=$u,hr.xorBy=Lu,hr.xorWith=Nu,hr.zip=zu,hr.zipObject=function(t,e){return Bo(t||[],e||[],Tr)},hr.zipObjectDeep=function(t,e){return Bo(t||[],e||[],Ro)},hr.zipWith=Iu,hr.entries=ls,hr.entriesIn=ps,hr.extend=Ka,hr.extendWith=Ya,$s(hr,hr),hr.add=Bs,hr.attempt=Os,hr.camelCase=ds,hr.capitalize=vs,hr.ceil=Hs,hr.clamp=function(t,e,n){return n===i&&(n=e,e=i),n!==i&&(n=(n=Wa(n))==n?n:0),e!==i&&(e=(e=Wa(e))==e?e:0),$r(Wa(t),e,n)},hr.clone=function(t){return Lr(t,d)},hr.cloneDeep=function(t){return Lr(t,p|d)},hr.cloneDeepWith=function(t,e){return Lr(t,p|d,e="function"==typeof e?e:i)},hr.cloneWith=function(t,e){return Lr(t,d,e="function"==typeof e?e:i)},hr.conformsTo=function(t,e){return null==e||Nr(t,e,os(e))},hr.deburr=gs,hr.defaultTo=function(t,e){return null==t||t!=t?e:t},hr.divide=Vs,hr.endsWith=function(t,e,n){t=Ha(t),e=zo(e);var r=t.length,o=n=n===i?r:$r(qa(n),0,r);return(n-=e.length)>=0&&t.slice(n,o)==e},hr.eq=ha,hr.escape=function(t){return(t=Ha(t))&&Ot.test(t)?t.replace(jt,jn):t},hr.escapeRegExp=function(t){return(t=Ha(t))&&Mt.test(t)?t.replace(At,"\\$&"):t},hr.every=function(t,e,n){var r=ya(t)?Ge:qr;return n&&Ki(t,e,n)&&(e=i),r(t,Ni(e,3))},hr.find=Wu,hr.findIndex=gu,hr.findKey=function(t,e){return un(t,Ni(e,3),Kr)},hr.findLast=Bu,hr.findLastIndex=yu,hr.findLastKey=function(t,e){return un(t,Ni(e,3),Yr)},hr.floor=Ks,hr.forEach=Hu,hr.forEachRight=Vu,hr.forIn=function(t,e){return null==t?t:Hr(t,Ni(e,3),is)},hr.forInRight=function(t,e){return null==t?t:Vr(t,Ni(e,3),is)},hr.forOwn=function(t,e){return t&&Kr(t,Ni(e,3))},hr.forOwnRight=function(t,e){return t&&Yr(t,Ni(e,3))},hr.get=Ja,hr.gt=da,hr.gte=va,hr.has=function(t,e){return null!=t&&Wi(t,e,to)},hr.hasIn=ts,hr.head=_u,hr.identity=Cs,hr.includes=function(t,e,n,r){t=_a(t)?t:hs(t),n=n&&!r?qa(n):0;var o=t.length;return n<0&&(n=Hn(o+n,0)),$a(t)?n<=o&&t.indexOf(e,n)>-1:!!o&&sn(t,e,n)>-1},hr.indexOf=function(t,e,n){var r=null==t?0:t.length;if(!r)return-1;var o=null==n?0:qa(n);return o<0&&(o=Hn(r+o,0)),sn(t,e,o)},hr.inRange=function(t,e,n){return e=Da(e),n===i?(n=e,e=0):n=Da(n),function(t,e,n){return t>=Vn(e,n)&&t<Hn(e,n)}(t=Wa(t),e,n)},hr.invoke=rs,hr.isArguments=ga,hr.isArray=ya,hr.isArrayBuffer=ma,hr.isArrayLike=_a,hr.isArrayLikeObject=ba,hr.isBoolean=function(t){return!0===t||!1===t||Ta(t)&&Qr(t)==B},hr.isBuffer=wa,hr.isDate=xa,hr.isElement=function(t){return Ta(t)&&1===t.nodeType&&!Pa(t)},hr.isEmpty=function(t){if(null==t)return!0;if(_a(t)&&(ya(t)||"string"==typeof t||"function"==typeof t.splice||wa(t)||Na(t)||ga(t)))return!t.length;var e=Ui(t);if(e==Z||e==nt)return!t.size;if(Xi(t))return!co(t).length;for(var n in t)if(fe.call(t,n))return!1;return!0},hr.isEqual=function(t,e){return io(t,e)},hr.isEqualWith=function(t,e,n){var r=(n="function"==typeof n?n:i)?n(t,e):i;return r===i?io(t,e,i,n):!!r},hr.isError=ja,hr.isFinite=function(t){return"number"==typeof t&&Un(t)},hr.isFunction=Ea,hr.isInteger=Oa,hr.isLength=Sa,hr.isMap=ka,hr.isMatch=function(t,e){return t===e||uo(t,e,Ii(e))},hr.isMatchWith=function(t,e,n){return n="function"==typeof n?n:i,uo(t,e,Ii(e),n)},hr.isNaN=function(t){return Ca(t)&&t!=+t},hr.isNative=function(t){if(Zi(t))throw new Qt(a);return ao(t)},hr.isNil=function(t){return null==t},hr.isNull=function(t){return null===t},hr.isNumber=Ca,hr.isObject=Ra,hr.isObjectLike=Ta,hr.isPlainObject=Pa,hr.isRegExp=Aa,hr.isSafeInteger=function(t){return Oa(t)&&t>=-$&&t<=$},hr.isSet=Ma,hr.isString=$a,hr.isSymbol=La,hr.isTypedArray=Na,hr.isUndefined=function(t){return t===i},hr.isWeakMap=function(t){return Ta(t)&&Ui(t)==ut},hr.isWeakSet=function(t){return Ta(t)&&Qr(t)==at},hr.join=function(t,e){return null==t?"":Wn.call(t,e)},hr.kebabCase=ys,hr.last=ju,hr.lastIndexOf=function(t,e,n){var r=null==t?0:t.length;if(!r)return-1;var o=r;return n!==i&&(o=(o=qa(n))<0?Hn(r+o,0):Vn(o,r-1)),e==e?function(t,e,n){for(var r=n+1;r--;)if(t[r]===e)return r;return r}(t,e,o):an(t,fn,o,!0)},hr.lowerCase=ms,hr.lowerFirst=_s,hr.lt=za,hr.lte=Ia,hr.max=function(t){return t&&t.length?Ur(t,Cs,Jr):i},hr.maxBy=function(t,e){return t&&t.length?Ur(t,Ni(e,2),Jr):i},hr.mean=function(t){return ln(t,Cs)},hr.meanBy=function(t,e){return ln(t,Ni(e,2))},hr.min=function(t){return t&&t.length?Ur(t,Cs,lo):i},hr.minBy=function(t,e){return t&&t.length?Ur(t,Ni(e,2),lo):i},hr.stubArray=Us,hr.stubFalse=Ws,hr.stubObject=function(){return{}},hr.stubString=function(){return""},hr.stubTrue=function(){return!0},hr.multiply=Gs,hr.nth=function(t,e){return t&&t.length?yo(t,qa(e)):i},hr.noConflict=function(){return Me._===this&&(Me._=ve),this},hr.noop=Ls,hr.now=Ju,hr.pad=function(t,e,n){t=Ha(t);var r=(e=qa(e))?Pn(t):0;if(!e||r>=e)return t;var o=(e-r)/2;return mi(Fn(o),n)+t+mi(In(o),n)},hr.padEnd=function(t,e,n){t=Ha(t);var r=(e=qa(e))?Pn(t):0;return e&&r<e?t+mi(e-r,n):t},hr.padStart=function(t,e,n){t=Ha(t);var r=(e=qa(e))?Pn(t):0;return e&&r<e?mi(e-r,n)+t:t},hr.parseInt=function(t,e,n){return n||null==e?e=0:e&&(e=+e),Yn(Ha(t).replace(Lt,""),e||0)},hr.random=function(t,e,n){if(n&&"boolean"!=typeof n&&Ki(t,e,n)&&(e=n=i),n===i&&("boolean"==typeof e?(n=e,e=i):"boolean"==typeof t&&(n=t,t=i)),t===i&&e===i?(t=0,e=1):(t=Da(t),e===i?(e=t,t=0):e=Da(e)),t>e){var r=t;t=e,e=r}if(n||t%1||e%1){var o=Gn();return Vn(t+o*(e-t+ke("1e-"+((o+"").length-1))),e)}return xo(t,e)},hr.reduce=function(t,e,n){var r=ya(t)?en:dn,o=arguments.length<3;return r(t,Ni(e,4),n,o,Fr)},hr.reduceRight=function(t,e,n){var r=ya(t)?nn:dn,o=arguments.length<3;return r(t,Ni(e,4),n,o,Dr)},hr.repeat=function(t,e,n){return e=(n?Ki(t,e,n):e===i)?1:qa(e),jo(Ha(t),e)},hr.replace=function(){var t=arguments,e=Ha(t[0]);return t.length<3?e:e.replace(t[1],t[2])},hr.result=function(t,e,n){var r=-1,o=(e=Ko(e,t)).length;for(o||(o=1,t=i);++r<o;){var u=null==t?i:t[fu(e[r])];u===i&&(r=o,u=n),t=Ea(u)?u.call(t):u}return t},hr.round=Zs,hr.runInContext=t,hr.sample=function(t){return(ya(t)?Er:Oo)(t)},hr.size=function(t){if(null==t)return 0;if(_a(t))return $a(t)?Pn(t):t.length;var e=Ui(t);return e==Z||e==nt?t.size:co(t).length},hr.snakeCase=bs,hr.some=function(t,e,n){var r=ya(t)?rn:Ao;return n&&Ki(t,e,n)&&(e=i),r(t,Ni(e,3))},hr.sortedIndex=function(t,e){return Mo(t,e)},hr.sortedIndexBy=function(t,e,n){return $o(t,e,Ni(n,2))},hr.sortedIndexOf=function(t,e){var n=null==t?0:t.length;if(n){var r=Mo(t,e);if(r<n&&ha(t[r],e))return r}return-1},hr.sortedLastIndex=function(t,e){return Mo(t,e,!0)},hr.sortedLastIndexBy=function(t,e,n){return $o(t,e,Ni(n,2),!0)},hr.sortedLastIndexOf=function(t,e){if(null!=t&&t.length){var n=Mo(t,e,!0)-1;if(ha(t[n],e))return n}return-1},hr.startCase=ws,hr.startsWith=function(t,e,n){return t=Ha(t),n=null==n?0:$r(qa(n),0,t.length),e=zo(e),t.slice(n,n+e.length)==e},hr.subtract=Xs,hr.sum=function(t){return t&&t.length?vn(t,Cs):0},hr.sumBy=function(t,e){return t&&t.length?vn(t,Ni(e,2)):0},hr.template=function(t,e,n){var r=hr.templateSettings;n&&Ki(t,e,n)&&(e=i),t=Ha(t),e=Ya({},e,r,Si);var o,u,a=Ya({},e.imports,r.imports,Si),s=os(a),c=mn(a,s),f=0,l=e.interpolate||Zt,p="__p += '",h=ne((e.escape||Zt).source+"|"+l.source+"|"+(l===Tt?Ut:Zt).source+"|"+(e.evaluate||Zt).source+"|$","g"),d="//# sourceURL="+(fe.call(e,"sourceURL")?(e.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++Oe+"]")+"\n";t.replace(h,function(e,n,r,i,a,s){return r||(r=i),p+=t.slice(f,s).replace(Xt,En),n&&(o=!0,p+="' +\n__e("+n+") +\n'"),a&&(u=!0,p+="';\n"+a+";\n__p += '"),r&&(p+="' +\n((__t = ("+r+")) == null ? '' : __t) +\n'"),f=s+e.length,e}),p+="';\n";var v=fe.call(e,"variable")&&e.variable;v||(p="with (obj) {\n"+p+"\n}\n"),p=(u?p.replace(_t,""):p).replace(bt,"$1").replace(wt,"$1;"),p="function("+(v||"obj")+") {\n"+(v?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(o?", __e = _.escape":"")+(u?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+p+"return __p\n}";var g=Os(function(){return Jt(s,d+"return "+p).apply(i,c)});if(g.source=p,ja(g))throw g;return g},hr.times=function(t,e){if((t=qa(t))<1||t>$)return[];var n=z,r=Vn(t,z);e=Ni(e),t-=z;for(var o=gn(r,e);++n<t;)e(n);return o},hr.toFinite=Da,hr.toInteger=qa,hr.toLength=Ua,hr.toLower=function(t){return Ha(t).toLowerCase()},hr.toNumber=Wa,hr.toSafeInteger=function(t){return t?$r(qa(t),-$,$):0===t?t:0},hr.toString=Ha,hr.toUpper=function(t){return Ha(t).toUpperCase()},hr.trim=function(t,e,n){if((t=Ha(t))&&(n||e===i))return t.replace($t,"");if(!t||!(e=zo(e)))return t;var r=An(t),o=An(e);return Go(r,bn(r,o),wn(r,o)+1).join("")},hr.trimEnd=function(t,e,n){if((t=Ha(t))&&(n||e===i))return t.replace(Nt,"");if(!t||!(e=zo(e)))return t;var r=An(t);return Go(r,0,wn(r,An(e))+1).join("")},hr.trimStart=function(t,e,n){if((t=Ha(t))&&(n||e===i))return t.replace(Lt,"");if(!t||!(e=zo(e)))return t;var r=An(t);return Go(r,bn(r,An(e))).join("")},hr.truncate=function(t,e){var n=R,r=T;if(Ra(e)){var o="separator"in e?e.separator:o;n="length"in e?qa(e.length):n,r="omission"in e?zo(e.omission):r}var u=(t=Ha(t)).length;if(On(t)){var a=An(t);u=a.length}if(n>=u)return t;var s=n-Pn(r);if(s<1)return r;var c=a?Go(a,0,s).join(""):t.slice(0,s);if(o===i)return c+r;if(a&&(s+=c.length-s),Aa(o)){if(t.slice(s).search(o)){var f,l=c;for(o.global||(o=ne(o.source,Ha(Wt.exec(o))+"g")),o.lastIndex=0;f=o.exec(l);)var p=f.index;c=c.slice(0,p===i?s:p)}}else if(t.indexOf(zo(o),s)!=s){var h=c.lastIndexOf(o);h>-1&&(c=c.slice(0,h))}return c+r},hr.unescape=function(t){return(t=Ha(t))&&Et.test(t)?t.replace(xt,Mn):t},hr.uniqueId=function(t){var e=++le;return Ha(t)+e},hr.upperCase=xs,hr.upperFirst=js,hr.each=Hu,hr.eachRight=Vu,hr.first=_u,$s(hr,(Ys={},Kr(hr,function(t,e){fe.call(hr.prototype,e)||(Ys[e]=t)}),Ys),{chain:!1}),hr.VERSION="4.17.19",Ke(["bind","bindKey","curry","curryRight","partial","partialRight"],function(t){hr[t].placeholder=hr}),Ke(["drop","take"],function(t,e){yr.prototype[t]=function(n){n=n===i?1:Hn(qa(n),0);var r=this.__filtered__&&!e?new yr(this):this.clone();return r.__filtered__?r.__takeCount__=Vn(n,r.__takeCount__):r.__views__.push({size:Vn(n,z),type:t+(r.__dir__<0?"Right":"")}),r},yr.prototype[t+"Right"]=function(e){return this.reverse()[t](e).reverse()}}),Ke(["filter","map","takeWhile"],function(t,e){var n=e+1,r=n==P||3==n;yr.prototype[t]=function(t){var e=this.clone();return e.__iteratees__.push({iteratee:Ni(t,3),type:n}),e.__filtered__=e.__filtered__||r,e}}),Ke(["head","last"],function(t,e){var n="take"+(e?"Right":"");yr.prototype[t]=function(){return this[n](1).value()[0]}}),Ke(["initial","tail"],function(t,e){var n="drop"+(e?"":"Right");yr.prototype[t]=function(){return this.__filtered__?new yr(this):this[n](1)}}),yr.prototype.compact=function(){return this.filter(Cs)},yr.prototype.find=function(t){return this.filter(t).head()},yr.prototype.findLast=function(t){return this.reverse().find(t)},yr.prototype.invokeMap=Eo(function(t,e){return"function"==typeof t?new yr(this):this.map(function(n){return ro(n,t,e)})}),yr.prototype.reject=function(t){return this.filter(sa(Ni(t)))},yr.prototype.slice=function(t,e){t=qa(t);var n=this;return n.__filtered__&&(t>0||e<0)?new yr(n):(t<0?n=n.takeRight(-t):t&&(n=n.drop(t)),e!==i&&(n=(e=qa(e))<0?n.dropRight(-e):n.take(e-t)),n)},yr.prototype.takeRightWhile=function(t){return this.reverse().takeWhile(t).reverse()},yr.prototype.toArray=function(){return this.take(z)},Kr(yr.prototype,function(t,e){var n=/^(?:filter|find|map|reject)|While$/.test(e),r=/^(?:head|last)$/.test(e),o=hr[r?"take"+("last"==e?"Right":""):e],u=r||/^find/.test(e);o&&(hr.prototype[e]=function(){var e=this.__wrapped__,a=r?[1]:arguments,s=e instanceof yr,c=a[0],f=s||ya(e),l=function(t){var e=o.apply(hr,tn([t],a));return r&&p?e[0]:e};f&&n&&"function"==typeof c&&1!=c.length&&(s=f=!1);var p=this.__chain__,h=!!this.__actions__.length,d=u&&!p,v=s&&!h;if(!u&&f){e=v?e:new yr(this);var g=t.apply(e,a);return g.__actions__.push({func:Du,args:[l],thisArg:i}),new gr(g,p)}return d&&v?t.apply(this,a):(g=this.thru(l),d?r?g.value()[0]:g.value():g)})}),Ke(["pop","push","shift","sort","splice","unshift"],function(t){var e=ie[t],n=/^(?:push|sort|unshift)$/.test(t)?"tap":"thru",r=/^(?:pop|shift)$/.test(t);hr.prototype[t]=function(){var t=arguments;if(r&&!this.__chain__){var o=this.value();return e.apply(ya(o)?o:[],t)}return this[n](function(n){return e.apply(ya(n)?n:[],t)})}}),Kr(yr.prototype,function(t,e){var n=hr[e];if(n){var r=n.name+"";fe.call(or,r)||(or[r]=[]),or[r].push({name:e,func:n})}}),or[di(i,m).name]=[{name:"wrapper",func:i}],yr.prototype.clone=function(){var t=new yr(this.__wrapped__);return t.__actions__=ri(this.__actions__),t.__dir__=this.__dir__,t.__filtered__=this.__filtered__,t.__iteratees__=ri(this.__iteratees__),t.__takeCount__=this.__takeCount__,t.__views__=ri(this.__views__),t},yr.prototype.reverse=function(){if(this.__filtered__){var t=new yr(this);t.__dir__=-1,t.__filtered__=!0}else(t=this.clone()).__dir__*=-1;return t},yr.prototype.value=function(){var t=this.__wrapped__.value(),e=this.__dir__,n=ya(t),r=e<0,o=n?t.length:0,i=function(t,e,n){for(var r=-1,o=n.length;++r<o;){var i=n[r],u=i.size;switch(i.type){case"drop":t+=u;break;case"dropRight":e-=u;break;case"take":e=Vn(e,t+u);break;case"takeRight":t=Hn(t,e-u)}}return{start:t,end:e}}(0,o,this.__views__),u=i.start,a=i.end,s=a-u,c=r?a:u-1,f=this.__iteratees__,l=f.length,p=0,h=Vn(s,this.__takeCount__);if(!n||!r&&o==s&&h==s)return Uo(t,this.__actions__);var d=[];t:for(;s--&&p<h;){for(var v=-1,g=t[c+=e];++v<l;){var y=f[v],m=y.iteratee,_=y.type,b=m(g);if(_==A)g=b;else if(!b){if(_==P)continue t;break t}}d[p++]=g}return d},hr.prototype.at=qu,hr.prototype.chain=function(){return Fu(this)},hr.prototype.commit=function(){return new gr(this.value(),this.__chain__)},hr.prototype.next=function(){this.__values__===i&&(this.__values__=Fa(this.value()));var t=this.__index__>=this.__values__.length;return{done:t,value:t?i:this.__values__[this.__index__++]}},hr.prototype.plant=function(t){for(var e,n=this;n instanceof vr;){var r=pu(n);r.__index__=0,r.__values__=i,e?o.__wrapped__=r:e=r;var o=r;n=n.__wrapped__}return o.__wrapped__=t,e},hr.prototype.reverse=function(){var t=this.__wrapped__;if(t instanceof yr){var e=t;return this.__actions__.length&&(e=new yr(this)),(e=e.reverse()).__actions__.push({func:Du,args:[Ru],thisArg:i}),new gr(e,this.__chain__)}return this.thru(Ru)},hr.prototype.toJSON=hr.prototype.valueOf=hr.prototype.value=function(){return Uo(this.__wrapped__,this.__actions__)},hr.prototype.first=hr.prototype.head,Ie&&(hr.prototype[Ie]=function(){return this}),hr}();Me._=$n,(o=function(){return $n}.call(e,n,e,r))===i||(r.exports=o)}).call(this)}).call(e,n(71),n(31)(t))},function(t,e,n){var r=n(17);t.exports=function(){return r.Date.now()}},function(t,e){t.exports=function(){return!1}},function(t,e,n){var r=n(8),o=n(69),i=NaN,u=/^\s+|\s+$/g,a=/^[-+]0x[0-9a-f]+$/i,s=/^0b[01]+$/i,c=/^0o[0-7]+$/i,f=parseInt;t.exports=function(t){if("number"==typeof t)return t;if(o(t))return i;if(r(t)){var e="function"==typeof t.valueOf?t.valueOf():t;t=r(e)?e+"":e}if("string"!=typeof t)return 0===t?t:+t;t=t.replace(u,"");var n=s.test(t);return n||c.test(t)?f(t.slice(2),n?2:8):a.test(t)?i:+t}},function(t,e,n){var r=n(165);t.exports=function(t){return null==t?"":r(t)}},function(t,e,n){var r=n(169)("toUpperCase");t.exports=r},function(t,e,n){var r=function(){return this}()||Function("return this")(),o=r.regeneratorRuntime&&Object.getOwnPropertyNames(r).indexOf("regeneratorRuntime")>=0,i=o&&r.regeneratorRuntime;if(r.regeneratorRuntime=void 0,t.exports=n(200),o)r.regeneratorRuntime=i;else try{delete r.regeneratorRuntime}catch(t){r.regeneratorRuntime=void 0}},function(t,e){!function(e){"use strict";var n,r=Object.prototype,o=r.hasOwnProperty,i="function"==typeof Symbol?Symbol:{},u=i.iterator||"@@iterator",a=i.asyncIterator||"@@asyncIterator",s=i.toStringTag||"@@toStringTag",c="object"==typeof t,f=e.regeneratorRuntime;if(f)c&&(t.exports=f);else{(f=e.regeneratorRuntime=c?t.exports:{}).wrap=b;var l="suspendedStart",p="suspendedYield",h="executing",d="completed",v={},g={};g[u]=function(){return this};var y=Object.getPrototypeOf,m=y&&y(y(P([])));m&&m!==r&&o.call(m,u)&&(g=m);var _=E.prototype=x.prototype=Object.create(g);j.prototype=_.constructor=E,E.constructor=j,E[s]=j.displayName="GeneratorFunction",f.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===j||"GeneratorFunction"===(e.displayName||e.name))},f.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,E):(t.__proto__=E,s in t||(t[s]="GeneratorFunction")),t.prototype=Object.create(_),t},f.awrap=function(t){return{__await:t}},O(S.prototype),S.prototype[a]=function(){return this},f.AsyncIterator=S,f.async=function(t,e,n,r){var o=new S(b(t,e,n,r));return f.isGeneratorFunction(e)?o:o.next().then(function(t){return t.done?t.value:o.next()})},O(_),_[s]="Generator",_[u]=function(){return this},_.toString=function(){return"[object Generator]"},f.keys=function(t){var e=[];for(var n in t)e.push(n);return e.reverse(),function n(){for(;e.length;){var r=e.pop();if(r in t)return n.value=r,n.done=!1,n}return n.done=!0,n}},f.values=P,C.prototype={constructor:C,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=n,this.done=!1,this.delegate=null,this.method="next",this.arg=n,this.tryEntries.forEach(k),!t)for(var e in this)"t"===e.charAt(0)&&o.call(this,e)&&!isNaN(+e.slice(1))&&(this[e]=n)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var e=this;function r(r,o){return a.type="throw",a.arg=t,e.next=r,o&&(e.method="next",e.arg=n),!!o}for(var i=this.tryEntries.length-1;i>=0;--i){var u=this.tryEntries[i],a=u.completion;if("root"===u.tryLoc)return r("end");if(u.tryLoc<=this.prev){var s=o.call(u,"catchLoc"),c=o.call(u,"finallyLoc");if(s&&c){if(this.prev<u.catchLoc)return r(u.catchLoc,!0);if(this.prev<u.finallyLoc)return r(u.finallyLoc)}else if(s){if(this.prev<u.catchLoc)return r(u.catchLoc,!0)}else{if(!c)throw new Error("try statement without catch or finally");if(this.prev<u.finallyLoc)return r(u.finallyLoc)}}}},abrupt:function(t,e){for(var n=this.tryEntries.length-1;n>=0;--n){var r=this.tryEntries[n];if(r.tryLoc<=this.prev&&o.call(r,"finallyLoc")&&this.prev<r.finallyLoc){var i=r;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var u=i?i.completion:{};return u.type=t,u.arg=e,i?(this.method="next",this.next=i.finallyLoc,v):this.complete(u)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),v},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),k(n),v}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===t){var r=n.completion;if("throw"===r.type){var o=r.arg;k(n)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,r){return this.delegate={iterator:P(t),resultName:e,nextLoc:r},"next"===this.method&&(this.arg=n),v}}}function b(t,e,n,r){var o=e&&e.prototype instanceof x?e:x,i=Object.create(o.prototype),u=new C(r||[]);return i._invoke=function(t,e,n){var r=l;return function(o,i){if(r===h)throw new Error("Generator is already running");if(r===d){if("throw"===o)throw i;return A()}for(n.method=o,n.arg=i;;){var u=n.delegate;if(u){var a=R(u,n);if(a){if(a===v)continue;return a}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(r===l)throw r=d,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r=h;var s=w(t,e,n);if("normal"===s.type){if(r=n.done?d:p,s.arg===v)continue;return{value:s.arg,done:n.done}}"throw"===s.type&&(r=d,n.method="throw",n.arg=s.arg)}}}(t,n,u),i}function w(t,e,n){try{return{type:"normal",arg:t.call(e,n)}}catch(t){return{type:"throw",arg:t}}}function x(){}function j(){}function E(){}function O(t){["next","throw","return"].forEach(function(e){t[e]=function(t){return this._invoke(e,t)}})}function S(t){var e;this._invoke=function(n,r){function i(){return new Promise(function(e,i){!function e(n,r,i,u){var a=w(t[n],t,r);if("throw"!==a.type){var s=a.arg,c=s.value;return c&&"object"==typeof c&&o.call(c,"__await")?Promise.resolve(c.__await).then(function(t){e("next",t,i,u)},function(t){e("throw",t,i,u)}):Promise.resolve(c).then(function(t){s.value=t,i(s)},u)}u(a.arg)}(n,r,e,i)})}return e=e?e.then(i,i):i()}}function R(t,e){var r=t.iterator[e.method];if(r===n){if(e.delegate=null,"throw"===e.method){if(t.iterator.return&&(e.method="return",e.arg=n,R(t,e),"throw"===e.method))return v;e.method="throw",e.arg=new TypeError("The iterator does not provide a 'throw' method")}return v}var o=w(r,t.iterator,e.arg);if("throw"===o.type)return e.method="throw",e.arg=o.arg,e.delegate=null,v;var i=o.arg;return i?i.done?(e[t.resultName]=i.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=n),e.delegate=null,v):i:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,v)}function T(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function k(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function C(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(T,this),this.reset(!0)}function P(t){if(t){var e=t[u];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var r=-1,i=function e(){for(;++r<t.length;)if(o.call(t,r))return e.value=t[r],e.done=!1,e;return e.value=n,e.done=!0,e};return i.next=i}}return{next:A}}function A(){return{value:n,done:!0}}}(function(){return this}()||Function("return this")())}])},t.exports=r()},function(t,e){t.exports={render:function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{staticClass:"border-b border-40"},[n("div",{staticClass:"px-8 py-4 flex items-center justify-between"},[t.isCreate?n("heading",[t._v(t._s(t.locale.label))]):t.field.value?n("heading",[t._v(t._s(t.field.locales[t.field.value.locale_id].label))]):t._e()],1)])},staticRenderFns:[]}},function(t,e){}]);
module.exports = { purge: [], darkMode: false, // or 'media' or 'class' theme: { extend: { colors: { "title-red": "#bd0202", "title-black": "#222222", "title-hover": "#9d242c", }, fontFamily:{ Nunito:["'Nunito', sans-serif"], }, }, container: { center: true, padding:"1rem", screens: { lg: "1240px", xl: "1240px", "2xl": "1240px", }, }, }, variants: { extend: {}, }, plugins: [], }
/* * Copyright 2014, Gregg Tavares. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Gregg Tavares. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ "use strict"; requirejs( [ 'hft/hft-system', 'hft/misc/strings', ], function( HFTSystem, Strings) { var $ = function(id) { return document.getElementById(id); }; var gamemenu = $("gamemenu"); var nogames = $("nogames"); var template = $("item-template").text; var oldHtml = ""; var hftSystem = new HFTSystem(); hftSystem.on('runningGames', function(obj) { console.log(obj); // If there's only one game just go to it. if (obj.length === 1 && obj[0].controllerUrl) { window.location.href = obj[0].controllerUrl; return; } var items = []; for (var ii = 0; ii < obj.length; ++ii) { var game = obj[ii]; var runtimeInfo = game.runtimeInfo; if (runtimeInfo) { var hftInfo = runtimeInfo.info.happyFunTimes; // Not sure how I should figure out the name and screenshot. var dev = (runtimeInfo.originalGameId !== hftInfo.gameId) ? "(*)" : ""; game.name = dev + (hftInfo.name || runtimeInfo.originalGameId); game.screenshotUrl = game.screenshotUrl; items.push(Strings.replaceParams(template, game)); } } var html = items.join(""); if (html !== oldHtml) { oldHtml = html; gamemenu.innerHTML = html; } nogames.style.display = items.length ? "none" : "block"; }); });
_N_E = (window["webpackJsonp_N_E"] = window["webpackJsonp_N_E"] || []).push([["pages/_error"],{ /***/ "./node_modules/next/dist/build/polyfills/object-assign.js": /*!*****************************************************************!*\ !*** ./node_modules/next/dist/build/polyfills/object-assign.js ***! \*****************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var assign=Object.assign.bind(Object);module.exports=assign;module.exports.default=module.exports; //# sourceMappingURL=object-assign.js.map /***/ }), /***/ "./node_modules/next/dist/build/webpack/loaders/next-client-pages-loader.js?page=%2F_error&absolutePagePath=next%2Fdist%2Fpages%2F_error!./": /*!***********************************************************************************************************************************************!*\ !*** ./node_modules/next/dist/build/webpack/loaders/next-client-pages-loader.js?page=%2F_error&absolutePagePath=next%2Fdist%2Fpages%2F_error ***! \***********************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { (window.__NEXT_P = window.__NEXT_P || []).push([ "/_error", function () { return __webpack_require__(/*! next/dist/pages/_error */ "./node_modules/next/dist/pages/_error.js"); } ]); /***/ }), /***/ "./node_modules/next/dist/next-server/lib/amp-context.js": /*!***************************************************************!*\ !*** ./node_modules/next/dist/next-server/lib/amp-context.js ***! \***************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(module) { exports.__esModule = true; exports.AmpStateContext = void 0; var _react = _interopRequireDefault(__webpack_require__(/*! react */ "./node_modules/react/index.js")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var AmpStateContext = /*#__PURE__*/_react["default"].createContext({}); exports.AmpStateContext = AmpStateContext; if (true) { AmpStateContext.displayName = 'AmpStateContext'; } ; var _a, _b; // Legacy CSS implementations will `eval` browser code in a Node.js context // to extract CSS. For backwards compatibility, we need to check we're in a // browser context before continuing. if (typeof self !== 'undefined' && // AMP / No-JS mode does not inject these helpers: '$RefreshHelpers$' in self) { var currentExports = module.__proto__.exports; var prevExports = (_b = (_a = module.hot.data) === null || _a === void 0 ? void 0 : _a.prevExports) !== null && _b !== void 0 ? _b : null; // This cannot happen in MainTemplate because the exports mismatch between // templating and execution. self.$RefreshHelpers$.registerExportsForReactRefresh(currentExports, module.i); // A module can be accepted automatically based on its exports, e.g. when // it is a Refresh Boundary. if (self.$RefreshHelpers$.isReactRefreshBoundary(currentExports)) { // Save the previous exports on update so we can compare the boundary // signatures. module.hot.dispose(function (data) { data.prevExports = currentExports; }); // Unconditionally accept an update to this module, we'll check if it's // still a Refresh Boundary later. module.hot.accept(); // This field is set when the previous version of this module was a // Refresh Boundary, letting us know we need to check for invalidation or // enqueue an update. if (prevExports !== null) { // A boundary can become ineligible if its exports are incompatible // with the previous exports. // // For example, if you add/remove/change exports, we'll want to // re-execute the importing modules, and force those components to // re-render. Similarly, if you convert a class component to a // function, we want to invalidate the boundary. if (self.$RefreshHelpers$.shouldInvalidateReactRefreshBoundary(prevExports, currentExports)) { module.hot.invalidate(); } else { self.$RefreshHelpers$.scheduleUpdate(); } } } else { // Since we just executed the code for the module, it's possible that the // new exports made it ineligible for being a boundary. // We only care about the case when we were _previously_ a boundary, // because we already accepted this update (accidental side effect). var isNoLongerABoundary = prevExports !== null; if (isNoLongerABoundary) { module.hot.invalidate(); } } } /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../node_modules/webpack/buildin/module.js */ "./node_modules/next/node_modules/webpack/buildin/module.js")(module))) /***/ }), /***/ "./node_modules/next/dist/next-server/lib/amp.js": /*!*******************************************************!*\ !*** ./node_modules/next/dist/next-server/lib/amp.js ***! \*******************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(module) { var _s = $RefreshSig$(); exports.__esModule = true; exports.isInAmpMode = isInAmpMode; exports.useAmp = useAmp; var _react = _interopRequireDefault(__webpack_require__(/*! react */ "./node_modules/react/index.js")); var _ampContext = __webpack_require__(/*! ./amp-context */ "./node_modules/next/dist/next-server/lib/amp-context.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function isInAmpMode() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, _ref$ampFirst = _ref.ampFirst, ampFirst = _ref$ampFirst === void 0 ? false : _ref$ampFirst, _ref$hybrid = _ref.hybrid, hybrid = _ref$hybrid === void 0 ? false : _ref$hybrid, _ref$hasQuery = _ref.hasQuery, hasQuery = _ref$hasQuery === void 0 ? false : _ref$hasQuery; return ampFirst || hybrid && hasQuery; } function useAmp() { _s(); // Don't assign the context value to a variable to save bytes return isInAmpMode(_react["default"].useContext(_ampContext.AmpStateContext)); } _s(useAmp, "gDsCjeeItUuvgOWf1v4qoK9RF6k="); ; var _a, _b; // Legacy CSS implementations will `eval` browser code in a Node.js context // to extract CSS. For backwards compatibility, we need to check we're in a // browser context before continuing. if (typeof self !== 'undefined' && // AMP / No-JS mode does not inject these helpers: '$RefreshHelpers$' in self) { var currentExports = module.__proto__.exports; var prevExports = (_b = (_a = module.hot.data) === null || _a === void 0 ? void 0 : _a.prevExports) !== null && _b !== void 0 ? _b : null; // This cannot happen in MainTemplate because the exports mismatch between // templating and execution. self.$RefreshHelpers$.registerExportsForReactRefresh(currentExports, module.i); // A module can be accepted automatically based on its exports, e.g. when // it is a Refresh Boundary. if (self.$RefreshHelpers$.isReactRefreshBoundary(currentExports)) { // Save the previous exports on update so we can compare the boundary // signatures. module.hot.dispose(function (data) { data.prevExports = currentExports; }); // Unconditionally accept an update to this module, we'll check if it's // still a Refresh Boundary later. module.hot.accept(); // This field is set when the previous version of this module was a // Refresh Boundary, letting us know we need to check for invalidation or // enqueue an update. if (prevExports !== null) { // A boundary can become ineligible if its exports are incompatible // with the previous exports. // // For example, if you add/remove/change exports, we'll want to // re-execute the importing modules, and force those components to // re-render. Similarly, if you convert a class component to a // function, we want to invalidate the boundary. if (self.$RefreshHelpers$.shouldInvalidateReactRefreshBoundary(prevExports, currentExports)) { module.hot.invalidate(); } else { self.$RefreshHelpers$.scheduleUpdate(); } } } else { // Since we just executed the code for the module, it's possible that the // new exports made it ineligible for being a boundary. // We only care about the case when we were _previously_ a boundary, // because we already accepted this update (accidental side effect). var isNoLongerABoundary = prevExports !== null; if (isNoLongerABoundary) { module.hot.invalidate(); } } } /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../node_modules/webpack/buildin/module.js */ "./node_modules/next/node_modules/webpack/buildin/module.js")(module))) /***/ }), /***/ "./node_modules/next/dist/next-server/lib/head-manager-context.js": /*!************************************************************************!*\ !*** ./node_modules/next/dist/next-server/lib/head-manager-context.js ***! \************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(module) { exports.__esModule = true; exports.HeadManagerContext = void 0; var _react = _interopRequireDefault(__webpack_require__(/*! react */ "./node_modules/react/index.js")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var HeadManagerContext = /*#__PURE__*/_react["default"].createContext({}); exports.HeadManagerContext = HeadManagerContext; if (true) { HeadManagerContext.displayName = 'HeadManagerContext'; } ; var _a, _b; // Legacy CSS implementations will `eval` browser code in a Node.js context // to extract CSS. For backwards compatibility, we need to check we're in a // browser context before continuing. if (typeof self !== 'undefined' && // AMP / No-JS mode does not inject these helpers: '$RefreshHelpers$' in self) { var currentExports = module.__proto__.exports; var prevExports = (_b = (_a = module.hot.data) === null || _a === void 0 ? void 0 : _a.prevExports) !== null && _b !== void 0 ? _b : null; // This cannot happen in MainTemplate because the exports mismatch between // templating and execution. self.$RefreshHelpers$.registerExportsForReactRefresh(currentExports, module.i); // A module can be accepted automatically based on its exports, e.g. when // it is a Refresh Boundary. if (self.$RefreshHelpers$.isReactRefreshBoundary(currentExports)) { // Save the previous exports on update so we can compare the boundary // signatures. module.hot.dispose(function (data) { data.prevExports = currentExports; }); // Unconditionally accept an update to this module, we'll check if it's // still a Refresh Boundary later. module.hot.accept(); // This field is set when the previous version of this module was a // Refresh Boundary, letting us know we need to check for invalidation or // enqueue an update. if (prevExports !== null) { // A boundary can become ineligible if its exports are incompatible // with the previous exports. // // For example, if you add/remove/change exports, we'll want to // re-execute the importing modules, and force those components to // re-render. Similarly, if you convert a class component to a // function, we want to invalidate the boundary. if (self.$RefreshHelpers$.shouldInvalidateReactRefreshBoundary(prevExports, currentExports)) { module.hot.invalidate(); } else { self.$RefreshHelpers$.scheduleUpdate(); } } } else { // Since we just executed the code for the module, it's possible that the // new exports made it ineligible for being a boundary. // We only care about the case when we were _previously_ a boundary, // because we already accepted this update (accidental side effect). var isNoLongerABoundary = prevExports !== null; if (isNoLongerABoundary) { module.hot.invalidate(); } } } /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../node_modules/webpack/buildin/module.js */ "./node_modules/next/node_modules/webpack/buildin/module.js")(module))) /***/ }), /***/ "./node_modules/next/dist/next-server/lib/head.js": /*!********************************************************!*\ !*** ./node_modules/next/dist/next-server/lib/head.js ***! \********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(module) { var _defineProperty = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/next/node_modules/@babel/runtime/helpers/defineProperty.js"); function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } exports.__esModule = true; exports.defaultHead = defaultHead; exports["default"] = void 0; var _react = _interopRequireWildcard(__webpack_require__(/*! react */ "./node_modules/react/index.js")); var _sideEffect = _interopRequireDefault(__webpack_require__(/*! ./side-effect */ "./node_modules/next/dist/next-server/lib/side-effect.js")); var _ampContext = __webpack_require__(/*! ./amp-context */ "./node_modules/next/dist/next-server/lib/amp-context.js"); var _headManagerContext = __webpack_require__(/*! ./head-manager-context */ "./node_modules/next/dist/next-server/lib/head-manager-context.js"); var _amp = __webpack_require__(/*! ./amp */ "./node_modules/next/dist/next-server/lib/amp.js"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function defaultHead() { var inAmpMode = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; var head = [/*#__PURE__*/_react["default"].createElement("meta", { charSet: "utf-8" })]; if (!inAmpMode) { head.push( /*#__PURE__*/_react["default"].createElement("meta", { name: "viewport", content: "width=device-width" })); } return head; } function onlyReactElement(list, child) { // React children can be "string" or "number" in this case we ignore them for backwards compat if (typeof child === 'string' || typeof child === 'number') { return list; } // Adds support for React.Fragment if (child.type === _react["default"].Fragment) { return list.concat(_react["default"].Children.toArray(child.props.children).reduce(function (fragmentList, fragmentChild) { if (typeof fragmentChild === 'string' || typeof fragmentChild === 'number') { return fragmentList; } return fragmentList.concat(fragmentChild); }, [])); } return list.concat(child); } var METATYPES = ['name', 'httpEquiv', 'charSet', 'itemProp']; /* returns a function for filtering head child elements which shouldn't be duplicated, like <title/> Also adds support for deduplicated `key` properties */ function unique() { var keys = new Set(); var tags = new Set(); var metaTypes = new Set(); var metaCategories = {}; return function (h) { var isUnique = true; if (h.key && typeof h.key !== 'number' && h.key.indexOf('$') > 0) { var key = h.key.slice(h.key.indexOf('$') + 1); if (keys.has(key)) { isUnique = false; } else { keys.add(key); } } // eslint-disable-next-line default-case switch (h.type) { case 'title': case 'base': if (tags.has(h.type)) { isUnique = false; } else { tags.add(h.type); } break; case 'meta': for (var i = 0, len = METATYPES.length; i < len; i++) { var metatype = METATYPES[i]; if (!h.props.hasOwnProperty(metatype)) continue; if (metatype === 'charSet') { if (metaTypes.has(metatype)) { isUnique = false; } else { metaTypes.add(metatype); } } else { var category = h.props[metatype]; var categories = metaCategories[metatype] || new Set(); if (categories.has(category)) { isUnique = false; } else { categories.add(category); metaCategories[metatype] = categories; } } } break; } return isUnique; }; } /** * * @param headElements List of multiple <Head> instances */ function reduceComponents(headElements, props) { return headElements.reduce(function (list, headElement) { var headElementChildren = _react["default"].Children.toArray(headElement.props.children); return list.concat(headElementChildren); }, []).reduce(onlyReactElement, []).reverse().concat(defaultHead(props.inAmpMode)).filter(unique()).reverse().map(function (c, i) { var key = c.key || i; if (false) { var newProps; } return /*#__PURE__*/_react["default"].cloneElement(c, { key: key }); }); } /** * This component injects elements to `<head>` of your page. * To avoid duplicated `tags` in `<head>` you can use the `key` property, which will make sure every tag is only rendered once. */ function Head(_ref) { var children = _ref.children; var ampState = (0, _react.useContext)(_ampContext.AmpStateContext); var headManager = (0, _react.useContext)(_headManagerContext.HeadManagerContext); return /*#__PURE__*/_react["default"].createElement(_sideEffect["default"], { reduceComponentsToState: reduceComponents, headManager: headManager, inAmpMode: (0, _amp.isInAmpMode)(ampState) }, children); } // TODO: Remove in the next major release _c = Head; Head.rewind = function () {}; var _default = Head; exports["default"] = _default; var _c; $RefreshReg$(_c, "Head"); ; var _a, _b; // Legacy CSS implementations will `eval` browser code in a Node.js context // to extract CSS. For backwards compatibility, we need to check we're in a // browser context before continuing. if (typeof self !== 'undefined' && // AMP / No-JS mode does not inject these helpers: '$RefreshHelpers$' in self) { var currentExports = module.__proto__.exports; var prevExports = (_b = (_a = module.hot.data) === null || _a === void 0 ? void 0 : _a.prevExports) !== null && _b !== void 0 ? _b : null; // This cannot happen in MainTemplate because the exports mismatch between // templating and execution. self.$RefreshHelpers$.registerExportsForReactRefresh(currentExports, module.i); // A module can be accepted automatically based on its exports, e.g. when // it is a Refresh Boundary. if (self.$RefreshHelpers$.isReactRefreshBoundary(currentExports)) { // Save the previous exports on update so we can compare the boundary // signatures. module.hot.dispose(function (data) { data.prevExports = currentExports; }); // Unconditionally accept an update to this module, we'll check if it's // still a Refresh Boundary later. module.hot.accept(); // This field is set when the previous version of this module was a // Refresh Boundary, letting us know we need to check for invalidation or // enqueue an update. if (prevExports !== null) { // A boundary can become ineligible if its exports are incompatible // with the previous exports. // // For example, if you add/remove/change exports, we'll want to // re-execute the importing modules, and force those components to // re-render. Similarly, if you convert a class component to a // function, we want to invalidate the boundary. if (self.$RefreshHelpers$.shouldInvalidateReactRefreshBoundary(prevExports, currentExports)) { module.hot.invalidate(); } else { self.$RefreshHelpers$.scheduleUpdate(); } } } else { // Since we just executed the code for the module, it's possible that the // new exports made it ineligible for being a boundary. // We only care about the case when we were _previously_ a boundary, // because we already accepted this update (accidental side effect). var isNoLongerABoundary = prevExports !== null; if (isNoLongerABoundary) { module.hot.invalidate(); } } } /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../node_modules/webpack/buildin/module.js */ "./node_modules/next/node_modules/webpack/buildin/module.js")(module))) /***/ }), /***/ "./node_modules/next/dist/next-server/lib/side-effect.js": /*!***************************************************************!*\ !*** ./node_modules/next/dist/next-server/lib/side-effect.js ***! \***************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(module) { var _toConsumableArray = __webpack_require__(/*! @babel/runtime/helpers/toConsumableArray */ "./node_modules/next/node_modules/@babel/runtime/helpers/toConsumableArray.js"); var _classCallCheck = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/next/node_modules/@babel/runtime/helpers/classCallCheck.js"); var _createClass = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/next/node_modules/@babel/runtime/helpers/createClass.js"); var _assertThisInitialized = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "./node_modules/next/node_modules/@babel/runtime/helpers/assertThisInitialized.js"); var _inherits = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/next/node_modules/@babel/runtime/helpers/inherits.js"); var _possibleConstructorReturn = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/next/node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"); var _getPrototypeOf = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/next/node_modules/@babel/runtime/helpers/getPrototypeOf.js"); function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } exports.__esModule = true; exports["default"] = void 0; var _react = __webpack_require__(/*! react */ "./node_modules/react/index.js"); var isServer = false; var _default = /*#__PURE__*/function (_react$Component) { _inherits(_default, _react$Component); var _super = _createSuper(_default); function _default(props) { var _this; _classCallCheck(this, _default); _this = _super.call(this, props); _this._hasHeadManager = void 0; _this.emitChange = function () { if (_this._hasHeadManager) { _this.props.headManager.updateHead(_this.props.reduceComponentsToState(_toConsumableArray(_this.props.headManager.mountedInstances), _this.props)); } }; _this._hasHeadManager = _this.props.headManager && _this.props.headManager.mountedInstances; if (isServer && _this._hasHeadManager) { _this.props.headManager.mountedInstances.add(_assertThisInitialized(_this)); _this.emitChange(); } return _this; } _createClass(_default, [{ key: "componentDidMount", value: function componentDidMount() { if (this._hasHeadManager) { this.props.headManager.mountedInstances.add(this); } this.emitChange(); } }, { key: "componentDidUpdate", value: function componentDidUpdate() { this.emitChange(); } }, { key: "componentWillUnmount", value: function componentWillUnmount() { if (this._hasHeadManager) { this.props.headManager.mountedInstances["delete"](this); } this.emitChange(); } }, { key: "render", value: function render() { return null; } }]); return _default; }(_react.Component); exports["default"] = _default; ; var _a, _b; // Legacy CSS implementations will `eval` browser code in a Node.js context // to extract CSS. For backwards compatibility, we need to check we're in a // browser context before continuing. if (typeof self !== 'undefined' && // AMP / No-JS mode does not inject these helpers: '$RefreshHelpers$' in self) { var currentExports = module.__proto__.exports; var prevExports = (_b = (_a = module.hot.data) === null || _a === void 0 ? void 0 : _a.prevExports) !== null && _b !== void 0 ? _b : null; // This cannot happen in MainTemplate because the exports mismatch between // templating and execution. self.$RefreshHelpers$.registerExportsForReactRefresh(currentExports, module.i); // A module can be accepted automatically based on its exports, e.g. when // it is a Refresh Boundary. if (self.$RefreshHelpers$.isReactRefreshBoundary(currentExports)) { // Save the previous exports on update so we can compare the boundary // signatures. module.hot.dispose(function (data) { data.prevExports = currentExports; }); // Unconditionally accept an update to this module, we'll check if it's // still a Refresh Boundary later. module.hot.accept(); // This field is set when the previous version of this module was a // Refresh Boundary, letting us know we need to check for invalidation or // enqueue an update. if (prevExports !== null) { // A boundary can become ineligible if its exports are incompatible // with the previous exports. // // For example, if you add/remove/change exports, we'll want to // re-execute the importing modules, and force those components to // re-render. Similarly, if you convert a class component to a // function, we want to invalidate the boundary. if (self.$RefreshHelpers$.shouldInvalidateReactRefreshBoundary(prevExports, currentExports)) { module.hot.invalidate(); } else { self.$RefreshHelpers$.scheduleUpdate(); } } } else { // Since we just executed the code for the module, it's possible that the // new exports made it ineligible for being a boundary. // We only care about the case when we were _previously_ a boundary, // because we already accepted this update (accidental side effect). var isNoLongerABoundary = prevExports !== null; if (isNoLongerABoundary) { module.hot.invalidate(); } } } /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../node_modules/webpack/buildin/module.js */ "./node_modules/next/node_modules/webpack/buildin/module.js")(module))) /***/ }), /***/ "./node_modules/next/dist/pages/_error.js": /*!************************************************!*\ !*** ./node_modules/next/dist/pages/_error.js ***! \************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(module) { var _classCallCheck = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/next/node_modules/@babel/runtime/helpers/classCallCheck.js"); var _createClass = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/next/node_modules/@babel/runtime/helpers/createClass.js"); var _inherits = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/next/node_modules/@babel/runtime/helpers/inherits.js"); var _possibleConstructorReturn = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/next/node_modules/@babel/runtime/helpers/possibleConstructorReturn.js"); var _getPrototypeOf = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/next/node_modules/@babel/runtime/helpers/getPrototypeOf.js"); function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/next/node_modules/@babel/runtime/helpers/interopRequireDefault.js"); exports.__esModule = true; exports["default"] = void 0; var _react = _interopRequireDefault(__webpack_require__(/*! react */ "./node_modules/react/index.js")); var _head = _interopRequireDefault(__webpack_require__(/*! ../next-server/lib/head */ "./node_modules/next/dist/next-server/lib/head.js")); var statusCodes = { 400: 'Bad Request', 404: 'This page could not be found', 405: 'Method Not Allowed', 500: 'Internal Server Error' }; function _getInitialProps(_ref) { var res = _ref.res, err = _ref.err; var statusCode = res && res.statusCode ? res.statusCode : err ? err.statusCode : 404; return { statusCode: statusCode }; } /** * `Error` component used for handling errors. */ var Error = /*#__PURE__*/function (_react$default$Compon) { _inherits(Error, _react$default$Compon); var _super = _createSuper(Error); function Error() { _classCallCheck(this, Error); return _super.apply(this, arguments); } _createClass(Error, [{ key: "render", value: function render() { var statusCode = this.props.statusCode; var title = this.props.title || statusCodes[statusCode] || 'An unexpected error has occurred'; return /*#__PURE__*/_react["default"].createElement("div", { style: styles.error }, /*#__PURE__*/_react["default"].createElement(_head["default"], null, /*#__PURE__*/_react["default"].createElement("title", null, statusCode, ": ", title)), /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement("style", { dangerouslySetInnerHTML: { __html: 'body { margin: 0 }' } }), statusCode ? /*#__PURE__*/_react["default"].createElement("h1", { style: styles.h1 }, statusCode) : null, /*#__PURE__*/_react["default"].createElement("div", { style: styles.desc }, /*#__PURE__*/_react["default"].createElement("h2", { style: styles.h2 }, title, ".")))); } }]); return Error; }(_react["default"].Component); exports["default"] = Error; Error.displayName = 'ErrorPage'; Error.getInitialProps = _getInitialProps; Error.origGetInitialProps = _getInitialProps; var styles = { error: { color: '#000', background: '#fff', fontFamily: '-apple-system, BlinkMacSystemFont, Roboto, "Segoe UI", "Fira Sans", Avenir, "Helvetica Neue", "Lucida Grande", sans-serif', height: '100vh', textAlign: 'center', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }, desc: { display: 'inline-block', textAlign: 'left', lineHeight: '49px', height: '49px', verticalAlign: 'middle' }, h1: { display: 'inline-block', borderRight: '1px solid rgba(0, 0, 0,.3)', margin: 0, marginRight: '20px', padding: '10px 23px 10px 0', fontSize: '24px', fontWeight: 500, verticalAlign: 'top' }, h2: { fontSize: '14px', fontWeight: 'normal', lineHeight: 'inherit', margin: 0, padding: 0 } }; ; var _a, _b; // Legacy CSS implementations will `eval` browser code in a Node.js context // to extract CSS. For backwards compatibility, we need to check we're in a // browser context before continuing. if (typeof self !== 'undefined' && // AMP / No-JS mode does not inject these helpers: '$RefreshHelpers$' in self) { var currentExports = module.__proto__.exports; var prevExports = (_b = (_a = module.hot.data) === null || _a === void 0 ? void 0 : _a.prevExports) !== null && _b !== void 0 ? _b : null; // This cannot happen in MainTemplate because the exports mismatch between // templating and execution. self.$RefreshHelpers$.registerExportsForReactRefresh(currentExports, module.i); // A module can be accepted automatically based on its exports, e.g. when // it is a Refresh Boundary. if (self.$RefreshHelpers$.isReactRefreshBoundary(currentExports)) { // Save the previous exports on update so we can compare the boundary // signatures. module.hot.dispose(function (data) { data.prevExports = currentExports; }); // Unconditionally accept an update to this module, we'll check if it's // still a Refresh Boundary later. module.hot.accept(); // This field is set when the previous version of this module was a // Refresh Boundary, letting us know we need to check for invalidation or // enqueue an update. if (prevExports !== null) { // A boundary can become ineligible if its exports are incompatible // with the previous exports. // // For example, if you add/remove/change exports, we'll want to // re-execute the importing modules, and force those components to // re-render. Similarly, if you convert a class component to a // function, we want to invalidate the boundary. if (self.$RefreshHelpers$.shouldInvalidateReactRefreshBoundary(prevExports, currentExports)) { module.hot.invalidate(); } else { self.$RefreshHelpers$.scheduleUpdate(); } } } else { // Since we just executed the code for the module, it's possible that the // new exports made it ineligible for being a boundary. // We only care about the case when we were _previously_ a boundary, // because we already accepted this update (accidental side effect). var isNoLongerABoundary = prevExports !== null; if (isNoLongerABoundary) { module.hot.invalidate(); } } } /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../node_modules/webpack/buildin/module.js */ "./node_modules/next/node_modules/webpack/buildin/module.js")(module))) /***/ }), /***/ "./node_modules/next/node_modules/@babel/runtime/helpers/arrayLikeToArray.js": /*!***********************************************************************************!*\ !*** ./node_modules/next/node_modules/@babel/runtime/helpers/arrayLikeToArray.js ***! \***********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } module.exports = _arrayLikeToArray; /***/ }), /***/ "./node_modules/next/node_modules/@babel/runtime/helpers/arrayWithoutHoles.js": /*!************************************************************************************!*\ !*** ./node_modules/next/node_modules/@babel/runtime/helpers/arrayWithoutHoles.js ***! \************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var arrayLikeToArray = __webpack_require__(/*! ./arrayLikeToArray */ "./node_modules/next/node_modules/@babel/runtime/helpers/arrayLikeToArray.js"); function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return arrayLikeToArray(arr); } module.exports = _arrayWithoutHoles; /***/ }), /***/ "./node_modules/next/node_modules/@babel/runtime/helpers/assertThisInitialized.js": /*!****************************************************************************************!*\ !*** ./node_modules/next/node_modules/@babel/runtime/helpers/assertThisInitialized.js ***! \****************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } module.exports = _assertThisInitialized; /***/ }), /***/ "./node_modules/next/node_modules/@babel/runtime/helpers/classCallCheck.js": /*!*********************************************************************************!*\ !*** ./node_modules/next/node_modules/@babel/runtime/helpers/classCallCheck.js ***! \*********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } module.exports = _classCallCheck; /***/ }), /***/ "./node_modules/next/node_modules/@babel/runtime/helpers/createClass.js": /*!******************************************************************************!*\ !*** ./node_modules/next/node_modules/@babel/runtime/helpers/createClass.js ***! \******************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } module.exports = _createClass; /***/ }), /***/ "./node_modules/next/node_modules/@babel/runtime/helpers/defineProperty.js": /*!*********************************************************************************!*\ !*** ./node_modules/next/node_modules/@babel/runtime/helpers/defineProperty.js ***! \*********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } module.exports = _defineProperty; /***/ }), /***/ "./node_modules/next/node_modules/@babel/runtime/helpers/getPrototypeOf.js": /*!*********************************************************************************!*\ !*** ./node_modules/next/node_modules/@babel/runtime/helpers/getPrototypeOf.js ***! \*********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { function _getPrototypeOf(o) { module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } module.exports = _getPrototypeOf; /***/ }), /***/ "./node_modules/next/node_modules/@babel/runtime/helpers/inherits.js": /*!***************************************************************************!*\ !*** ./node_modules/next/node_modules/@babel/runtime/helpers/inherits.js ***! \***************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var setPrototypeOf = __webpack_require__(/*! ./setPrototypeOf */ "./node_modules/next/node_modules/@babel/runtime/helpers/setPrototypeOf.js"); function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) setPrototypeOf(subClass, superClass); } module.exports = _inherits; /***/ }), /***/ "./node_modules/next/node_modules/@babel/runtime/helpers/interopRequireDefault.js": /*!****************************************************************************************!*\ !*** ./node_modules/next/node_modules/@babel/runtime/helpers/interopRequireDefault.js ***! \****************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } module.exports = _interopRequireDefault; /***/ }), /***/ "./node_modules/next/node_modules/@babel/runtime/helpers/iterableToArray.js": /*!**********************************************************************************!*\ !*** ./node_modules/next/node_modules/@babel/runtime/helpers/iterableToArray.js ***! \**********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } module.exports = _iterableToArray; /***/ }), /***/ "./node_modules/next/node_modules/@babel/runtime/helpers/nonIterableSpread.js": /*!************************************************************************************!*\ !*** ./node_modules/next/node_modules/@babel/runtime/helpers/nonIterableSpread.js ***! \************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } module.exports = _nonIterableSpread; /***/ }), /***/ "./node_modules/next/node_modules/@babel/runtime/helpers/possibleConstructorReturn.js": /*!********************************************************************************************!*\ !*** ./node_modules/next/node_modules/@babel/runtime/helpers/possibleConstructorReturn.js ***! \********************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var _typeof = __webpack_require__(/*! ../helpers/typeof */ "./node_modules/next/node_modules/@babel/runtime/helpers/typeof.js"); var assertThisInitialized = __webpack_require__(/*! ./assertThisInitialized */ "./node_modules/next/node_modules/@babel/runtime/helpers/assertThisInitialized.js"); function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return assertThisInitialized(self); } module.exports = _possibleConstructorReturn; /***/ }), /***/ "./node_modules/next/node_modules/@babel/runtime/helpers/setPrototypeOf.js": /*!*********************************************************************************!*\ !*** ./node_modules/next/node_modules/@babel/runtime/helpers/setPrototypeOf.js ***! \*********************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { function _setPrototypeOf(o, p) { module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } module.exports = _setPrototypeOf; /***/ }), /***/ "./node_modules/next/node_modules/@babel/runtime/helpers/toConsumableArray.js": /*!************************************************************************************!*\ !*** ./node_modules/next/node_modules/@babel/runtime/helpers/toConsumableArray.js ***! \************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var arrayWithoutHoles = __webpack_require__(/*! ./arrayWithoutHoles */ "./node_modules/next/node_modules/@babel/runtime/helpers/arrayWithoutHoles.js"); var iterableToArray = __webpack_require__(/*! ./iterableToArray */ "./node_modules/next/node_modules/@babel/runtime/helpers/iterableToArray.js"); var unsupportedIterableToArray = __webpack_require__(/*! ./unsupportedIterableToArray */ "./node_modules/next/node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js"); var nonIterableSpread = __webpack_require__(/*! ./nonIterableSpread */ "./node_modules/next/node_modules/@babel/runtime/helpers/nonIterableSpread.js"); function _toConsumableArray(arr) { return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread(); } module.exports = _toConsumableArray; /***/ }), /***/ "./node_modules/next/node_modules/@babel/runtime/helpers/typeof.js": /*!*************************************************************************!*\ !*** ./node_modules/next/node_modules/@babel/runtime/helpers/typeof.js ***! \*************************************************************************/ /*! no static exports found */ /***/ (function(module, exports) { function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { module.exports = _typeof = function _typeof(obj) { return typeof obj; }; } else { module.exports = _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } module.exports = _typeof; /***/ }), /***/ "./node_modules/next/node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js": /*!*********************************************************************************************!*\ !*** ./node_modules/next/node_modules/@babel/runtime/helpers/unsupportedIterableToArray.js ***! \*********************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { var arrayLikeToArray = __webpack_require__(/*! ./arrayLikeToArray */ "./node_modules/next/node_modules/@babel/runtime/helpers/arrayLikeToArray.js"); function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen); } module.exports = _unsupportedIterableToArray; /***/ }), /***/ "./node_modules/next/node_modules/webpack/buildin/module.js": /*!***********************************!*\ !*** (webpack)/buildin/module.js ***! \***********************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function(module) { if (!module.webpackPolyfill) { module.deprecate = function() {}; module.paths = []; // module.parent = undefined by default if (!module.children) module.children = []; Object.defineProperty(module, "loaded", { enumerable: true, get: function() { return module.l; } }); Object.defineProperty(module, "id", { enumerable: true, get: function() { return module.i; } }); module.webpackPolyfill = 1; } return module; }; /***/ }), /***/ "./node_modules/prop-types/checkPropTypes.js": /*!***************************************************!*\ !*** ./node_modules/prop-types/checkPropTypes.js ***! \***************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var printWarning = function() {}; if (true) { var ReactPropTypesSecret = __webpack_require__(/*! ./lib/ReactPropTypesSecret */ "./node_modules/prop-types/lib/ReactPropTypesSecret.js"); var loggedTypeFailures = {}; var has = Function.call.bind(Object.prototype.hasOwnProperty); printWarning = function(text) { var message = 'Warning: ' + text; if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} }; } /** * Assert that the values match with the type specs. * Error messages are memorized and will only be shown once. * * @param {object} typeSpecs Map of name to a ReactPropType * @param {object} values Runtime values that need to be type-checked * @param {string} location e.g. "prop", "context", "child context" * @param {string} componentName Name of the component for error messages. * @param {?Function} getStack Returns the component stack. * @private */ function checkPropTypes(typeSpecs, values, location, componentName, getStack) { if (true) { for (var typeSpecName in typeSpecs) { if (has(typeSpecs, typeSpecName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. if (typeof typeSpecs[typeSpecName] !== 'function') { var err = Error( (componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' ); err.name = 'Invariant Violation'; throw err; } error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret); } catch (ex) { error = ex; } if (error && !(error instanceof Error)) { printWarning( (componentName || 'React class') + ': type specification of ' + location + ' `' + typeSpecName + '` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a ' + typeof error + '. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).' ); } if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var stack = getStack ? getStack() : ''; printWarning( 'Failed ' + location + ' type: ' + error.message + (stack != null ? stack : '') ); } } } } } /** * Resets warning cache when testing. * * @private */ checkPropTypes.resetWarningCache = function() { if (true) { loggedTypeFailures = {}; } } module.exports = checkPropTypes; /***/ }), /***/ "./node_modules/prop-types/lib/ReactPropTypesSecret.js": /*!*************************************************************!*\ !*** ./node_modules/prop-types/lib/ReactPropTypesSecret.js ***! \*************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; module.exports = ReactPropTypesSecret; /***/ }), /***/ "./node_modules/react/cjs/react.development.js": /*!*****************************************************!*\ !*** ./node_modules/react/cjs/react.development.js ***! \*****************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** @license React v16.13.1 * react.development.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ if (true) { (function() { 'use strict'; var _assign = __webpack_require__(/*! object-assign */ "./node_modules/next/dist/build/polyfills/object-assign.js"); var checkPropTypes = __webpack_require__(/*! prop-types/checkPropTypes */ "./node_modules/prop-types/checkPropTypes.js"); var ReactVersion = '16.13.1'; // The Symbol used to tag the ReactElement-like types. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var hasSymbol = typeof Symbol === 'function' && Symbol.for; var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for('react.element') : 0xeac7; var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca; var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb; var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc; var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2; var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd; var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace; // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf; var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0; var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1; var REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for('react.suspense_list') : 0xead8; var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3; var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4; var REACT_BLOCK_TYPE = hasSymbol ? Symbol.for('react.block') : 0xead9; var REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for('react.fundamental') : 0xead5; var REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for('react.responder') : 0xead6; var REACT_SCOPE_TYPE = hasSymbol ? Symbol.for('react.scope') : 0xead7; var MAYBE_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; function getIteratorFn(maybeIterable) { if (maybeIterable === null || typeof maybeIterable !== 'object') { return null; } var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; if (typeof maybeIterator === 'function') { return maybeIterator; } return null; } /** * Keeps track of the current dispatcher. */ var ReactCurrentDispatcher = { /** * @internal * @type {ReactComponent} */ current: null }; /** * Keeps track of the current batch's configuration such as how long an update * should suspend for if it needs to. */ var ReactCurrentBatchConfig = { suspense: null }; /** * Keeps track of the current owner. * * The current owner is the component who should own any components that are * currently being constructed. */ var ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null }; var BEFORE_SLASH_RE = /^(.*)[\\\/]/; function describeComponentFrame (name, source, ownerName) { var sourceInfo = ''; if (source) { var path = source.fileName; var fileName = path.replace(BEFORE_SLASH_RE, ''); { // In DEV, include code for a common special case: // prefer "folder/index.js" instead of just "index.js". if (/^index\./.test(fileName)) { var match = path.match(BEFORE_SLASH_RE); if (match) { var pathBeforeSlash = match[1]; if (pathBeforeSlash) { var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, ''); fileName = folderName + '/' + fileName; } } } } sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')'; } else if (ownerName) { sourceInfo = ' (created by ' + ownerName + ')'; } return '\n in ' + (name || 'Unknown') + sourceInfo; } var Resolved = 1; function refineResolvedLazyComponent(lazyComponent) { return lazyComponent._status === Resolved ? lazyComponent._result : null; } function getWrappedName(outerType, innerType, wrapperName) { var functionName = innerType.displayName || innerType.name || ''; return outerType.displayName || (functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName); } function getComponentName(type) { if (type == null) { // Host root, text node or just invalid type. return null; } { if (typeof type.tag === 'number') { error('Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.'); } } if (typeof type === 'function') { return type.displayName || type.name || null; } if (typeof type === 'string') { return type; } switch (type) { case REACT_FRAGMENT_TYPE: return 'Fragment'; case REACT_PORTAL_TYPE: return 'Portal'; case REACT_PROFILER_TYPE: return "Profiler"; case REACT_STRICT_MODE_TYPE: return 'StrictMode'; case REACT_SUSPENSE_TYPE: return 'Suspense'; case REACT_SUSPENSE_LIST_TYPE: return 'SuspenseList'; } if (typeof type === 'object') { switch (type.$$typeof) { case REACT_CONTEXT_TYPE: return 'Context.Consumer'; case REACT_PROVIDER_TYPE: return 'Context.Provider'; case REACT_FORWARD_REF_TYPE: return getWrappedName(type, type.render, 'ForwardRef'); case REACT_MEMO_TYPE: return getComponentName(type.type); case REACT_BLOCK_TYPE: return getComponentName(type.render); case REACT_LAZY_TYPE: { var thenable = type; var resolvedThenable = refineResolvedLazyComponent(thenable); if (resolvedThenable) { return getComponentName(resolvedThenable); } break; } } } return null; } var ReactDebugCurrentFrame = {}; var currentlyValidatingElement = null; function setCurrentlyValidatingElement(element) { { currentlyValidatingElement = element; } } { // Stack implementation injected by the current renderer. ReactDebugCurrentFrame.getCurrentStack = null; ReactDebugCurrentFrame.getStackAddendum = function () { var stack = ''; // Add an extra top frame while an element is being validated if (currentlyValidatingElement) { var name = getComponentName(currentlyValidatingElement.type); var owner = currentlyValidatingElement._owner; stack += describeComponentFrame(name, currentlyValidatingElement._source, owner && getComponentName(owner.type)); } // Delegate to the injected renderer-specific implementation var impl = ReactDebugCurrentFrame.getCurrentStack; if (impl) { stack += impl() || ''; } return stack; }; } /** * Used by act() to track whether you're inside an act() scope. */ var IsSomeRendererActing = { current: false }; var ReactSharedInternals = { ReactCurrentDispatcher: ReactCurrentDispatcher, ReactCurrentBatchConfig: ReactCurrentBatchConfig, ReactCurrentOwner: ReactCurrentOwner, IsSomeRendererActing: IsSomeRendererActing, // Used by renderers to avoid bundling object-assign twice in UMD bundles: assign: _assign }; { _assign(ReactSharedInternals, { // These should not be included in production. ReactDebugCurrentFrame: ReactDebugCurrentFrame, // Shim for React DOM 16.0.0 which still destructured (but not used) this. // TODO: remove in React 17.0. ReactComponentTreeHook: {} }); } // by calls to these methods by a Babel plugin. // // In PROD (or in packages without access to React internals), // they are left as they are instead. function warn(format) { { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } printWarning('warn', format, args); } } function error(format) { { for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } printWarning('error', format, args); } } function printWarning(level, format, args) { // When changing this logic, you might want to also // update consoleWithStackDev.www.js as well. { var hasExistingStack = args.length > 0 && typeof args[args.length - 1] === 'string' && args[args.length - 1].indexOf('\n in') === 0; if (!hasExistingStack) { var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; var stack = ReactDebugCurrentFrame.getStackAddendum(); if (stack !== '') { format += '%s'; args = args.concat([stack]); } } var argsWithFormat = args.map(function (item) { return '' + item; }); // Careful: RN currently depends on this prefix argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it // breaks IE9: https://github.com/facebook/react/issues/13610 // eslint-disable-next-line react-internal/no-production-logging Function.prototype.apply.call(console[level], console, argsWithFormat); try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); throw new Error(message); } catch (x) {} } } var didWarnStateUpdateForUnmountedComponent = {}; function warnNoop(publicInstance, callerName) { { var _constructor = publicInstance.constructor; var componentName = _constructor && (_constructor.displayName || _constructor.name) || 'ReactClass'; var warningKey = componentName + "." + callerName; if (didWarnStateUpdateForUnmountedComponent[warningKey]) { return; } error("Can't call %s on a component that is not yet mounted. " + 'This is a no-op, but it might indicate a bug in your application. ' + 'Instead, assign to `this.state` directly or define a `state = {};` ' + 'class property with the desired state in the %s component.', callerName, componentName); didWarnStateUpdateForUnmountedComponent[warningKey] = true; } } /** * This is the abstract API for an update queue. */ var ReactNoopUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function (publicInstance) { return false; }, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {?function} callback Called after component is updated. * @param {?string} callerName name of the calling function in the public API. * @internal */ enqueueForceUpdate: function (publicInstance, callback, callerName) { warnNoop(publicInstance, 'forceUpdate'); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @param {?function} callback Called after component is updated. * @param {?string} callerName name of the calling function in the public API. * @internal */ enqueueReplaceState: function (publicInstance, completeState, callback, callerName) { warnNoop(publicInstance, 'replaceState'); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @param {?function} callback Called after component is updated. * @param {?string} Name of the calling function in the public API. * @internal */ enqueueSetState: function (publicInstance, partialState, callback, callerName) { warnNoop(publicInstance, 'setState'); } }; var emptyObject = {}; { Object.freeze(emptyObject); } /** * Base class helpers for the updating state of a component. */ function Component(props, context, updater) { this.props = props; this.context = context; // If a component has string refs, we will assign a different object later. this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the // renderer. this.updater = updater || ReactNoopUpdateQueue; } Component.prototype.isReactComponent = {}; /** * Sets a subset of the state. Always use this to mutate * state. You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * There is no guarantee that calls to `setState` will run synchronously, * as they may eventually be batched together. You can provide an optional * callback that will be executed when the call to setState is actually * completed. * * When a function is provided to setState, it will be called at some point in * the future (not synchronously). It will be called with the up to date * component arguments (state, props, context). These values can be different * from this.* because your function may be called after receiveProps but before * shouldComponentUpdate, and this new state, props, and context will not yet be * assigned to this. * * @param {object|function} partialState Next partial state or function to * produce next partial state to be merged with current state. * @param {?function} callback Called after state is updated. * @final * @protected */ Component.prototype.setState = function (partialState, callback) { if (!(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null)) { { throw Error( "setState(...): takes an object of state variables to update or a function which returns an object of state variables." ); } } this.updater.enqueueSetState(this, partialState, callback, 'setState'); }; /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {?function} callback Called after update is complete. * @final * @protected */ Component.prototype.forceUpdate = function (callback) { this.updater.enqueueForceUpdate(this, callback, 'forceUpdate'); }; /** * Deprecated APIs. These APIs used to exist on classic React classes but since * we would like to deprecate them, we're not going to move them over to this * modern base class. Instead, we define a getter that warns if it's accessed. */ { var deprecatedAPIs = { isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'], replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).'] }; var defineDeprecationWarning = function (methodName, info) { Object.defineProperty(Component.prototype, methodName, { get: function () { warn('%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]); return undefined; } }); }; for (var fnName in deprecatedAPIs) { if (deprecatedAPIs.hasOwnProperty(fnName)) { defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); } } } function ComponentDummy() {} ComponentDummy.prototype = Component.prototype; /** * Convenience component with default shallow equality check for sCU. */ function PureComponent(props, context, updater) { this.props = props; this.context = context; // If a component has string refs, we will assign a different object later. this.refs = emptyObject; this.updater = updater || ReactNoopUpdateQueue; } var pureComponentPrototype = PureComponent.prototype = new ComponentDummy(); pureComponentPrototype.constructor = PureComponent; // Avoid an extra prototype jump for these methods. _assign(pureComponentPrototype, Component.prototype); pureComponentPrototype.isPureReactComponent = true; // an immutable object with a single mutable value function createRef() { var refObject = { current: null }; { Object.seal(refObject); } return refObject; } var hasOwnProperty = Object.prototype.hasOwnProperty; var RESERVED_PROPS = { key: true, ref: true, __self: true, __source: true }; var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs; { didWarnAboutStringRefs = {}; } function hasValidRef(config) { { if (hasOwnProperty.call(config, 'ref')) { var getter = Object.getOwnPropertyDescriptor(config, 'ref').get; if (getter && getter.isReactWarning) { return false; } } } return config.ref !== undefined; } function hasValidKey(config) { { if (hasOwnProperty.call(config, 'key')) { var getter = Object.getOwnPropertyDescriptor(config, 'key').get; if (getter && getter.isReactWarning) { return false; } } } return config.key !== undefined; } function defineKeyPropWarningGetter(props, displayName) { var warnAboutAccessingKey = function () { { if (!specialPropKeyWarningShown) { specialPropKeyWarningShown = true; error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName); } } }; warnAboutAccessingKey.isReactWarning = true; Object.defineProperty(props, 'key', { get: warnAboutAccessingKey, configurable: true }); } function defineRefPropWarningGetter(props, displayName) { var warnAboutAccessingRef = function () { { if (!specialPropRefWarningShown) { specialPropRefWarningShown = true; error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', displayName); } } }; warnAboutAccessingRef.isReactWarning = true; Object.defineProperty(props, 'ref', { get: warnAboutAccessingRef, configurable: true }); } function warnIfStringRefCannotBeAutoConverted(config) { { if (typeof config.ref === 'string' && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) { var componentName = getComponentName(ReactCurrentOwner.current.type); if (!didWarnAboutStringRefs[componentName]) { error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://fb.me/react-strict-mode-string-ref', getComponentName(ReactCurrentOwner.current.type), config.ref); didWarnAboutStringRefs[componentName] = true; } } } } /** * Factory method to create a new React element. This no longer adheres to * the class pattern, so do not use new to call it. Also, instanceof check * will not work. Instead test $$typeof field against Symbol.for('react.element') to check * if something is a React Element. * * @param {*} type * @param {*} props * @param {*} key * @param {string|object} ref * @param {*} owner * @param {*} self A *temporary* helper to detect places where `this` is * different from the `owner` when React.createElement is called, so that we * can warn. We want to get rid of owner and replace string `ref`s with arrow * functions, and as long as `this` and owner are the same, there will be no * change in behavior. * @param {*} source An annotation object (added by a transpiler or otherwise) * indicating filename, line number, and/or other information. * @internal */ var ReactElement = function (type, key, ref, self, source, owner, props) { var element = { // This tag allows us to uniquely identify this as a React Element $$typeof: REACT_ELEMENT_TYPE, // Built-in properties that belong on the element type: type, key: key, ref: ref, props: props, // Record the component responsible for creating this element. _owner: owner }; { // The validation flag is currently mutative. We put it on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. element._store = {}; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. Object.defineProperty(element._store, 'validated', { configurable: false, enumerable: false, writable: true, value: false }); // self and source are DEV only properties. Object.defineProperty(element, '_self', { configurable: false, enumerable: false, writable: false, value: self }); // Two elements created in two different places should be considered // equal for testing purposes and therefore we hide it from enumeration. Object.defineProperty(element, '_source', { configurable: false, enumerable: false, writable: false, value: source }); if (Object.freeze) { Object.freeze(element.props); Object.freeze(element); } } return element; }; /** * Create and return a new ReactElement of the given type. * See https://reactjs.org/docs/react-api.html#createelement */ function createElement(type, config, children) { var propName; // Reserved names are extracted var props = {}; var key = null; var ref = null; var self = null; var source = null; if (config != null) { if (hasValidRef(config)) { ref = config.ref; { warnIfStringRefCannotBeAutoConverted(config); } } if (hasValidKey(config)) { key = '' + config.key; } self = config.__self === undefined ? null : config.__self; source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } { if (Object.freeze) { Object.freeze(childArray); } } props.children = childArray; } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } } { if (key || ref) { var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type; if (key) { defineKeyPropWarningGetter(props, displayName); } if (ref) { defineRefPropWarningGetter(props, displayName); } } } return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); } function cloneAndReplaceKey(oldElement, newKey) { var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); return newElement; } /** * Clone and return a new ReactElement using element as the starting point. * See https://reactjs.org/docs/react-api.html#cloneelement */ function cloneElement(element, config, children) { if (!!(element === null || element === undefined)) { { throw Error( "React.cloneElement(...): The argument must be a React element, but you passed " + element + "." ); } } var propName; // Original props are copied var props = _assign({}, element.props); // Reserved names are extracted var key = element.key; var ref = element.ref; // Self is preserved since the owner is preserved. var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a // transpiler, and the original source is probably a better indicator of the // true owner. var source = element._source; // Owner will be preserved, unless ref is overridden var owner = element._owner; if (config != null) { if (hasValidRef(config)) { // Silently steal the ref from the parent. ref = config.ref; owner = ReactCurrentOwner.current; } if (hasValidKey(config)) { key = '' + config.key; } // Remaining properties override existing props var defaultProps; if (element.type && element.type.defaultProps) { defaultProps = element.type.defaultProps; } for (propName in config) { if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { if (config[propName] === undefined && defaultProps !== undefined) { // Resolve default props props[propName] = defaultProps[propName]; } else { props[propName] = config[propName]; } } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } return ReactElement(element.type, key, ref, self, source, owner, props); } /** * Verifies the object is a ReactElement. * See https://reactjs.org/docs/react-api.html#isvalidelement * @param {?object} object * @return {boolean} True if `object` is a ReactElement. * @final */ function isValidElement(object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; } var SEPARATOR = '.'; var SUBSEPARATOR = ':'; /** * Escape and wrap key so it is safe to use as a reactid * * @param {string} key to be escaped. * @return {string} the escaped key. */ function escape(key) { var escapeRegex = /[=:]/g; var escaperLookup = { '=': '=0', ':': '=2' }; var escapedString = ('' + key).replace(escapeRegex, function (match) { return escaperLookup[match]; }); return '$' + escapedString; } /** * TODO: Test that a single child and an array with one item have the same key * pattern. */ var didWarnAboutMaps = false; var userProvidedKeyEscapeRegex = /\/+/g; function escapeUserProvidedKey(text) { return ('' + text).replace(userProvidedKeyEscapeRegex, '$&/'); } var POOL_SIZE = 10; var traverseContextPool = []; function getPooledTraverseContext(mapResult, keyPrefix, mapFunction, mapContext) { if (traverseContextPool.length) { var traverseContext = traverseContextPool.pop(); traverseContext.result = mapResult; traverseContext.keyPrefix = keyPrefix; traverseContext.func = mapFunction; traverseContext.context = mapContext; traverseContext.count = 0; return traverseContext; } else { return { result: mapResult, keyPrefix: keyPrefix, func: mapFunction, context: mapContext, count: 0 }; } } function releaseTraverseContext(traverseContext) { traverseContext.result = null; traverseContext.keyPrefix = null; traverseContext.func = null; traverseContext.context = null; traverseContext.count = 0; if (traverseContextPool.length < POOL_SIZE) { traverseContextPool.push(traverseContext); } } /** * @param {?*} children Children tree container. * @param {!string} nameSoFar Name of the key path so far. * @param {!function} callback Callback to invoke with each child found. * @param {?*} traverseContext Used to pass information throughout the traversal * process. * @return {!number} The number of children in this subtree. */ function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) { var type = typeof children; if (type === 'undefined' || type === 'boolean') { // All of the above are perceived as null. children = null; } var invokeCallback = false; if (children === null) { invokeCallback = true; } else { switch (type) { case 'string': case 'number': invokeCallback = true; break; case 'object': switch (children.$$typeof) { case REACT_ELEMENT_TYPE: case REACT_PORTAL_TYPE: invokeCallback = true; } } } if (invokeCallback) { callback(traverseContext, children, // If it's the only child, treat the name as if it was wrapped in an array // so that it's consistent if the number of children grows. nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar); return 1; } var child; var nextName; var subtreeCount = 0; // Count of children found in the current subtree. var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR; if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { child = children[i]; nextName = nextNamePrefix + getComponentKey(child, i); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { var iteratorFn = getIteratorFn(children); if (typeof iteratorFn === 'function') { { // Warn about using Maps as children if (iteratorFn === children.entries) { if (!didWarnAboutMaps) { warn('Using Maps as children is deprecated and will be removed in ' + 'a future major release. Consider converting children to ' + 'an array of keyed ReactElements instead.'); } didWarnAboutMaps = true; } } var iterator = iteratorFn.call(children); var step; var ii = 0; while (!(step = iterator.next()).done) { child = step.value; nextName = nextNamePrefix + getComponentKey(child, ii++); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else if (type === 'object') { var addendum = ''; { addendum = ' If you meant to render a collection of children, use an array ' + 'instead.' + ReactDebugCurrentFrame.getStackAddendum(); } var childrenString = '' + children; { { throw Error( "Objects are not valid as a React child (found: " + (childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString) + ")." + addendum ); } } } } return subtreeCount; } /** * Traverses children that are typically specified as `props.children`, but * might also be specified through attributes: * * - `traverseAllChildren(this.props.children, ...)` * - `traverseAllChildren(this.props.leftPanelChildren, ...)` * * The `traverseContext` is an optional argument that is passed through the * entire traversal. It can be used to store accumulations or anything else that * the callback might find relevant. * * @param {?*} children Children tree object. * @param {!function} callback To invoke upon traversing each child. * @param {?*} traverseContext Context for traversal. * @return {!number} The number of children in this subtree. */ function traverseAllChildren(children, callback, traverseContext) { if (children == null) { return 0; } return traverseAllChildrenImpl(children, '', callback, traverseContext); } /** * Generate a key string that identifies a component within a set. * * @param {*} component A component that could contain a manual key. * @param {number} index Index that is used if a manual key is not provided. * @return {string} */ function getComponentKey(component, index) { // Do some typechecking here since we call this blindly. We want to ensure // that we don't block potential future ES APIs. if (typeof component === 'object' && component !== null && component.key != null) { // Explicit key return escape(component.key); } // Implicit key determined by the index in the set return index.toString(36); } function forEachSingleChild(bookKeeping, child, name) { var func = bookKeeping.func, context = bookKeeping.context; func.call(context, child, bookKeeping.count++); } /** * Iterates through children that are typically specified as `props.children`. * * See https://reactjs.org/docs/react-api.html#reactchildrenforeach * * The provided forEachFunc(child, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} forEachFunc * @param {*} forEachContext Context for forEachContext. */ function forEachChildren(children, forEachFunc, forEachContext) { if (children == null) { return children; } var traverseContext = getPooledTraverseContext(null, null, forEachFunc, forEachContext); traverseAllChildren(children, forEachSingleChild, traverseContext); releaseTraverseContext(traverseContext); } function mapSingleChildIntoContext(bookKeeping, child, childKey) { var result = bookKeeping.result, keyPrefix = bookKeeping.keyPrefix, func = bookKeeping.func, context = bookKeeping.context; var mappedChild = func.call(context, child, bookKeeping.count++); if (Array.isArray(mappedChild)) { mapIntoWithKeyPrefixInternal(mappedChild, result, childKey, function (c) { return c; }); } else if (mappedChild != null) { if (isValidElement(mappedChild)) { mappedChild = cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as // traverseAllChildren used to do for objects as children keyPrefix + (mappedChild.key && (!child || child.key !== mappedChild.key) ? escapeUserProvidedKey(mappedChild.key) + '/' : '') + childKey); } result.push(mappedChild); } } function mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) { var escapedPrefix = ''; if (prefix != null) { escapedPrefix = escapeUserProvidedKey(prefix) + '/'; } var traverseContext = getPooledTraverseContext(array, escapedPrefix, func, context); traverseAllChildren(children, mapSingleChildIntoContext, traverseContext); releaseTraverseContext(traverseContext); } /** * Maps children that are typically specified as `props.children`. * * See https://reactjs.org/docs/react-api.html#reactchildrenmap * * The provided mapFunction(child, key, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} func The map function. * @param {*} context Context for mapFunction. * @return {object} Object containing the ordered map of results. */ function mapChildren(children, func, context) { if (children == null) { return children; } var result = []; mapIntoWithKeyPrefixInternal(children, result, null, func, context); return result; } /** * Count the number of children that are typically specified as * `props.children`. * * See https://reactjs.org/docs/react-api.html#reactchildrencount * * @param {?*} children Children tree container. * @return {number} The number of children. */ function countChildren(children) { return traverseAllChildren(children, function () { return null; }, null); } /** * Flatten a children object (typically specified as `props.children`) and * return an array with appropriately re-keyed children. * * See https://reactjs.org/docs/react-api.html#reactchildrentoarray */ function toArray(children) { var result = []; mapIntoWithKeyPrefixInternal(children, result, null, function (child) { return child; }); return result; } /** * Returns the first child in a collection of children and verifies that there * is only one child in the collection. * * See https://reactjs.org/docs/react-api.html#reactchildrenonly * * The current implementation of this function assumes that a single child gets * passed without a wrapper, but the purpose of this helper function is to * abstract away the particular structure of children. * * @param {?object} children Child collection structure. * @return {ReactElement} The first and only `ReactElement` contained in the * structure. */ function onlyChild(children) { if (!isValidElement(children)) { { throw Error( "React.Children.only expected to receive a single React element child." ); } } return children; } function createContext(defaultValue, calculateChangedBits) { if (calculateChangedBits === undefined) { calculateChangedBits = null; } else { { if (calculateChangedBits !== null && typeof calculateChangedBits !== 'function') { error('createContext: Expected the optional second argument to be a ' + 'function. Instead received: %s', calculateChangedBits); } } } var context = { $$typeof: REACT_CONTEXT_TYPE, _calculateChangedBits: calculateChangedBits, // As a workaround to support multiple concurrent renderers, we categorize // some renderers as primary and others as secondary. We only expect // there to be two concurrent renderers at most: React Native (primary) and // Fabric (secondary); React DOM (primary) and React ART (secondary). // Secondary renderers store their context values on separate fields. _currentValue: defaultValue, _currentValue2: defaultValue, // Used to track how many concurrent renderers this context currently // supports within in a single renderer. Such as parallel server rendering. _threadCount: 0, // These are circular Provider: null, Consumer: null }; context.Provider = { $$typeof: REACT_PROVIDER_TYPE, _context: context }; var hasWarnedAboutUsingNestedContextConsumers = false; var hasWarnedAboutUsingConsumerProvider = false; { // A separate object, but proxies back to the original context object for // backwards compatibility. It has a different $$typeof, so we can properly // warn for the incorrect usage of Context as a Consumer. var Consumer = { $$typeof: REACT_CONTEXT_TYPE, _context: context, _calculateChangedBits: context._calculateChangedBits }; // $FlowFixMe: Flow complains about not setting a value, which is intentional here Object.defineProperties(Consumer, { Provider: { get: function () { if (!hasWarnedAboutUsingConsumerProvider) { hasWarnedAboutUsingConsumerProvider = true; error('Rendering <Context.Consumer.Provider> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Provider> instead?'); } return context.Provider; }, set: function (_Provider) { context.Provider = _Provider; } }, _currentValue: { get: function () { return context._currentValue; }, set: function (_currentValue) { context._currentValue = _currentValue; } }, _currentValue2: { get: function () { return context._currentValue2; }, set: function (_currentValue2) { context._currentValue2 = _currentValue2; } }, _threadCount: { get: function () { return context._threadCount; }, set: function (_threadCount) { context._threadCount = _threadCount; } }, Consumer: { get: function () { if (!hasWarnedAboutUsingNestedContextConsumers) { hasWarnedAboutUsingNestedContextConsumers = true; error('Rendering <Context.Consumer.Consumer> is not supported and will be removed in ' + 'a future major release. Did you mean to render <Context.Consumer> instead?'); } return context.Consumer; } } }); // $FlowFixMe: Flow complains about missing properties because it doesn't understand defineProperty context.Consumer = Consumer; } { context._currentRenderer = null; context._currentRenderer2 = null; } return context; } function lazy(ctor) { var lazyType = { $$typeof: REACT_LAZY_TYPE, _ctor: ctor, // React uses these fields to store the result. _status: -1, _result: null }; { // In production, this would just set it on the object. var defaultProps; var propTypes; Object.defineProperties(lazyType, { defaultProps: { configurable: true, get: function () { return defaultProps; }, set: function (newDefaultProps) { error('React.lazy(...): It is not supported to assign `defaultProps` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.'); defaultProps = newDefaultProps; // Match production behavior more closely: Object.defineProperty(lazyType, 'defaultProps', { enumerable: true }); } }, propTypes: { configurable: true, get: function () { return propTypes; }, set: function (newPropTypes) { error('React.lazy(...): It is not supported to assign `propTypes` to ' + 'a lazy component import. Either specify them where the component ' + 'is defined, or create a wrapping component around it.'); propTypes = newPropTypes; // Match production behavior more closely: Object.defineProperty(lazyType, 'propTypes', { enumerable: true }); } } }); } return lazyType; } function forwardRef(render) { { if (render != null && render.$$typeof === REACT_MEMO_TYPE) { error('forwardRef requires a render function but received a `memo` ' + 'component. Instead of forwardRef(memo(...)), use ' + 'memo(forwardRef(...)).'); } else if (typeof render !== 'function') { error('forwardRef requires a render function but was given %s.', render === null ? 'null' : typeof render); } else { if (render.length !== 0 && render.length !== 2) { error('forwardRef render functions accept exactly two parameters: props and ref. %s', render.length === 1 ? 'Did you forget to use the ref parameter?' : 'Any additional parameter will be undefined.'); } } if (render != null) { if (render.defaultProps != null || render.propTypes != null) { error('forwardRef render functions do not support propTypes or defaultProps. ' + 'Did you accidentally pass a React component?'); } } } return { $$typeof: REACT_FORWARD_REF_TYPE, render: render }; } function isValidElementType(type) { return typeof type === 'string' || typeof type === 'function' || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill. type === REACT_FRAGMENT_TYPE || type === REACT_CONCURRENT_MODE_TYPE || type === REACT_PROFILER_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || typeof type === 'object' && type !== null && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_RESPONDER_TYPE || type.$$typeof === REACT_SCOPE_TYPE || type.$$typeof === REACT_BLOCK_TYPE); } function memo(type, compare) { { if (!isValidElementType(type)) { error('memo: The first argument must be a component. Instead ' + 'received: %s', type === null ? 'null' : typeof type); } } return { $$typeof: REACT_MEMO_TYPE, type: type, compare: compare === undefined ? null : compare }; } function resolveDispatcher() { var dispatcher = ReactCurrentDispatcher.current; if (!(dispatcher !== null)) { { throw Error( "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem." ); } } return dispatcher; } function useContext(Context, unstable_observedBits) { var dispatcher = resolveDispatcher(); { if (unstable_observedBits !== undefined) { error('useContext() second argument is reserved for future ' + 'use in React. Passing it is not supported. ' + 'You passed: %s.%s', unstable_observedBits, typeof unstable_observedBits === 'number' && Array.isArray(arguments[2]) ? '\n\nDid you call array.map(useContext)? ' + 'Calling Hooks inside a loop is not supported. ' + 'Learn more at https://fb.me/rules-of-hooks' : ''); } // TODO: add a more generic warning for invalid values. if (Context._context !== undefined) { var realContext = Context._context; // Don't deduplicate because this legitimately causes bugs // and nobody should be using this in existing code. if (realContext.Consumer === Context) { error('Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be ' + 'removed in a future major release. Did you mean to call useContext(Context) instead?'); } else if (realContext.Provider === Context) { error('Calling useContext(Context.Provider) is not supported. ' + 'Did you mean to call useContext(Context) instead?'); } } } return dispatcher.useContext(Context, unstable_observedBits); } function useState(initialState) { var dispatcher = resolveDispatcher(); return dispatcher.useState(initialState); } function useReducer(reducer, initialArg, init) { var dispatcher = resolveDispatcher(); return dispatcher.useReducer(reducer, initialArg, init); } function useRef(initialValue) { var dispatcher = resolveDispatcher(); return dispatcher.useRef(initialValue); } function useEffect(create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useEffect(create, deps); } function useLayoutEffect(create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useLayoutEffect(create, deps); } function useCallback(callback, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useCallback(callback, deps); } function useMemo(create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useMemo(create, deps); } function useImperativeHandle(ref, create, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useImperativeHandle(ref, create, deps); } function useDebugValue(value, formatterFn) { { var dispatcher = resolveDispatcher(); return dispatcher.useDebugValue(value, formatterFn); } } var propTypesMisspellWarningShown; { propTypesMisspellWarningShown = false; } function getDeclarationErrorAddendum() { if (ReactCurrentOwner.current) { var name = getComponentName(ReactCurrentOwner.current.type); if (name) { return '\n\nCheck the render method of `' + name + '`.'; } } return ''; } function getSourceInfoErrorAddendum(source) { if (source !== undefined) { var fileName = source.fileName.replace(/^.*[\\\/]/, ''); var lineNumber = source.lineNumber; return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.'; } return ''; } function getSourceInfoErrorAddendumForProps(elementProps) { if (elementProps !== null && elementProps !== undefined) { return getSourceInfoErrorAddendum(elementProps.__source); } return ''; } /** * Warn if there's no key explicitly set on dynamic arrays of children or * object keys are not valid. This allows us to keep track of children between * updates. */ var ownerHasKeyUseWarning = {}; function getCurrentComponentErrorInfo(parentType) { var info = getDeclarationErrorAddendum(); if (!info) { var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; if (parentName) { info = "\n\nCheck the top-level render call using <" + parentName + ">."; } } return info; } /** * Warn if the element doesn't have an explicit key assigned to it. * This element is in an array. The array could grow and shrink or be * reordered. All children that haven't already been validated are required to * have a "key" property assigned to it. Error statuses are cached so a warning * will only be shown once. * * @internal * @param {ReactElement} element Element that requires a key. * @param {*} parentType element's parent's type. */ function validateExplicitKey(element, parentType) { if (!element._store || element._store.validated || element.key != null) { return; } element._store.validated = true; var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { return; } ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a // property, it may be the creator of the child that's responsible for // assigning it a key. var childOwner = ''; if (element && element._owner && element._owner !== ReactCurrentOwner.current) { // Give the component that originally created this child. childOwner = " It was passed a child from " + getComponentName(element._owner.type) + "."; } setCurrentlyValidatingElement(element); { error('Each child in a list should have a unique "key" prop.' + '%s%s See https://fb.me/react-warning-keys for more information.', currentComponentErrorInfo, childOwner); } setCurrentlyValidatingElement(null); } /** * Ensure that every element either is passed in a static location, in an * array with an explicit keys property defined, or in an object literal * with valid key property. * * @internal * @param {ReactNode} node Statically passed child of any type. * @param {*} parentType node's parent's type. */ function validateChildKeys(node, parentType) { if (typeof node !== 'object') { return; } if (Array.isArray(node)) { for (var i = 0; i < node.length; i++) { var child = node[i]; if (isValidElement(child)) { validateExplicitKey(child, parentType); } } } else if (isValidElement(node)) { // This element was passed in a valid location. if (node._store) { node._store.validated = true; } } else if (node) { var iteratorFn = getIteratorFn(node); if (typeof iteratorFn === 'function') { // Entry iterators used to provide implicit keys, // but now we print a separate warning for them later. if (iteratorFn !== node.entries) { var iterator = iteratorFn.call(node); var step; while (!(step = iterator.next()).done) { if (isValidElement(step.value)) { validateExplicitKey(step.value, parentType); } } } } } } /** * Given an element, validate that its props follow the propTypes definition, * provided by the type. * * @param {ReactElement} element */ function validatePropTypes(element) { { var type = element.type; if (type === null || type === undefined || typeof type === 'string') { return; } var name = getComponentName(type); var propTypes; if (typeof type === 'function') { propTypes = type.propTypes; } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here. // Inner props are checked in the reconciler. type.$$typeof === REACT_MEMO_TYPE)) { propTypes = type.propTypes; } else { return; } if (propTypes) { setCurrentlyValidatingElement(element); checkPropTypes(propTypes, element.props, 'prop', name, ReactDebugCurrentFrame.getStackAddendum); setCurrentlyValidatingElement(null); } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) { propTypesMisspellWarningShown = true; error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', name || 'Unknown'); } if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) { error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.'); } } } /** * Given a fragment, validate that it can only be provided with fragment props * @param {ReactElement} fragment */ function validateFragmentProps(fragment) { { setCurrentlyValidatingElement(fragment); var keys = Object.keys(fragment.props); for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (key !== 'children' && key !== 'key') { error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key); break; } } if (fragment.ref !== null) { error('Invalid attribute `ref` supplied to `React.Fragment`.'); } setCurrentlyValidatingElement(null); } } function createElementWithValidation(type, props, children) { var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to // succeed and there will likely be errors in render. if (!validType) { var info = ''; if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) { info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports."; } var sourceInfo = getSourceInfoErrorAddendumForProps(props); if (sourceInfo) { info += sourceInfo; } else { info += getDeclarationErrorAddendum(); } var typeString; if (type === null) { typeString = 'null'; } else if (Array.isArray(type)) { typeString = 'array'; } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) { typeString = "<" + (getComponentName(type.type) || 'Unknown') + " />"; info = ' Did you accidentally export a JSX literal instead of a component?'; } else { typeString = typeof type; } { error('React.createElement: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info); } } var element = createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used. // TODO: Drop this when these are no longer allowed as the type argument. if (element == null) { return element; } // Skip key warning if the type isn't valid since our key validation logic // doesn't expect a non-string/function type and can throw confusing errors. // We don't want exception behavior to differ between dev and prod. // (Rendering will throw with a helpful message and as soon as the type is // fixed, the key warnings will appear.) if (validType) { for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], type); } } if (type === REACT_FRAGMENT_TYPE) { validateFragmentProps(element); } else { validatePropTypes(element); } return element; } var didWarnAboutDeprecatedCreateFactory = false; function createFactoryWithValidation(type) { var validatedFactory = createElementWithValidation.bind(null, type); validatedFactory.type = type; { if (!didWarnAboutDeprecatedCreateFactory) { didWarnAboutDeprecatedCreateFactory = true; warn('React.createFactory() is deprecated and will be removed in ' + 'a future major release. Consider using JSX ' + 'or use React.createElement() directly instead.'); } // Legacy hook: remove it Object.defineProperty(validatedFactory, 'type', { enumerable: false, get: function () { warn('Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.'); Object.defineProperty(this, 'type', { value: type }); return type; } }); } return validatedFactory; } function cloneElementWithValidation(element, props, children) { var newElement = cloneElement.apply(this, arguments); for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], newElement.type); } validatePropTypes(newElement); return newElement; } { try { var frozenObject = Object.freeze({}); var testMap = new Map([[frozenObject, null]]); var testSet = new Set([frozenObject]); // This is necessary for Rollup to not consider these unused. // https://github.com/rollup/rollup/issues/1771 // TODO: we can remove these if Rollup fixes the bug. testMap.set(0, 0); testSet.add(0); } catch (e) { } } var createElement$1 = createElementWithValidation ; var cloneElement$1 = cloneElementWithValidation ; var createFactory = createFactoryWithValidation ; var Children = { map: mapChildren, forEach: forEachChildren, count: countChildren, toArray: toArray, only: onlyChild }; exports.Children = Children; exports.Component = Component; exports.Fragment = REACT_FRAGMENT_TYPE; exports.Profiler = REACT_PROFILER_TYPE; exports.PureComponent = PureComponent; exports.StrictMode = REACT_STRICT_MODE_TYPE; exports.Suspense = REACT_SUSPENSE_TYPE; exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals; exports.cloneElement = cloneElement$1; exports.createContext = createContext; exports.createElement = createElement$1; exports.createFactory = createFactory; exports.createRef = createRef; exports.forwardRef = forwardRef; exports.isValidElement = isValidElement; exports.lazy = lazy; exports.memo = memo; exports.useCallback = useCallback; exports.useContext = useContext; exports.useDebugValue = useDebugValue; exports.useEffect = useEffect; exports.useImperativeHandle = useImperativeHandle; exports.useLayoutEffect = useLayoutEffect; exports.useMemo = useMemo; exports.useReducer = useReducer; exports.useRef = useRef; exports.useState = useState; exports.version = ReactVersion; })(); } /***/ }), /***/ "./node_modules/react/index.js": /*!*************************************!*\ !*** ./node_modules/react/index.js ***! \*************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; if (false) {} else { module.exports = __webpack_require__(/*! ./cjs/react.development.js */ "./node_modules/react/cjs/react.development.js"); } /***/ }) },[["./node_modules/next/dist/build/webpack/loaders/next-client-pages-loader.js?page=%2F_error&absolutePagePath=next%2Fdist%2Fpages%2F_error!./","webpack"]]]); //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly9fTl9FLy4vbm9kZV9tb2R1bGVzL25leHQvZGlzdC9idWlsZC9wb2x5ZmlsbHMvb2JqZWN0LWFzc2lnbi5qcyIsIndlYnBhY2s6Ly9fTl9FLy4vbm9kZV9tb2R1bGVzL25leHQvZGlzdC9idWlsZC93ZWJwYWNrL2xvYWRlcnMvbmV4dC1jbGllbnQtcGFnZXMtbG9hZGVyLmpzIiwid2VicGFjazovL19OX0UvLi4vLi4vLi4vbmV4dC1zZXJ2ZXIvbGliL2FtcC1jb250ZXh0LnRzIiwid2VicGFjazovL19OX0UvLi4vLi4vLi4vbmV4dC1zZXJ2ZXIvbGliL2FtcC50cyIsIndlYnBhY2s6Ly9fTl9FLy4uLy4uLy4uL25leHQtc2VydmVyL2xpYi9oZWFkLW1hbmFnZXItY29udGV4dC50cyIsIndlYnBhY2s6Ly9fTl9FLy4uLy4uLy4uL25leHQtc2VydmVyL2xpYi9oZWFkLnRzeCIsIndlYnBhY2s6Ly9fTl9FLy4uLy4uLy4uL25leHQtc2VydmVyL2xpYi9zaWRlLWVmZmVjdC50c3giLCJ3ZWJwYWNrOi8vX05fRS8uLi8uLi9wYWdlcy9fZXJyb3IudHN4Iiwid2VicGFjazovL19OX0UvLi9ub2RlX21vZHVs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iAgICAgICAgICByZXR1cm4gY29udGV4dC5fY3VycmVudFZhbHVlO1xuICAgICAgICB9LFxuICAgICAgICBzZXQ6IGZ1bmN0aW9uIChfY3VycmVudFZhbHVlKSB7XG4gICAgICAgICAgY29udGV4dC5fY3VycmVudFZhbHVlID0gX2N1cnJlbnRWYWx1ZTtcbiAgICAgICAgfVxuICAgICAgfSxcbiAgICAgIF9jdXJyZW50VmFsdWUyOiB7XG4gICAgICAgIGdldDogZnVuY3Rpb24gKCkge1xuICAgICAgICAgIHJldHVybiBjb250ZXh0Ll9jdXJyZW50VmFsdWUyO1xuICAgICAgICB9LFxuICAgICAgICBzZXQ6IGZ1bmN0aW9uIChfY3VycmVudFZhbHVlMikge1xuICAgICAgICAgIGNvbnRleHQuX2N1cnJlbnRWYWx1ZTIgPSBfY3VycmVudFZhbHVlMjtcbiAgICAgICAgfVxuICAgICAgfSxcbiAgICAgIF90aHJlYWRDb3VudDoge1xuICAgICAgICBnZXQ6IGZ1bmN0aW9uICgpIHtcbiAgICAgICAgICByZXR1cm4gY29udGV4dC5fdGhyZWFkQ291bnQ7XG4gICAgICAgIH0sXG4gICAgICAgIHNldDogZnVuY3Rpb24gKF90aHJlYWRDb3VudCkge1xuICAgICAgICAgIGNvbnRleHQuX3RocmVhZENvdW50ID0gX3RocmVhZENvdW50O1xuICAgICAgICB9XG4gICAgICB9LFxuICAgICAgQ29uc3VtZXI6IHtcbiAgICAgICAgZ2V0OiBmdW5jdGlvbiAoKSB7XG4gICAgICAgICAgaWYgKCFoYXNXYXJuZWRBYm91dFVzaW5nTmVzdGVkQ29udGV4dENvbnN1bWVycykge1xuICAgICAgICAgICAgaGFzV2FybmVkQWJvdXRVc2luZ05lc3RlZENvbnRleHRDb25zdW1lcnMgPSB0cnVlO1xuXG4gICAgICAgICAgICBlcnJvcignUmVuZGVyaW5nIDxDb250ZXh0LkNvbnN1bWVyLkNvbnN1bWVyPiBpcyBub3Qgc3VwcG9ydGVkIGFuZCB3aWxsIGJlIH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CcuL2Nqcy9yZWFjdC5kZXZlbG9wbWVudC5qcycpO1xufVxuIl0sInNvdXJjZVJvb3QiOiIifQ==
/* @flow */ import path from "path" import zealot from "../../index" import {ztestDir} from "../env" describe("zealot client spaces tests", () => { const client = zealot.client("localhost:9867") let spaceName = "newSpace" let spaceId const spacePath = (spaceId) => path.join(path.resolve(ztestDir()), spaceId) const emptySpace = { pcap_path: "", pcap_size: 0, pcap_support: false, size: 0 } test("create space", async () => { const resp = await client.spaces.create({name: spaceName}) expect(resp.name).toBe(spaceName) expect(resp.id).toBeDefined() spaceId = resp.id }) test("list spaces", async () => { const resp = await client.spaces.list() expect(resp).toHaveLength(1) expect(resp).toEqual([ { ...emptySpace, data_path: spacePath(spaceId), name: spaceName, id: spaceId } ]) }) test("update space", async () => { const newName = "updated space name" const resp = await client.spaces.update(spaceId, {name: newName}) expect(resp).toEqual("") spaceName = newName }) test("get space by id", async () => { const resp = await client.spaces.get(spaceId) expect(resp).toEqual({ ...emptySpace, data_path: spacePath(spaceId), name: spaceName, id: spaceId }) }) test("delete space", async () => { const resp = await client.spaces.delete(spaceId) expect(resp).toBe("") }) })
/* * Created in février 2021 * Written by Eden Cadagiani <e.cadagiani@gmail.com> */ const GAME_STATUS = { "IN_PROGRESS": "IN_PROGRESS", "FAIL": "FAIL", "WIN": "WIN", }; const DEFAULT_WIDTH = 7; const DEFAULT_HEIGHT = 4; const DEFAULT_TIME = 120; // in second module.exports = { GAME_STATUS, DEFAULT_WIDTH, DEFAULT_HEIGHT, DEFAULT_TIME };
// THIS FILE IS AUTO GENERATED var GenIcon = require('../lib').GenIcon module.exports.BiMenu = function BiMenu (props) { return GenIcon({"tag":"svg","attr":{"viewBox":"0 0 24 24"},"child":[{"tag":"path","attr":{"d":"M4 6H20V8H4zM4 11H20V13H4zM4 16H20V18H4z"}}]})(props); };
'use strict'; describe('appLogin', function () { var elm, elmScope, $scope, $compile, $timeout, $httpBackend; beforeEach(module('myApp')); beforeEach(inject(function(_$rootScope_, _$compile_, _$timeout_, _$httpBackend_) { $compile = _$compile_; $timeout = _$timeout_; $httpBackend = _$httpBackend_; $scope = _$rootScope_.$new(); $httpBackend.expectPOST('/api/twitter/requestToken').respond({result: {} }); })); afterEach(function() { $httpBackend.flush(); //twitter requestToken $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); }); /** @param params */ var createElm =function(params) { var html ="<div app-login>"+ "</div>"; if(params.html) { html =params.html; } // elm =angular.element(html); elm =$compile(html)($scope); // $scope.$digest(); $scope.$apply(); //NOTE: required otherwise the alert directive won't be compiled!!!! ... wtf? elmScope =elm.isolateScope(); var elements ={ }; return elements; }; it('should toggle forgot password visibility', function() { var eles =createElm({}); expect(elmScope.forgotPassVisible).toBe(false); elmScope.toggleForgotPass({}); expect(elmScope.forgotPassVisible).toBe(true); elmScope.toggleForgotPass({}); expect(elmScope.forgotPassVisible).toBe(false); }); it('should call forgotPass function', function() { var forgotPassCalled =false; var html ="<div app-login forgot-pass='forgotPass'></div>"; var eles =createElm({html:html}); //should NOT work if forgotPass function is not defined elmScope.formVals ={ email: 'test@email.com' }; $scope.$digest(); //need the form to be valid elmScope.forgotPassDtv({}); $scope.forgotPass =function(params, callback) { expect(params.email).toBe(elmScope.formVals.email); forgotPassCalled =true; callback({}); }; //should NOT be called if invalid formVals (i.e. no email) elmScope.formVals ={}; $scope.$digest(); //need the form to be valid elmScope.forgotPassDtv({}); expect(forgotPassCalled).toBe(false); //now SHOULD be called elmScope.formVals ={ email: 'test@email.com' }; $scope.$digest(); //need the form to be valid elmScope.forgotPassDtv({}); expect(forgotPassCalled).toBe(true); }); it('should call login function', function() { var loginCalled =false; var html ="<div app-login login='login'></div>"; var eles =createElm({html:html}); //should NOT work if login function not defined elmScope.formVals ={ email: 'test@email.com', password: 'password' }; $scope.$digest(); //need the form to be valid elmScope.submitForm({}); $scope.login =function(params, callback) { expect(params.vals.email).toBe(elmScope.formVals.email); expect(params.vals.password).toBe(elmScope.formVals.password); loginCalled =true; callback({}); }; //should NOT be called if invalid formVals (i.e. no email) elmScope.formVals ={}; $scope.$digest(); //need the form to be valid elmScope.submitForm({}); expect(loginCalled).toBe(false); //now SHOULD be called elmScope.formVals ={ email: 'test@email.com', password: 'password' }; $scope.$digest(); //need the form to be valid elmScope.submitForm({}); expect(loginCalled).toBe(true); }); });
/** * impressConsole.js * * Adds a presenter console to impress.js * * MIT Licensed, see license.txt. * * Copyright 2012, 2013, 2015 impress-console contributors (see README.txt) * * version: 1.3-dev * */ (function ( document, window ) { 'use strict'; // create Language object depending on browsers language setting var lang; switch (navigator.language) { case 'de': lang = { 'noNotes' : '<div class="noNotes">Keine Notizen hierzu</div>', 'restart' : 'Neustart', 'clickToOpen' : 'Klicken um Sprecherkonsole zu öffnen', 'prev' : 'zurück', 'next' : 'weiter', 'loading' : 'initalisiere', 'ready' : 'Bereit', 'moving' : 'in Bewegung', 'useAMPM' : false }; break; case 'en': default : lang = { 'noNotes' : '<div class="noNotes">No notes for this step</div>', 'restart' : 'Restart', 'clickToOpen' : 'Click to open speaker console', 'prev' : 'Prev', 'next' : 'Next', 'loading' : 'Loading', 'ready' : 'Ready', 'moving' : 'Moving', 'useAMPM' : false }; break; } // Settings to set iframe in speaker console const preViewDefaultFactor = 0.7; const preViewMinimumFactor = 0.5; const preViewGap = 4; // This is the default template for the speaker console window const consoleTemplate = '<!DOCTYPE html>' + '<html id="impressconsole"><head>' + '<link rel="stylesheet" type="text/css" media="screen" href="{{cssFile}}">' + '</head><body>' + '<div id="console">' + '<div id="views">' + '<iframe id="slideView" scrolling="no"></iframe>' + '<iframe id="preView" scrolling="no"></iframe>' + '<div id="blocker"></div>' + '</div>' + '<div id="notes"></div>' + '</div>' + '<div id="controls"> ' + '<div id="prev"><a href="#" onclick="impress().prev(); return false;" />{{prev}}</a></div>' + '<div id="next"><a href="#" onclick="impress().next(); return false;" />{{next}}</a></div>' + '<div id="clock">--:--</div>' + '<div id="timer" onclick="timerReset()">00m 00s</div>' + '<div id="status">{{loading}}</div>' + '</div>' + '</body></html>'; // Default css location var cssFile = "css/impressConsole.css"; // css for styling iframs on the console var cssFileIframe = "css/iframe.css"; // All console windows, so that you can call impressConsole() repeatedly. var allConsoles = {}; // Zero padding helper function: var zeroPad = function(i) { return (i < 10 ? '0' : '') + i; }; // The console object var impressConsole = window.impressConsole = function (rootId) { rootId = rootId || 'impress'; if (allConsoles[rootId]) { return allConsoles[rootId]; } // root presentation elements var root = document.getElementById( rootId ); var consoleWindow = null; var nextStep = function() { var classes = ""; var nextElement = document.querySelector('.active'); // return to parents as long as there is no next sibling while (!nextElement.nextElementSibling && nextElement.parentNode) { nextElement = nextElement.parentNode; } nextElement = nextElement.nextElementSibling; while (nextElement) { classes = nextElement.attributes['class']; if (classes && classes.value.indexOf('step') !== -1) { consoleWindow.document.getElementById('blocker').innerHTML = lang.next; return nextElement; } if (nextElement.firstElementChild) { // first go into deep nextElement = nextElement.firstElementChild; } else { // go to next sibling or through parents until there is a next sibling while (!nextElement.nextElementSibling && nextElement.parentNode) { nextElement = nextElement.parentNode; } nextElement = nextElement.nextElementSibling; } } // No next element. Pick the first consoleWindow.document.getElementById('blocker').innerHTML = lang.restart; return document.querySelector('.step'); }; // Sync the notes to the step var onStepLeave = function(){ if(consoleWindow) { // Set notes to next steps notes. var newNotes = document.querySelector('.active').querySelector('.notes'); if (newNotes) { newNotes = newNotes.innerHTML; } else { newNotes = lang.noNotes; } consoleWindow.document.getElementById('notes').innerHTML = newNotes; // Set the views var baseURL = document.URL.substring(0, document.URL.search('#/')); var slideSrc = baseURL + '#' + document.querySelector('.active').id; var preSrc = baseURL + '#' + nextStep().id; var slideView = consoleWindow.document.getElementById('slideView'); // Setting them when they are already set causes glithes in Firefox, so we check first: if (slideView.src !== slideSrc) { slideView.src = slideSrc; } var preView = consoleWindow.document.getElementById('preView'); if (preView.src !== preSrc) { preView.src = preSrc; } consoleWindow.document.getElementById('status').innerHTML = '<span class="moving">' + lang.moving + '</span>'; } }; // Sync the previews to the step var onStepEnter = function(){ if(consoleWindow) { // We do everything here again, because if you stopped the previos step to // early, the onstepleave trigger is not called for that step, so // we need this to sync things. var newNotes = document.querySelector('.active').querySelector('.notes'); if (newNotes) { newNotes = newNotes.innerHTML; } else { newNotes = lang.noNotes; } var notes = consoleWindow.document.getElementById('notes'); notes.innerHTML = newNotes; notes.scrollTop = 0; // Set the views var baseURL = document.URL.substring(0, document.URL.search('#/')); var slideSrc = baseURL + '#' + document.querySelector('.active').id; var preSrc = baseURL + '#' + nextStep().id; var slideView = consoleWindow.document.getElementById('slideView'); // Setting them when they are already set causes glithes in Firefox, so we check first: if (slideView.src !== slideSrc) { slideView.src = slideSrc; } var preView = consoleWindow.document.getElementById('preView'); if (preView.src !== preSrc) { preView.src = preSrc; } consoleWindow.document.getElementById('status').innerHTML = '<span class="ready">' + lang.ready + '</span>'; } }; var spaceHandler = function () { var notes = consoleWindow.document.getElementById('notes'); if (notes.scrollTopMax - notes.scrollTop > 20) { notes.scrollTop = notes.scrollTop + notes.clientHeight * 0.8; } else { impress().next(); } }; var timerReset = function () { consoleWindow.timerStart = new Date(); }; // Show a clock var clockTick = function () { var now = new Date(); var hours = now.getHours(); var minutes = now.getMinutes(); var seconds = now.getSeconds(); var ampm = ''; if (lang.useAMPM) { ampm = ( hours < 12 ) ? 'AM' : 'PM'; hours = ( hours > 12 ) ? hours - 12 : hours; hours = ( hours === 0 ) ? 12 : hours; } // Clock var clockStr = zeroPad(hours) + ':' + zeroPad(minutes) + ':' + zeroPad(seconds) + ' ' + ampm; consoleWindow.document.getElementById('clock').firstChild.nodeValue = clockStr; // Timer seconds = Math.floor((now - consoleWindow.timerStart) / 1000); minutes = Math.floor(seconds / 60); seconds = Math.floor(seconds % 60); consoleWindow.document.getElementById('timer').firstChild.nodeValue = zeroPad(minutes) + 'm ' + zeroPad(seconds) + 's'; if (!consoleWindow.initialized) { // Nudge the slide windows after load, or they will scrolled wrong on Firefox. consoleWindow.document.getElementById('slideView').contentWindow.scrollTo(0,0); consoleWindow.document.getElementById('preView').contentWindow.scrollTo(0,0); consoleWindow.initialized = true; } }; var registerKeyEvent = function(keyCodes, handler, window) { if (window === undefined) { window = consoleWindow; } // prevent default keydown action when one of supported key is pressed window.document.addEventListener("keydown", function ( event ) { if ( !event.ctrlKey && !event.altKey && !event.shiftKey && !event.metaKey && keyCodes.indexOf(event.keyCode) !== -1) { event.preventDefault(); } }, false); // trigger impress action on keyup window.document.addEventListener("keyup", function ( event ) { if ( !event.ctrlKey && !event.altKey && !event.shiftKey && !event.metaKey && keyCodes.indexOf(event.keyCode) !== -1) { handler(); event.preventDefault(); } }, false); }; var consoleOnLoad = function() { var slideView = consoleWindow.document.getElementById('slideView'); var preView = consoleWindow.document.getElementById('preView'); // Firefox: slideView.contentDocument.body.classList.add('impress-console'); preView.contentDocument.body.classList.add('impress-console'); slideView.contentDocument.head.insertAdjacentHTML('beforeend', '<link rel="stylesheet" type="text/css" href="' + cssFileIframe + '">'); preView.contentDocument.head.insertAdjacentHTML('beforeend', '<link rel="stylesheet" type="text/css" href="' + cssFileIframe + '">'); // Chrome: slideView.addEventListener('load', function() { slideView.contentDocument.body.classList.add('impress-console'); slideView.contentDocument.head.insertAdjacentHTML('beforeend', '<link rel="stylesheet" type="text/css" href="' + cssFileIframe + '">'); }); preView.addEventListener('load', function() { preView.contentDocument.body.classList.add('impress-console'); preView.contentDocument.head.insertAdjacentHTML('beforeend', '<link rel="stylesheet" type="text/css" href="' + cssFileIframe + '">'); }); }; var open = function() { if(top.isconsoleWindow){ return; } if (consoleWindow && !consoleWindow.closed) { consoleWindow.focus(); } else { consoleWindow = window.open(); // if opening failes this may be because the browser prevents this from // not (or less) interactive JavaScript... if (consoleWindow == null) { // ... so I add a button to klick. // workaround on firefox var message = document.createElement('div'); message.id = 'consoleWindowError'; message.style.position = "fixed"; message.style.left = 0; message.style.top = 0; message.style.right = 0; message.style.bottom = 0; message.style.backgroundColor = 'rgba(255, 255, 255, 0.9)'; message.innerHTML = '<button style="margin: 25vh 25vw;width:50vw;height:50vh;" onclick="var x = document.getElementById(\'consoleWindowError\');x.parentNode.removeChild(x);impressConsole().open();">' + lang.clickToOpen + '</button>'; document.body.appendChild(message); return; } // This sets the window location to the main window location, so css can be loaded: consoleWindow.document.open(); // Write the template: consoleWindow.document.write(consoleTemplate.replace("{{cssFile}}", cssFile).replace(/{{.*?}}/gi, function (x){ return lang[x.substring(2, x.length-2)]; })); consoleWindow.document.title = 'Speaker Console (' + document.title + ')'; consoleWindow.impress = window.impress; // We set this flag so we can detect it later, to prevent infinite popups. consoleWindow.isconsoleWindow = true; // Set the onload function: consoleWindow.onload = consoleOnLoad; // Add clock tick consoleWindow.timerStart = new Date(); consoleWindow.timerReset = timerReset; consoleWindow.clockInterval = setInterval('impressConsole("' + rootId + '").clockTick()', 1000 ); // keyboard navigation handlers // 33: pg up, 37: left, 38: up registerKeyEvent([33, 37, 38], impress().prev); // 34: pg down, 39: right, 40: down registerKeyEvent([34, 39, 40], impress().next); // 32: space registerKeyEvent([32], spaceHandler); // 82: R registerKeyEvent([82], timerReset); // Cleanup consoleWindow.onbeforeunload = function() { // I don't know why onunload doesn't work here. clearInterval(consoleWindow.clockInterval); }; // It will need a little nudge on Firefox, but only after loading: onStepEnter(); consoleWindow.initialized = false; consoleWindow.document.close(); //catch any window resize to pass size on window.onresize = resize; consoleWindow.onresize = resize; return consoleWindow; } }; var resize = function() { var slideView = consoleWindow.document.getElementById('slideView'); var preView = consoleWindow.document.getElementById('preView'); // get ratio of presentation var ratio = window.innerHeight / window.innerWidth; // get size available for views var views = consoleWindow.document.getElementById('views'); // slideView may have a border or some padding: // asuming same border width on both direktions var delta = slideView.offsetWidth - slideView.clientWidth; // set views var slideViewWidth = (views.clientWidth - delta); var slideViewHeight = Math.floor(slideViewWidth * ratio); var preViewTop = slideViewHeight + preViewGap; var preViewWidth = Math.floor(slideViewWidth * preViewDefaultFactor); var preViewHeight = Math.floor(slideViewHeight * preViewDefaultFactor); // shrink preview to fit into space available if (views.clientHeight - delta < preViewTop + preViewHeight) { preViewHeight = views.clientHeight - delta - preViewTop; preViewWidth = Math.floor(preViewHeight / ratio); } // if preview is not high enough forget ratios! if (preViewWidth <= Math.floor(slideViewWidth * preViewMinimumFactor)) { slideViewWidth = (views.clientWidth - delta); slideViewHeight = Math.floor((views.clientHeight - delta - preViewGap) / (1 + preViewMinimumFactor)); preViewTop = slideViewHeight + preViewGap; preViewWidth = Math.floor(slideViewWidth * preViewMinimumFactor); preViewHeight = views.clientHeight - delta - preViewTop; } // set the calculated into styles slideView.style.width = slideViewWidth + "px"; slideView.style.height = slideViewHeight + "px"; preView.style.top = preViewTop + "px"; preView.style.width = preViewWidth + "px"; preView.style.height = preViewHeight + "px"; } var init = function(cssConsole, cssIframe) { if (cssConsole !== undefined) { cssFile = cssConsole; } if (cssIframe !== undefined) { cssFileIframe = cssIframe; } // Register the event root.addEventListener('impress:stepleave', onStepLeave); root.addEventListener('impress:stepenter', onStepEnter); //When the window closes, clean up after ourselves. window.onunload = function(){ if (consoleWindow && !consoleWindow.closed) { consoleWindow.close(); } }; //Open speaker console when they press 'p' registerKeyEvent([80], open, window); }; // Return the object allConsoles[rootId] = {init: init, open: open, clockTick: clockTick, registerKeyEvent: registerKeyEvent}; return allConsoles[rootId]; }; })(document, window);
var assert = require("assert") var dirname = require("path").dirname var resolve = require("path").resolve var rimraf = require("rimraf") var lstat = require("graceful-fs").lstat var readdir = require("graceful-fs").readdir var rmdir = require("graceful-fs").rmdir var unlink = require("graceful-fs").unlink module.exports = vacuum function vacuum(leaf, options, cb) { assert(typeof leaf === "string", "must pass in path to remove") assert(typeof cb === "function", "must pass in callback") if (!options) options = {} assert(typeof options === "object", "options must be an object") var log = options.log ? options.log : function () {} var base = options.base if (base && resolve(leaf).indexOf(resolve(base)) !== 0) { return cb(new Error(resolve(leaf) + " is not a child of " + resolve(base))) } lstat(leaf, function (error, stat) { if (error) { if (error.code === "ENOENT") return cb(null) log(error.stack) return cb(error) } if (!(stat && (stat.isDirectory() || stat.isSymbolicLink() || stat.isFile()))) { log(leaf, "is not a directory, file, or link") return cb(new Error(leaf + " is not a directory, file, or link")) } if (options.purge) { log("purging", leaf) rimraf(leaf, function (error) { if (error) return cb(error) next(dirname(leaf)) }) } else if (!stat.isDirectory()) { log("removing", leaf) unlink(leaf, function (error) { if (error) return cb(error) next(dirname(leaf)) }) } else { next(leaf) } }) function next(branch) { // either we've reached the base or we've reached the root if ((base && resolve(branch) === resolve(base)) || branch === dirname(branch)) { log("finished vacuuming up to", branch) return cb(null) } readdir(branch, function (error, files) { if (error) { if (error.code === "ENOENT") return cb(null) log("unable to check directory", branch, "due to", error.message) return cb(error) } if (files.length > 0) { log("quitting because other entries in", branch) return cb(null) } log("removing", branch) lstat(branch, function (error, stat) { if (error) { if (error.code === "ENOENT") return cb(null) log("unable to lstat", branch, "due to", error.message) return cb(error) } var remove = stat.isDirectory() ? rmdir : unlink remove(branch, function (error) { if (error) { if (error.code === "ENOENT") return cb(null) log("unable to remove", branch, "due to", error.message) return cb(error) } next(dirname(branch)) }) }) }) } }
import { createSelector } from 'reselect'; import { path, propOr, prop, } from 'ramda'; const localState = prop('usersData'); export const getUserLoadingStatus = id => createSelector( getUserById(id), propOr(true, 'loading'), ); export const getUserById = id => createSelector( localState, prop(id), ); export const getUserId = id => createSelector( getUserById(id), path(['data', 'id']), ); export const getUserName = id => createSelector( getUserById(id), path(['data', 'name']), ); export const getUserGender = id => createSelector( getUserById(id), path(['data', 'gender']), ); export const getUserBirthDate = id => createSelector( getUserById(id), path(['data', 'birthDate']), );
#!/usr/bin/env node /** * @license r.js 2.2.0 Copyright jQuery Foundation and other contributors. * Released under MIT license, http://github.com/requirejs/r.js/LICENSE */ /* * This is a bootstrap script to allow running RequireJS in the command line * in either a Java/Rhino or Node environment. It is modified by the top-level * dist.js file to inject other files to completely enable this file. It is * the shell of the r.js file. */ /*jslint evil: true, nomen: true, sloppy: true */ /*global readFile: true, process: false, Packages: false, print: false, console: false, java: false, module: false, requirejsVars, navigator, document, importScripts, self, location, Components, FileUtils */ var requirejs, require, define, xpcUtil; (function (console, args, readFileFunc) { var fileName, env, fs, vm, path, exec, rhinoContext, dir, nodeRequire, nodeDefine, exists, reqMain, loadedOptimizedLib, existsForNode, Cc, Ci, version = '2.2.0', jsSuffixRegExp = /\.js$/, commandOption = '', useLibLoaded = {}, //Used by jslib/rhino/args.js rhinoArgs = args, //Used by jslib/xpconnect/args.js xpconnectArgs = args, readFile = typeof readFileFunc !== 'undefined' ? readFileFunc : null; function showHelp() { console.log('See https://github.com/requirejs/r.js for usage.'); } if (typeof process !== 'undefined' && process.versions && !!process.versions.node) { env = 'node'; //Get the fs module via Node's require before it //gets replaced. Used in require/node.js fs = require('fs'); vm = require('vm'); path = require('path'); //In Node 0.7+ existsSync is on fs. existsForNode = fs.existsSync || path.existsSync; nodeRequire = require; nodeDefine = define; reqMain = require.main; //Temporarily hide require and define to allow require.js to define //them. require = undefined; define = undefined; readFile = function (path) { return fs.readFileSync(path, 'utf8'); }; exec = function (string, name) { return vm.runInThisContext(this.requirejsVars.require.makeNodeWrapper(string), name ? fs.realpathSync(name) : ''); }; exists = function (fileName) { return existsForNode(fileName); }; fileName = process.argv[2]; if (fileName && fileName.indexOf('-') === 0) { commandOption = fileName.substring(1); fileName = process.argv[3]; } } else if (typeof Packages !== 'undefined') { env = 'rhino'; fileName = args[0]; if (fileName && fileName.indexOf('-') === 0) { commandOption = fileName.substring(1); fileName = args[1]; } //Exec/readFile differs between Rhino and Nashorn. Rhino has an //importPackage where Nashorn does not, so branch on that. This is a //coarser check -- detecting readFile existence might also be enough for //this spot. However, sticking with importPackage to keep it the same //as other Rhino/Nashorn detection branches. if (typeof importPackage !== 'undefined') { rhinoContext = Packages.org.mozilla.javascript.ContextFactory.getGlobal().enterContext(); exec = function (string, name) { return rhinoContext.evaluateString(this, string, name, 0, null); }; } else { exec = function (string, name) { load({ script: string, name: name}); }; readFile = readFully; } exists = function (fileName) { return (new java.io.File(fileName)).exists(); }; //Define a console.log for easier logging. Don't //get fancy though. if (typeof console === 'undefined') { console = { log: function () { print.apply(undefined, arguments); } }; } } else if ((typeof navigator !== 'undefined' && typeof document !== 'undefined') || (typeof importScripts !== 'undefined' && typeof self !== 'undefined')) { env = 'browser'; readFile = function (path) { return fs.readFileSync(path, 'utf8'); }; exec = function (string) { return eval(string); }; exists = function () { console.log('x.js exists not applicable in browser env'); return false; }; } else if (typeof Components !== 'undefined' && Components.classes && Components.interfaces) { env = 'xpconnect'; Components.utils['import']('resource://gre/modules/FileUtils.jsm'); Cc = Components.classes; Ci = Components.interfaces; fileName = args[0]; if (fileName && fileName.indexOf('-') === 0) { commandOption = fileName.substring(1); fileName = args[1]; } xpcUtil = { isWindows: ('@mozilla.org/windows-registry-key;1' in Cc), cwd: function () { return FileUtils.getFile("CurWorkD", []).path; }, //Remove . and .. from paths, normalize on front slashes normalize: function (path) { //There has to be an easier way to do this. var i, part, ary, firstChar = path.charAt(0); if (firstChar !== '/' && firstChar !== '\\' && path.indexOf(':') === -1) { //A relative path. Use the current working directory. path = xpcUtil.cwd() + '/' + path; } ary = path.replace(/\\/g, '/').split('/'); for (i = 0; i < ary.length; i += 1) { part = ary[i]; if (part === '.') { ary.splice(i, 1); i -= 1; } else if (part === '..') { ary.splice(i - 1, 2); i -= 2; } } return ary.join('/'); }, xpfile: function (path) { var fullPath; try { fullPath = xpcUtil.normalize(path); if (xpcUtil.isWindows) { fullPath = fullPath.replace(/\//g, '\\'); } return new FileUtils.File(fullPath); } catch (e) { throw new Error((fullPath || path) + ' failed: ' + e); } }, readFile: function (/*String*/path, /*String?*/encoding) { //A file read function that can deal with BOMs encoding = encoding || "utf-8"; var inStream, convertStream, readData = {}, fileObj = xpcUtil.xpfile(path); //XPCOM, you so crazy try { inStream = Cc['@mozilla.org/network/file-input-stream;1'] .createInstance(Ci.nsIFileInputStream); inStream.init(fileObj, 1, 0, false); convertStream = Cc['@mozilla.org/intl/converter-input-stream;1'] .createInstance(Ci.nsIConverterInputStream); convertStream.init(inStream, encoding, inStream.available(), Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER); convertStream.readString(inStream.available(), readData); return readData.value; } catch (e) { throw new Error((fileObj && fileObj.path || '') + ': ' + e); } finally { if (convertStream) { convertStream.close(); } if (inStream) { inStream.close(); } } } }; readFile = xpcUtil.readFile; exec = function (string) { return eval(string); }; exists = function (fileName) { return xpcUtil.xpfile(fileName).exists(); }; //Define a console.log for easier logging. Don't //get fancy though. if (typeof console === 'undefined') { console = { log: function () { print.apply(undefined, arguments); } }; } } /** vim: et:ts=4:sw=4:sts=4 * @license RequireJS 2.2.0 Copyright jQuery Foundation and other contributors. * Released under MIT license, http://github.com/requirejs/requirejs/LICENSE */ //Not using strict: uneven strict support in browsers, #392, and causes //problems with requirejs.exec()/transpiler plugins that may not be strict. /*jslint regexp: true, nomen: true, sloppy: true */ /*global window, navigator, document, importScripts, setTimeout, opera */ (function (global) { var req, s, head, baseElement, dataMain, src, interactiveScript, currentlyAddingScript, mainScript, subPath, version = '2.2.0', commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg, cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g, jsSuffixRegExp = /\.js$/, currDirRegExp = /^\.\//, op = Object.prototype, ostring = op.toString, hasOwn = op.hasOwnProperty, isBrowser = !!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document), isWebWorker = !isBrowser && typeof importScripts !== 'undefined', //PS3 indicates loaded and complete, but need to wait for complete //specifically. Sequence is 'loading', 'loaded', execution, // then 'complete'. The UA check is unfortunate, but not sure how //to feature test w/o causing perf issues. readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ? /^complete$/ : /^(complete|loaded)$/, defContextName = '_', //Oh the tragedy, detecting opera. See the usage of isOpera for reason. isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]', contexts = {}, cfg = {}, globalDefQueue = [], useInteractive = false; //Could match something like ')//comment', do not lose the prefix to comment. function commentReplace(match, multi, multiText, singlePrefix) { return singlePrefix || ''; } function isFunction(it) { return ostring.call(it) === '[object Function]'; } function isArray(it) { return ostring.call(it) === '[object Array]'; } /** * Helper function for iterating over an array. If the func returns * a true value, it will break out of the loop. */ function each(ary, func) { if (ary) { var i; for (i = 0; i < ary.length; i += 1) { if (ary[i] && func(ary[i], i, ary)) { break; } } } } /** * Helper function for iterating over an array backwards. If the func * returns a true value, it will break out of the loop. */ function eachReverse(ary, func) { if (ary) { var i; for (i = ary.length - 1; i > -1; i -= 1) { if (ary[i] && func(ary[i], i, ary)) { break; } } } } function hasProp(obj, prop) { return hasOwn.call(obj, prop); } function getOwn(obj, prop) { return hasProp(obj, prop) && obj[prop]; } /** * Cycles over properties in an object and calls a function for each * property value. If the function returns a truthy value, then the * iteration is stopped. */ function eachProp(obj, func) { var prop; for (prop in obj) { if (hasProp(obj, prop)) { if (func(obj[prop], prop)) { break; } } } } /** * Simple function to mix in properties from source into target, * but only if target does not already have a property of the same name. */ function mixin(target, source, force, deepStringMixin) { if (source) { eachProp(source, function (value, prop) { if (force || !hasProp(target, prop)) { if (deepStringMixin && typeof value === 'object' && value && !isArray(value) && !isFunction(value) && !(value instanceof RegExp)) { if (!target[prop]) { target[prop] = {}; } mixin(target[prop], value, force, deepStringMixin); } else { target[prop] = value; } } }); } return target; } //Similar to Function.prototype.bind, but the 'this' object is specified //first, since it is easier to read/figure out what 'this' will be. function bind(obj, fn) { return function () { return fn.apply(obj, arguments); }; } function scripts() { return document.getElementsByTagName('script'); } function defaultOnError(err) { throw err; } //Allow getting a global that is expressed in //dot notation, like 'a.b.c'. function getGlobal(value) { if (!value) { return value; } var g = global; each(value.split('.'), function (part) { g = g[part]; }); return g; } /** * Constructs an error with a pointer to an URL with more information. * @param {String} id the error ID that maps to an ID on a web page. * @param {String} message human readable error. * @param {Error} [err] the original error, if there is one. * * @returns {Error} */ function makeError(id, msg, err, requireModules) { var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id); e.requireType = id; e.requireModules = requireModules; if (err) { e.originalError = err; } return e; } if (typeof define !== 'undefined') { //If a define is already in play via another AMD loader, //do not overwrite. return; } if (typeof requirejs !== 'undefined') { if (isFunction(requirejs)) { //Do not overwrite an existing requirejs instance. return; } cfg = requirejs; requirejs = undefined; } //Allow for a require config object if (typeof require !== 'undefined' && !isFunction(require)) { //assume it is a config object. cfg = require; require = undefined; } function newContext(contextName) { var inCheckLoaded, Module, context, handlers, checkLoadedTimeoutId, config = { //Defaults. Do not set a default for map //config to speed up normalize(), which //will run faster if there is no default. waitSeconds: 7, baseUrl: './', paths: {}, bundles: {}, pkgs: {}, shim: {}, config: {} }, registry = {}, //registry of just enabled modules, to speed //cycle breaking code when lots of modules //are registered, but not activated. enabledRegistry = {}, undefEvents = {}, defQueue = [], defined = {}, urlFetched = {}, bundlesMap = {}, requireCounter = 1, unnormalizedCounter = 1; /** * Trims the . and .. from an array of path segments. * It will keep a leading path segment if a .. will become * the first path segment, to help with module name lookups, * which act like paths, but can be remapped. But the end result, * all paths that use this function should look normalized. * NOTE: this method MODIFIES the input array. * @param {Array} ary the array of path segments. */ function trimDots(ary) { var i, part; for (i = 0; i < ary.length; i++) { part = ary[i]; if (part === '.') { ary.splice(i, 1); i -= 1; } else if (part === '..') { // If at the start, or previous value is still .., // keep them so that when converted to a path it may // still work when converted to a path, even though // as an ID it is less than ideal. In larger point // releases, may be better to just kick out an error. if (i === 0 || (i === 1 && ary[2] === '..') || ary[i - 1] === '..') { continue; } else if (i > 0) { ary.splice(i - 1, 2); i -= 2; } } } } /** * Given a relative module name, like ./something, normalize it to * a real name that can be mapped to a path. * @param {String} name the relative name * @param {String} baseName a real name that the name arg is relative * to. * @param {Boolean} applyMap apply the map config to the value. Should * only be done if this normalization is for a dependency ID. * @returns {String} normalized name */ function normalize(name, baseName, applyMap) { var pkgMain, mapValue, nameParts, i, j, nameSegment, lastIndex, foundMap, foundI, foundStarMap, starI, normalizedBaseParts, baseParts = (baseName && baseName.split('/')), map = config.map, starMap = map && map['*']; //Adjust any relative paths. if (name) { name = name.split('/'); lastIndex = name.length - 1; // If wanting node ID compatibility, strip .js from end // of IDs. Have to do this here, and not in nameToUrl // because node allows either .js or non .js to map // to same file. if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) { name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, ''); } // Starts with a '.' so need the baseName if (name[0].charAt(0) === '.' && baseParts) { //Convert baseName to array, and lop off the last part, //so that . matches that 'directory' and not name of the baseName's //module. For instance, baseName of 'one/two/three', maps to //'one/two/three.js', but we want the directory, 'one/two' for //this normalization. normalizedBaseParts = baseParts.slice(0, baseParts.length - 1); name = normalizedBaseParts.concat(name); } trimDots(name); name = name.join('/'); } //Apply map config if available. if (applyMap && map && (baseParts || starMap)) { nameParts = name.split('/'); outerLoop: for (i = nameParts.length; i > 0; i -= 1) { nameSegment = nameParts.slice(0, i).join('/'); if (baseParts) { //Find the longest baseName segment match in the config. //So, do joins on the biggest to smallest lengths of baseParts. for (j = baseParts.length; j > 0; j -= 1) { mapValue = getOwn(map, baseParts.slice(0, j).join('/')); //baseName segment has config, find if it has one for //this name. if (mapValue) { mapValue = getOwn(mapValue, nameSegment); if (mapValue) { //Match, update name to the new value. foundMap = mapValue; foundI = i; break outerLoop; } } } } //Check for a star map match, but just hold on to it, //if there is a shorter segment match later in a matching //config, then favor over this star map. if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) { foundStarMap = getOwn(starMap, nameSegment); starI = i; } } if (!foundMap && foundStarMap) { foundMap = foundStarMap; foundI = starI; } if (foundMap) { nameParts.splice(0, foundI, foundMap); name = nameParts.join('/'); } } // If the name points to a package's name, use // the package main instead. pkgMain = getOwn(config.pkgs, name); return pkgMain ? pkgMain : name; } function removeScript(name) { if (isBrowser) { each(scripts(), function (scriptNode) { if (scriptNode.getAttribute('data-requiremodule') === name && scriptNode.getAttribute('data-requirecontext') === context.contextName) { scriptNode.parentNode.removeChild(scriptNode); return true; } }); } } function hasPathFallback(id) { var pathConfig = getOwn(config.paths, id); if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) { //Pop off the first array value, since it failed, and //retry pathConfig.shift(); context.require.undef(id); //Custom require that does not do map translation, since //ID is "absolute", already mapped/resolved. context.makeRequire(null, { skipMap: true })([id]); return true; } } //Turns a plugin!resource to [plugin, resource] //with the plugin being undefined if the name //did not have a plugin prefix. function splitPrefix(name) { var prefix, index = name ? name.indexOf('!') : -1; if (index > -1) { prefix = name.substring(0, index); name = name.substring(index + 1, name.length); } return [prefix, name]; } /** * Creates a module mapping that includes plugin prefix, module * name, and path. If parentModuleMap is provided it will * also normalize the name via require.normalize() * * @param {String} name the module name * @param {String} [parentModuleMap] parent module map * for the module name, used to resolve relative names. * @param {Boolean} isNormalized: is the ID already normalized. * This is true if this call is done for a define() module ID. * @param {Boolean} applyMap: apply the map config to the ID. * Should only be true if this map is for a dependency. * * @returns {Object} */ function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) { var url, pluginModule, suffix, nameParts, prefix = null, parentName = parentModuleMap ? parentModuleMap.name : null, originalName = name, isDefine = true, normalizedName = ''; //If no name, then it means it is a require call, generate an //internal name. if (!name) { isDefine = false; name = '_@r' + (requireCounter += 1); } nameParts = splitPrefix(name); prefix = nameParts[0]; name = nameParts[1]; if (prefix) { prefix = normalize(prefix, parentName, applyMap); pluginModule = getOwn(defined, prefix); } //Account for relative paths if there is a base name. if (name) { if (prefix) { if (pluginModule && pluginModule.normalize) { //Plugin is loaded, use its normalize method. normalizedName = pluginModule.normalize(name, function (name) { return normalize(name, parentName, applyMap); }); } else { // If nested plugin references, then do not try to // normalize, as it will not normalize correctly. This // places a restriction on resourceIds, and the longer // term solution is not to normalize until plugins are // loaded and all normalizations to allow for async // loading of a loader plugin. But for now, fixes the // common uses. Details in #1131 normalizedName = name.indexOf('!') === -1 ? normalize(name, parentName, applyMap) : name; } } else { //A regular module. normalizedName = normalize(name, parentName, applyMap); //Normalized name may be a plugin ID due to map config //application in normalize. The map config values must //already be normalized, so do not need to redo that part. nameParts = splitPrefix(normalizedName); prefix = nameParts[0]; normalizedName = nameParts[1]; isNormalized = true; url = context.nameToUrl(normalizedName); } } //If the id is a plugin id that cannot be determined if it needs //normalization, stamp it with a unique ID so two matching relative //ids that may conflict can be separate. suffix = prefix && !pluginModule && !isNormalized ? '_unnormalized' + (unnormalizedCounter += 1) : ''; return { prefix: prefix, name: normalizedName, parentMap: parentModuleMap, unnormalized: !!suffix, url: url, originalName: originalName, isDefine: isDefine, id: (prefix ? prefix + '!' + normalizedName : normalizedName) + suffix }; } function getModule(depMap) { var id = depMap.id, mod = getOwn(registry, id); if (!mod) { mod = registry[id] = new context.Module(depMap); } return mod; } function on(depMap, name, fn) { var id = depMap.id, mod = getOwn(registry, id); if (hasProp(defined, id) && (!mod || mod.defineEmitComplete)) { if (name === 'defined') { fn(defined[id]); } } else { mod = getModule(depMap); if (mod.error && name === 'error') { fn(mod.error); } else { mod.on(name, fn); } } } function onError(err, errback) { var ids = err.requireModules, notified = false; if (errback) { errback(err); } else { each(ids, function (id) { var mod = getOwn(registry, id); if (mod) { //Set error on module, so it skips timeout checks. mod.error = err; if (mod.events.error) { notified = true; mod.emit('error', err); } } }); if (!notified) { req.onError(err); } } } /** * Internal method to transfer globalQueue items to this context's * defQueue. */ function takeGlobalQueue() { //Push all the globalDefQueue items into the context's defQueue if (globalDefQueue.length) { each(globalDefQueue, function(queueItem) { var id = queueItem[0]; if (typeof id === 'string') { context.defQueueMap[id] = true; } defQueue.push(queueItem); }); globalDefQueue = []; } } handlers = { 'require': function (mod) { if (mod.require) { return mod.require; } else { return (mod.require = context.makeRequire(mod.map)); } }, 'exports': function (mod) { mod.usingExports = true; if (mod.map.isDefine) { if (mod.exports) { return (defined[mod.map.id] = mod.exports); } else { return (mod.exports = defined[mod.map.id] = {}); } } }, 'module': function (mod) { if (mod.module) { return mod.module; } else { return (mod.module = { id: mod.map.id, uri: mod.map.url, config: function () { return getOwn(config.config, mod.map.id) || {}; }, exports: mod.exports || (mod.exports = {}) }); } } }; function cleanRegistry(id) { //Clean up machinery used for waiting modules. delete registry[id]; delete enabledRegistry[id]; } function breakCycle(mod, traced, processed) { var id = mod.map.id; if (mod.error) { mod.emit('error', mod.error); } else { traced[id] = true; each(mod.depMaps, function (depMap, i) { var depId = depMap.id, dep = getOwn(registry, depId); //Only force things that have not completed //being defined, so still in the registry, //and only if it has not been matched up //in the module already. if (dep && !mod.depMatched[i] && !processed[depId]) { if (getOwn(traced, depId)) { mod.defineDep(i, defined[depId]); mod.check(); //pass false? } else { breakCycle(dep, traced, processed); } } }); processed[id] = true; } } function checkLoaded() { var err, usingPathFallback, waitInterval = config.waitSeconds * 1000, //It is possible to disable the wait interval by using waitSeconds of 0. expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(), noLoads = [], reqCalls = [], stillLoading = false, needCycleCheck = true; //Do not bother if this call was a result of a cycle break. if (inCheckLoaded) { return; } inCheckLoaded = true; //Figure out the state of all the modules. eachProp(enabledRegistry, function (mod) { var map = mod.map, modId = map.id; //Skip things that are not enabled or in error state. if (!mod.enabled) { return; } if (!map.isDefine) { reqCalls.push(mod); } if (!mod.error) { //If the module should be executed, and it has not //been inited and time is up, remember it. if (!mod.inited && expired) { if (hasPathFallback(modId)) { usingPathFallback = true; stillLoading = true; } else { noLoads.push(modId); removeScript(modId); } } else if (!mod.inited && mod.fetched && map.isDefine) { stillLoading = true; if (!map.prefix) { //No reason to keep looking for unfinished //loading. If the only stillLoading is a //plugin resource though, keep going, //because it may be that a plugin resource //is waiting on a non-plugin cycle. return (needCycleCheck = false); } } } }); if (expired && noLoads.length) { //If wait time expired, throw error of unloaded modules. err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads); err.contextName = context.contextName; return onError(err); } //Not expired, check for a cycle. if (needCycleCheck) { each(reqCalls, function (mod) { breakCycle(mod, {}, {}); }); } //If still waiting on loads, and the waiting load is something //other than a plugin resource, or there are still outstanding //scripts, then just try back later. if ((!expired || usingPathFallback) && stillLoading) { //Something is still waiting to load. Wait for it, but only //if a timeout is not already in effect. if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) { checkLoadedTimeoutId = setTimeout(function () { checkLoadedTimeoutId = 0; checkLoaded(); }, 50); } } inCheckLoaded = false; } Module = function (map) { this.events = getOwn(undefEvents, map.id) || {}; this.map = map; this.shim = getOwn(config.shim, map.id); this.depExports = []; this.depMaps = []; this.depMatched = []; this.pluginMaps = {}; this.depCount = 0; /* this.exports this.factory this.depMaps = [], this.enabled, this.fetched */ }; Module.prototype = { init: function (depMaps, factory, errback, options) { options = options || {}; //Do not do more inits if already done. Can happen if there //are multiple define calls for the same module. That is not //a normal, common case, but it is also not unexpected. if (this.inited) { return; } this.factory = factory; if (errback) { //Register for errors on this module. this.on('error', errback); } else if (this.events.error) { //If no errback already, but there are error listeners //on this module, set up an errback to pass to the deps. errback = bind(this, function (err) { this.emit('error', err); }); } //Do a copy of the dependency array, so that //source inputs are not modified. For example //"shim" deps are passed in here directly, and //doing a direct modification of the depMaps array //would affect that config. this.depMaps = depMaps && depMaps.slice(0); this.errback = errback; //Indicate this module has be initialized this.inited = true; this.ignore = options.ignore; //Could have option to init this module in enabled mode, //or could have been previously marked as enabled. However, //the dependencies are not known until init is called. So //if enabled previously, now trigger dependencies as enabled. if (options.enabled || this.enabled) { //Enable this module and dependencies. //Will call this.check() this.enable(); } else { this.check(); } }, defineDep: function (i, depExports) { //Because of cycles, defined callback for a given //export can be called more than once. if (!this.depMatched[i]) { this.depMatched[i] = true; this.depCount -= 1; this.depExports[i] = depExports; } }, fetch: function () { if (this.fetched) { return; } this.fetched = true; context.startTime = (new Date()).getTime(); var map = this.map; //If the Admin is for a plugin managed resource, //ask the plugin to load it now. if (this.shim) { context.makeRequire(this.map, { enableBuildCallback: true })(this.shim.deps || [], bind(this, function () { return map.prefix ? this.callPlugin() : this.load(); })); } else { //Regular dependency. return map.prefix ? this.callPlugin() : this.load(); } }, load: function () { var url = this.map.url; //Regular dependency. if (!urlFetched[url]) { urlFetched[url] = true; context.load(this.map.id, url); } }, /** * Checks if the module is ready to define itself, and if so, * define it. */ check: function () { if (!this.enabled || this.enabling) { return; } var err, cjsModule, id = this.map.id, depExports = this.depExports, exports = this.exports, factory = this.factory; if (!this.inited) { // Only fetch if not already in the defQueue. if (!hasProp(context.defQueueMap, id)) { this.fetch(); } } else if (this.error) { this.emit('error', this.error); } else if (!this.defining) { //The factory could trigger another require call //that would result in checking this module to //define itself again. If already in the process //of doing that, skip this work. this.defining = true; if (this.depCount < 1 && !this.defined) { if (isFunction(factory)) { //If there is an error listener, favor passing //to that instead of throwing an error. However, //only do it for define()'d modules. require //errbacks should not be called for failures in //their callbacks (#699). However if a global //onError is set, use that. if ((this.events.error && this.map.isDefine) || req.onError !== defaultOnError) { try { exports = context.execCb(id, factory, depExports, exports); } catch (e) { err = e; } } else { exports = context.execCb(id, factory, depExports, exports); } // Favor return value over exports. If node/cjs in play, // then will not have a return value anyway. Favor // module.exports assignment over exports object. if (this.map.isDefine && exports === undefined) { cjsModule = this.module; if (cjsModule) { exports = cjsModule.exports; } else if (this.usingExports) { //exports already set the defined value. exports = this.exports; } } if (err) { err.requireMap = this.map; err.requireModules = this.map.isDefine ? [this.map.id] : null; err.requireType = this.map.isDefine ? 'define' : 'require'; return onError((this.error = err)); } } else { //Just a literal value exports = factory; } this.exports = exports; if (this.map.isDefine && !this.ignore) { defined[id] = exports; if (req.onResourceLoad) { var resLoadMaps = []; each(this.depMaps, function (depMap) { resLoadMaps.push(depMap.normalizedMap || depMap); }); req.onResourceLoad(context, this.map, resLoadMaps); } } //Clean up cleanRegistry(id); this.defined = true; } //Finished the define stage. Allow calling check again //to allow define notifications below in the case of a //cycle. this.defining = false; if (this.defined && !this.defineEmitted) { this.defineEmitted = true; this.emit('defined', this.exports); this.defineEmitComplete = true; } } }, callPlugin: function () { var map = this.map, id = map.id, //Map already normalized the prefix. pluginMap = makeModuleMap(map.prefix); //Mark this as a dependency for this plugin, so it //can be traced for cycles. this.depMaps.push(pluginMap); on(pluginMap, 'defined', bind(this, function (plugin) { var load, normalizedMap, normalizedMod, bundleId = getOwn(bundlesMap, this.map.id), name = this.map.name, parentName = this.map.parentMap ? this.map.parentMap.name : null, localRequire = context.makeRequire(map.parentMap, { enableBuildCallback: true }); //If current map is not normalized, wait for that //normalized name to load instead of continuing. if (this.map.unnormalized) { //Normalize the ID if the plugin allows it. if (plugin.normalize) { name = plugin.normalize(name, function (name) { return normalize(name, parentName, true); }) || ''; } //prefix and name should already be normalized, no need //for applying map config again either. normalizedMap = makeModuleMap(map.prefix + '!' + name, this.map.parentMap); on(normalizedMap, 'defined', bind(this, function (value) { this.map.normalizedMap = normalizedMap; this.init([], function () { return value; }, null, { enabled: true, ignore: true }); })); normalizedMod = getOwn(registry, normalizedMap.id); if (normalizedMod) { //Mark this as a dependency for this plugin, so it //can be traced for cycles. this.depMaps.push(normalizedMap); if (this.events.error) { normalizedMod.on('error', bind(this, function (err) { this.emit('error', err); })); } normalizedMod.enable(); } return; } //If a paths config, then just load that file instead to //resolve the plugin, as it is built into that paths layer. if (bundleId) { this.map.url = context.nameToUrl(bundleId); this.load(); return; } load = bind(this, function (value) { this.init([], function () { return value; }, null, { enabled: true }); }); load.error = bind(this, function (err) { this.inited = true; this.error = err; err.requireModules = [id]; //Remove temp unnormalized modules for this module, //since they will never be resolved otherwise now. eachProp(registry, function (mod) { if (mod.map.id.indexOf(id + '_unnormalized') === 0) { cleanRegistry(mod.map.id); } }); onError(err); }); //Allow plugins to load other code without having to know the //context or how to 'complete' the load. load.fromText = bind(this, function (text, textAlt) { /*jslint evil: true */ var moduleName = map.name, moduleMap = makeModuleMap(moduleName), hasInteractive = useInteractive; //As of 2.1.0, support just passing the text, to reinforce //fromText only being called once per resource. Still //support old style of passing moduleName but discard //that moduleName in favor of the internal ref. if (textAlt) { text = textAlt; } //Turn off interactive script matching for IE for any define //calls in the text, then turn it back on at the end. if (hasInteractive) { useInteractive = false; } //Prime the system by creating a module instance for //it. getModule(moduleMap); //Transfer any config to this other module. if (hasProp(config.config, id)) { config.config[moduleName] = config.config[id]; } try { req.exec(text); } catch (e) { return onError(makeError('fromtexteval', 'fromText eval for ' + id + ' failed: ' + e, e, [id])); } if (hasInteractive) { useInteractive = true; } //Mark this as a dependency for the plugin //resource this.depMaps.push(moduleMap); //Support anonymous modules. context.completeLoad(moduleName); //Bind the value of that module to the value for this //resource ID. localRequire([moduleName], load); }); //Use parentName here since the plugin's name is not reliable, //could be some weird string with no path that actually wants to //reference the parentName's path. plugin.load(map.name, localRequire, load, config); })); context.enable(pluginMap, this); this.pluginMaps[pluginMap.id] = pluginMap; }, enable: function () { enabledRegistry[this.map.id] = this; this.enabled = true; //Set flag mentioning that the module is enabling, //so that immediate calls to the defined callbacks //for dependencies do not trigger inadvertent load //with the depCount still being zero. this.enabling = true; //Enable each dependency each(this.depMaps, bind(this, function (depMap, i) { var id, mod, handler; if (typeof depMap === 'string') { //Dependency needs to be converted to a depMap //and wired up to this module. depMap = makeModuleMap(depMap, (this.map.isDefine ? this.map : this.map.parentMap), false, !this.skipMap); this.depMaps[i] = depMap; handler = getOwn(handlers, depMap.id); if (handler) { this.depExports[i] = handler(this); return; } this.depCount += 1; on(depMap, 'defined', bind(this, function (depExports) { if (this.undefed) { return; } this.defineDep(i, depExports); this.check(); })); if (this.errback) { on(depMap, 'error', bind(this, this.errback)); } else if (this.events.error) { // No direct errback on this module, but something // else is listening for errors, so be sure to // propagate the error correctly. on(depMap, 'error', bind(this, function(err) { this.emit('error', err); })); } } id = depMap.id; mod = registry[id]; //Skip special modules like 'require', 'exports', 'module' //Also, don't call enable if it is already enabled, //important in circular dependency cases. if (!hasProp(handlers, id) && mod && !mod.enabled) { context.enable(depMap, this); } })); //Enable each plugin that is used in //a dependency eachProp(this.pluginMaps, bind(this, function (pluginMap) { var mod = getOwn(registry, pluginMap.id); if (mod && !mod.enabled) { context.enable(pluginMap, this); } })); this.enabling = false; this.check(); }, on: function (name, cb) { var cbs = this.events[name]; if (!cbs) { cbs = this.events[name] = []; } cbs.push(cb); }, emit: function (name, evt) { each(this.events[name], function (cb) { cb(evt); }); if (name === 'error') { //Now that the error handler was triggered, remove //the listeners, since this broken Module instance //can stay around for a while in the registry. delete this.events[name]; } } }; function callGetModule(args) { //Skip modules already defined. if (!hasProp(defined, args[0])) { getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]); } } function removeListener(node, func, name, ieName) { //Favor detachEvent because of IE9 //issue, see attachEvent/addEventListener comment elsewhere //in this file. if (node.detachEvent && !isOpera) { //Probably IE. If not it will throw an error, which will be //useful to know. if (ieName) { node.detachEvent(ieName, func); } } else { node.removeEventListener(name, func, false); } } /** * Given an event from a script node, get the requirejs info from it, * and then removes the event listeners on the node. * @param {Event} evt * @returns {Object} */ function getScriptData(evt) { //Using currentTarget instead of target for Firefox 2.0's sake. Not //all old browsers will be supported, but this one was easy enough //to support and still makes sense. var node = evt.currentTarget || evt.srcElement; //Remove the listeners once here. removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange'); removeListener(node, context.onScriptError, 'error'); return { node: node, id: node && node.getAttribute('data-requiremodule') }; } function intakeDefines() { var args; //Any defined modules in the global queue, intake them now. takeGlobalQueue(); //Make sure any remaining defQueue items get properly processed. while (defQueue.length) { args = defQueue.shift(); if (args[0] === null) { return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1])); } else { //args are id, deps, factory. Should be normalized by the //define() function. callGetModule(args); } } context.defQueueMap = {}; } context = { config: config, contextName: contextName, registry: registry, defined: defined, urlFetched: urlFetched, defQueue: defQueue, defQueueMap: {}, Module: Module, makeModuleMap: makeModuleMap, nextTick: req.nextTick, onError: onError, /** * Set a configuration for the context. * @param {Object} cfg config object to integrate. */ configure: function (cfg) { //Make sure the baseUrl ends in a slash. if (cfg.baseUrl) { if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') { cfg.baseUrl += '/'; } } // Convert old style urlArgs string to a function. if (typeof cfg.urlArgs === 'string') { var urlArgs = cfg.urlArgs; cfg.urlArgs = function(id, url) { return (url.indexOf('?') === -1 ? '?' : '&') + urlArgs; }; } //Save off the paths since they require special processing, //they are additive. var shim = config.shim, objs = { paths: true, bundles: true, config: true, map: true }; eachProp(cfg, function (value, prop) { if (objs[prop]) { if (!config[prop]) { config[prop] = {}; } mixin(config[prop], value, true, true); } else { config[prop] = value; } }); //Reverse map the bundles if (cfg.bundles) { eachProp(cfg.bundles, function (value, prop) { each(value, function (v) { if (v !== prop) { bundlesMap[v] = prop; } }); }); } //Merge shim if (cfg.shim) { eachProp(cfg.shim, function (value, id) { //Normalize the structure if (isArray(value)) { value = { deps: value }; } if ((value.exports || value.init) && !value.exportsFn) { value.exportsFn = context.makeShimExports(value); } shim[id] = value; }); config.shim = shim; } //Adjust packages if necessary. if (cfg.packages) { each(cfg.packages, function (pkgObj) { var location, name; pkgObj = typeof pkgObj === 'string' ? {name: pkgObj} : pkgObj; name = pkgObj.name; location = pkgObj.location; if (location) { config.paths[name] = pkgObj.location; } //Save pointer to main module ID for pkg name. //Remove leading dot in main, so main paths are normalized, //and remove any trailing .js, since different package //envs have different conventions: some use a module name, //some use a file name. config.pkgs[name] = pkgObj.name + '/' + (pkgObj.main || 'main') .replace(currDirRegExp, '') .replace(jsSuffixRegExp, ''); }); } //If there are any "waiting to execute" modules in the registry, //update the maps for them, since their info, like URLs to load, //may have changed. eachProp(registry, function (mod, id) { //If module already has init called, since it is too //late to modify them, and ignore unnormalized ones //since they are transient. if (!mod.inited && !mod.map.unnormalized) { mod.map = makeModuleMap(id, null, true); } }); //If a deps array or a config callback is specified, then call //require with those args. This is useful when require is defined as a //config object before require.js is loaded. if (cfg.deps || cfg.callback) { context.require(cfg.deps || [], cfg.callback); } }, makeShimExports: function (value) { function fn() { var ret; if (value.init) { ret = value.init.apply(global, arguments); } return ret || (value.exports && getGlobal(value.exports)); } return fn; }, makeRequire: function (relMap, options) { options = options || {}; function localRequire(deps, callback, errback) { var id, map, requireMod; if (options.enableBuildCallback && callback && isFunction(callback)) { callback.__requireJsBuild = true; } if (typeof deps === 'string') { if (isFunction(callback)) { //Invalid call return onError(makeError('requireargs', 'Invalid require call'), errback); } //If require|exports|module are requested, get the //value for them from the special handlers. Caveat: //this only works while module is being defined. if (relMap && hasProp(handlers, deps)) { return handlers[deps](registry[relMap.id]); } //Synchronous access to one module. If require.get is //available (as in the Node adapter), prefer that. if (req.get) { return req.get(context, deps, relMap, localRequire); } //Normalize module name, if it contains . or .. map = makeModuleMap(deps, relMap, false, true); id = map.id; if (!hasProp(defined, id)) { return onError(makeError('notloaded', 'Module name "' + id + '" has not been loaded yet for context: ' + contextName + (relMap ? '' : '. Use require([])'))); } return defined[id]; } //Grab defines waiting in the global queue. intakeDefines(); //Mark all the dependencies as needing to be loaded. context.nextTick(function () { //Some defines could have been added since the //require call, collect them. intakeDefines(); requireMod = getModule(makeModuleMap(null, relMap)); //Store if map config should be applied to this require //call for dependencies. requireMod.skipMap = options.skipMap; requireMod.init(deps, callback, errback, { enabled: true }); checkLoaded(); }); return localRequire; } mixin(localRequire, { isBrowser: isBrowser, /** * Converts a module name + .extension into an URL path. * *Requires* the use of a module name. It does not support using * plain URLs like nameToUrl. */ toUrl: function (moduleNamePlusExt) { var ext, index = moduleNamePlusExt.lastIndexOf('.'), segment = moduleNamePlusExt.split('/')[0], isRelative = segment === '.' || segment === '..'; //Have a file extension alias, and it is not the //dots from a relative path. if (index !== -1 && (!isRelative || index > 1)) { ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length); moduleNamePlusExt = moduleNamePlusExt.substring(0, index); } return context.nameToUrl(normalize(moduleNamePlusExt, relMap && relMap.id, true), ext, true); }, defined: function (id) { return hasProp(defined, makeModuleMap(id, relMap, false, true).id); }, specified: function (id) { id = makeModuleMap(id, relMap, false, true).id; return hasProp(defined, id) || hasProp(registry, id); } }); //Only allow undef on top level require calls if (!relMap) { localRequire.undef = function (id) { //Bind any waiting define() calls to this context, //fix for #408 takeGlobalQueue(); var map = makeModuleMap(id, relMap, true), mod = getOwn(registry, id); mod.undefed = true; removeScript(id); delete defined[id]; delete urlFetched[map.url]; delete undefEvents[id]; //Clean queued defines too. Go backwards //in array so that the splices do not //mess up the iteration. eachReverse(defQueue, function(args, i) { if (args[0] === id) { defQueue.splice(i, 1); } }); delete context.defQueueMap[id]; if (mod) { //Hold on to listeners in case the //module will be attempted to be reloaded //using a different config. if (mod.events.defined) { undefEvents[id] = mod.events; } cleanRegistry(id); } }; } return localRequire; }, /** * Called to enable a module if it is still in the registry * awaiting enablement. A second arg, parent, the parent module, * is passed in for context, when this method is overridden by * the optimizer. Not shown here to keep code compact. */ enable: function (depMap) { var mod = getOwn(registry, depMap.id); if (mod) { getModule(depMap).enable(); } }, /** * Internal method used by environment adapters to complete a load event. * A load event could be a script load or just a load pass from a synchronous * load call. * @param {String} moduleName the name of the module to potentially complete. */ completeLoad: function (moduleName) { var found, args, mod, shim = getOwn(config.shim, moduleName) || {}, shExports = shim.exports; takeGlobalQueue(); while (defQueue.length) { args = defQueue.shift(); if (args[0] === null) { args[0] = moduleName; //If already found an anonymous module and bound it //to this name, then this is some other anon module //waiting for its completeLoad to fire. if (found) { break; } found = true; } else if (args[0] === moduleName) { //Found matching define call for this script! found = true; } callGetModule(args); } context.defQueueMap = {}; //Do this after the cycle of callGetModule in case the result //of those calls/init calls changes the registry. mod = getOwn(registry, moduleName); if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) { if (config.enforceDefine && (!shExports || !getGlobal(shExports))) { if (hasPathFallback(moduleName)) { return; } else { return onError(makeError('nodefine', 'No define call for ' + moduleName, null, [moduleName])); } } else { //A script that does not call define(), so just simulate //the call for it. callGetModule([moduleName, (shim.deps || []), shim.exportsFn]); } } checkLoaded(); }, /** * Converts a module name to a file path. Supports cases where * moduleName may actually be just an URL. * Note that it **does not** call normalize on the moduleName, * it is assumed to have already been normalized. This is an * internal API, not a public one. Use toUrl for the public API. */ nameToUrl: function (moduleName, ext, skipExt) { var paths, syms, i, parentModule, url, parentPath, bundleId, pkgMain = getOwn(config.pkgs, moduleName); if (pkgMain) { moduleName = pkgMain; } bundleId = getOwn(bundlesMap, moduleName); if (bundleId) { return context.nameToUrl(bundleId, ext, skipExt); } //If a colon is in the URL, it indicates a protocol is used and it is just //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?) //or ends with .js, then assume the user meant to use an url and not a module id. //The slash is important for protocol-less URLs as well as full paths. if (req.jsExtRegExp.test(moduleName)) { //Just a plain path, not module name lookup, so just return it. //Add extension if it is included. This is a bit wonky, only non-.js things pass //an extension, this method probably needs to be reworked. url = moduleName + (ext || ''); } else { //A module that needs to be converted to a path. paths = config.paths; syms = moduleName.split('/'); //For each module name segment, see if there is a path //registered for it. Start with most specific name //and work up from it. for (i = syms.length; i > 0; i -= 1) { parentModule = syms.slice(0, i).join('/'); parentPath = getOwn(paths, parentModule); if (parentPath) { //If an array, it means there are a few choices, //Choose the one that is desired if (isArray(parentPath)) { parentPath = parentPath[0]; } syms.splice(0, i, parentPath); break; } } //Join the path parts together, then figure out if baseUrl is needed. url = syms.join('/'); url += (ext || (/^data\:|^blob\:|\?/.test(url) || skipExt ? '' : '.js')); url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url; } return config.urlArgs && !/^blob\:/.test(url) ? url + config.urlArgs(moduleName, url) : url; }, //Delegates to req.load. Broken out as a separate function to //allow overriding in the optimizer. load: function (id, url) { req.load(context, id, url); }, /** * Executes a module callback function. Broken out as a separate function * solely to allow the build system to sequence the files in the built * layer in the right sequence. * * @private */ execCb: function (name, callback, args, exports) { return callback.apply(exports, args); }, /** * callback for script loads, used to check status of loading. * * @param {Event} evt the event from the browser for the script * that was loaded. */ onScriptLoad: function (evt) { //Using currentTarget instead of target for Firefox 2.0's sake. Not //all old browsers will be supported, but this one was easy enough //to support and still makes sense. if (evt.type === 'load' || (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) { //Reset interactive script so a script node is not held onto for //to long. interactiveScript = null; //Pull out the name of the module and the context. var data = getScriptData(evt); context.completeLoad(data.id); } }, /** * Callback for script errors. */ onScriptError: function (evt) { var data = getScriptData(evt); if (!hasPathFallback(data.id)) { var parents = []; eachProp(registry, function(value, key) { if (key.indexOf('_@r') !== 0) { each(value.depMaps, function(depMap) { if (depMap.id === data.id) { parents.push(key); return true; } }); } }); return onError(makeError('scripterror', 'Script error for "' + data.id + (parents.length ? '", needed by: ' + parents.join(', ') : '"'), evt, [data.id])); } } }; context.require = context.makeRequire(); return context; } /** * Main entry point. * * If the only argument to require is a string, then the module that * is represented by that string is fetched for the appropriate context. * * If the first argument is an array, then it will be treated as an array * of dependency string names to fetch. An optional function callback can * be specified to execute when all of those dependencies are available. * * Make a local req variable to help Caja compliance (it assumes things * on a require that are not standardized), and to give a short * name for minification/local scope use. */ req = requirejs = function (deps, callback, errback, optional) { //Find the right context, use default var context, config, contextName = defContextName; // Determine if have config object in the call. if (!isArray(deps) && typeof deps !== 'string') { // deps is a config object config = deps; if (isArray(callback)) { // Adjust args if there are dependencies deps = callback; callback = errback; errback = optional; } else { deps = []; } } if (config && config.context) { contextName = config.context; } context = getOwn(contexts, contextName); if (!context) { context = contexts[contextName] = req.s.newContext(contextName); } if (config) { context.configure(config); } return context.require(deps, callback, errback); }; /** * Support require.config() to make it easier to cooperate with other * AMD loaders on globally agreed names. */ req.config = function (config) { return req(config); }; /** * Execute something after the current tick * of the event loop. Override for other envs * that have a better solution than setTimeout. * @param {Function} fn function to execute later. */ req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) { setTimeout(fn, 4); } : function (fn) { fn(); }; /** * Export require as a global, but only if it does not already exist. */ if (!require) { require = req; } req.version = version; //Used to filter out dependencies that are already paths. req.jsExtRegExp = /^\/|:|\?|\.js$/; req.isBrowser = isBrowser; s = req.s = { contexts: contexts, newContext: newContext }; //Create default context. req({}); //Exports some context-sensitive methods on global require. each([ 'toUrl', 'undef', 'defined', 'specified' ], function (prop) { //Reference from contexts instead of early binding to default context, //so that during builds, the latest instance of the default context //with its config gets used. req[prop] = function () { var ctx = contexts[defContextName]; return ctx.require[prop].apply(ctx, arguments); }; }); if (isBrowser) { head = s.head = document.getElementsByTagName('head')[0]; //If BASE tag is in play, using appendChild is a problem for IE6. //When that browser dies, this can be removed. Details in this jQuery bug: //http://dev.jquery.com/ticket/2709 baseElement = document.getElementsByTagName('base')[0]; if (baseElement) { head = s.head = baseElement.parentNode; } } /** * Any errors that require explicitly generates will be passed to this * function. Intercept/override it if you want custom error handling. * @param {Error} err the error object. */ req.onError = defaultOnError; /** * Creates the node for the load command. Only used in browser envs. */ req.createNode = function (config, moduleName, url) { var node = config.xhtml ? document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') : document.createElement('script'); node.type = config.scriptType || 'text/javascript'; node.charset = 'utf-8'; node.async = true; return node; }; /** * Does the request to load a module for the browser case. * Make this a separate function to allow other environments * to override it. * * @param {Object} context the require context to find state. * @param {String} moduleName the name of the module. * @param {Object} url the URL to the module. */ req.load = function (context, moduleName, url) { var config = (context && context.config) || {}, node; if (isBrowser) { //In the browser so use a script tag node = req.createNode(config, moduleName, url); node.setAttribute('data-requirecontext', context.contextName); node.setAttribute('data-requiremodule', moduleName); //Set up load listener. Test attachEvent first because IE9 has //a subtle issue in its addEventListener and script onload firings //that do not match the behavior of all other browsers with //addEventListener support, which fire the onload event for a //script right after the script execution. See: //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution //UNFORTUNATELY Opera implements attachEvent but does not follow the script //script execution mode. if (node.attachEvent && //Check if node.attachEvent is artificially added by custom script or //natively supported by browser //read https://github.com/requirejs/requirejs/issues/187 //if we can NOT find [native code] then it must NOT natively supported. //in IE8, node.attachEvent does not have toString() //Note the test for "[native code" with no closing brace, see: //https://github.com/requirejs/requirejs/issues/273 !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) && !isOpera) { //Probably IE. IE (at least 6-8) do not fire //script onload right after executing the script, so //we cannot tie the anonymous define call to a name. //However, IE reports the script as being in 'interactive' //readyState at the time of the define call. useInteractive = true; node.attachEvent('onreadystatechange', context.onScriptLoad); //It would be great to add an error handler here to catch //404s in IE9+. However, onreadystatechange will fire before //the error handler, so that does not help. If addEventListener //is used, then IE will fire error before load, but we cannot //use that pathway given the connect.microsoft.com issue //mentioned above about not doing the 'script execute, //then fire the script load event listener before execute //next script' that other browsers do. //Best hope: IE10 fixes the issues, //and then destroys all installs of IE 6-9. //node.attachEvent('onerror', context.onScriptError); } else { node.addEventListener('load', context.onScriptLoad, false); node.addEventListener('error', context.onScriptError, false); } node.src = url; //Calling onNodeCreated after all properties on the node have been //set, but before it is placed in the DOM. if (config.onNodeCreated) { config.onNodeCreated(node, config, moduleName, url); } //For some cache cases in IE 6-8, the script executes before the end //of the appendChild execution, so to tie an anonymous define //call to the module name (which is stored on the node), hold on //to a reference to this node, but clear after the DOM insertion. currentlyAddingScript = node; if (baseElement) { head.insertBefore(node, baseElement); } else { head.appendChild(node); } currentlyAddingScript = null; return node; } else if (isWebWorker) { try { //In a web worker, use importScripts. This is not a very //efficient use of importScripts, importScripts will block until //its script is downloaded and evaluated. However, if web workers //are in play, the expectation is that a build has been done so //that only one script needs to be loaded anyway. This may need //to be reevaluated if other use cases become common. // Post a task to the event loop to work around a bug in WebKit // where the worker gets garbage-collected after calling // importScripts(): https://webkit.org/b/153317 setTimeout(function() {}, 0); importScripts(url); //Account for anonymous modules context.completeLoad(moduleName); } catch (e) { context.onError(makeError('importscripts', 'importScripts failed for ' + moduleName + ' at ' + url, e, [moduleName])); } } }; function getInteractiveScript() { if (interactiveScript && interactiveScript.readyState === 'interactive') { return interactiveScript; } eachReverse(scripts(), function (script) { if (script.readyState === 'interactive') { return (interactiveScript = script); } }); return interactiveScript; } //Look for a data-main script attribute, which could also adjust the baseUrl. if (isBrowser && !cfg.skipDataMain) { //Figure out baseUrl. Get it from the script tag with require.js in it. eachReverse(scripts(), function (script) { //Set the 'head' where we can append children by //using the script's parent. if (!head) { head = script.parentNode; } //Look for a data-main attribute to set main script for the page //to load. If it is there, the path to data main becomes the //baseUrl, if it is not already set. dataMain = script.getAttribute('data-main'); if (dataMain) { //Preserve dataMain in case it is a path (i.e. contains '?') mainScript = dataMain; //Set final baseUrl if there is not already an explicit one, //but only do so if the data-main value is not a loader plugin //module ID. if (!cfg.baseUrl && mainScript.indexOf('!') === -1) { //Pull off the directory of data-main for use as the //baseUrl. src = mainScript.split('/'); mainScript = src.pop(); subPath = src.length ? src.join('/') + '/' : './'; cfg.baseUrl = subPath; } //Strip off any trailing .js since mainScript is now //like a module name. mainScript = mainScript.replace(jsSuffixRegExp, ''); //If mainScript is still a path, fall back to dataMain if (req.jsExtRegExp.test(mainScript)) { mainScript = dataMain; } //Put the data-main script in the files to load. cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript]; return true; } }); } /** * The function that handles definitions of modules. Differs from * require() in that a string for the module should be the first argument, * and the function to execute after dependencies are loaded should * return a value to define the module corresponding to the first argument's * name. */ define = function (name, deps, callback) { var node, context; //Allow for anonymous modules if (typeof name !== 'string') { //Adjust args appropriately callback = deps; deps = name; name = null; } //This module may not have dependencies if (!isArray(deps)) { callback = deps; deps = null; } //If no name, and callback is a function, then figure out if it a //CommonJS thing with dependencies. if (!deps && isFunction(callback)) { deps = []; //Remove comments from the callback string, //look for require calls, and pull them into the dependencies, //but only if there are function args. if (callback.length) { callback .toString() .replace(commentRegExp, commentReplace) .replace(cjsRequireRegExp, function (match, dep) { deps.push(dep); }); //May be a CommonJS thing even without require calls, but still //could use exports, and module. Avoid doing exports and module //work though if it just needs require. //REQUIRES the function to expect the CommonJS variables in the //order listed below. deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps); } } //If in IE 6-8 and hit an anonymous define() call, do the interactive //work. if (useInteractive) { node = currentlyAddingScript || getInteractiveScript(); if (node) { if (!name) { name = node.getAttribute('data-requiremodule'); } context = contexts[node.getAttribute('data-requirecontext')]; } } //Always save off evaluating the def call until the script onload handler. //This allows multiple modules to be in a file without prematurely //tracing dependencies, and allows for anonymous module support, //where the module name is not known until the script onload event //occurs. If no context, use the global queue, and get it processed //in the onscript load callback. if (context) { context.defQueue.push([name, deps, callback]); context.defQueueMap[name] = true; } else { globalDefQueue.push([name, deps, callback]); } }; define.amd = { jQuery: true }; /** * Executes the text. Normally just uses eval, but can be modified * to use a better, environment-specific call. Only used for transpiling * loader plugins, not for plain JS modules. * @param {String} text the text to execute/evaluate. */ req.exec = function (text) { /*jslint evil: true */ return eval(text); }; //Set up with config info. req(cfg); }(this)); this.requirejsVars = { require: require, requirejs: require, define: define }; if (env === 'browser') { //sloppy since eval enclosed with use strict causes problems if the source //text is not strict-compliant. /*jslint sloppy: true, evil: true */ /*global require, XMLHttpRequest */ (function () { // Separate function to avoid eval pollution, same with arguments use. function exec() { eval(arguments[0]); } require.load = function (context, moduleName, url) { var xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.send(); xhr.onreadystatechange = function () { if (xhr.readyState === 4) { exec(xhr.responseText); //Support anonymous modules. context.completeLoad(moduleName); } }; }; }()); } else if (env === 'rhino') { /*global require: false, java: false, load: false */ (function () { 'use strict'; require.load = function (context, moduleName, url) { load(url); //Support anonymous modules. context.completeLoad(moduleName); }; }()); } else if (env === 'node') { this.requirejsVars.nodeRequire = nodeRequire; require.nodeRequire = nodeRequire; //Explicity not strict since this file contains an eval call, and do not want //to enforce strict on code evaluated that way. See //https://github.com/requirejs/r.js/issues/774 /*jslint regexp: false, sloppy: true*/ /*global require: false, define: false, requirejsVars: false, process: false */ /** * This adapter assumes that x.js has loaded it and set up * some variables. This adapter just allows limited RequireJS * usage from within the requirejs directory. The general * node adapater is r.js. */ (function () { var nodeReq = requirejsVars.nodeRequire, req = requirejsVars.require, def = requirejsVars.define, fs = nodeReq('fs'), path = nodeReq('path'), vm = nodeReq('vm'), //In Node 0.7+ existsSync is on fs. exists = fs.existsSync || path.existsSync, hasOwn = Object.prototype.hasOwnProperty; function hasProp(obj, prop) { return hasOwn.call(obj, prop); } function syncTick(fn) { fn(); } function makeError(message, moduleName) { var err = new Error(message); err.requireModules = [moduleName]; return err; } //Supply an implementation that allows synchronous get of a module. req.get = function (context, moduleName, relModuleMap, localRequire) { if (moduleName === "require" || moduleName === "exports" || moduleName === "module") { context.onError(makeError("Explicit require of " + moduleName + " is not allowed.", moduleName)); } var ret, oldTick, moduleMap = context.makeModuleMap(moduleName, relModuleMap, false, true); //Normalize module name, if it contains . or .. moduleName = moduleMap.id; if (hasProp(context.defined, moduleName)) { ret = context.defined[moduleName]; } else { if (ret === undefined) { //Make sure nextTick for this type of call is sync-based. oldTick = context.nextTick; context.nextTick = syncTick; try { if (moduleMap.prefix) { //A plugin, call requirejs to handle it. Now that //nextTick is syncTick, the require will complete //synchronously. localRequire([moduleMap.originalName]); //Now that plugin is loaded, can regenerate the moduleMap //to get the final, normalized ID. moduleMap = context.makeModuleMap(moduleMap.originalName, relModuleMap, false, true); moduleName = moduleMap.id; } else { //Try to dynamically fetch it. req.load(context, moduleName, moduleMap.url); //Enable the module context.enable(moduleMap, relModuleMap); } //Break any cycles by requiring it normally, but this will //finish synchronously context.require([moduleName]); //The above calls are sync, so can do the next thing safely. ret = context.defined[moduleName]; } finally { context.nextTick = oldTick; } } } return ret; }; req.nextTick = function (fn) { process.nextTick(fn); }; //Add wrapper around the code so that it gets the requirejs //API instead of the Node API, and it is done lexically so //that it survives later execution. req.makeNodeWrapper = function (contents) { return '(function (require, requirejs, define) { ' + contents + '\n}(requirejsVars.require, requirejsVars.requirejs, requirejsVars.define));'; }; req.load = function (context, moduleName, url) { var contents, err, config = context.config; if (config.shim[moduleName] && (!config.suppress || !config.suppress.nodeShim)) { console.warn('Shim config not supported in Node, may or may not work. Detected ' + 'for module: ' + moduleName); } if (exists(url)) { contents = fs.readFileSync(url, 'utf8'); contents = req.makeNodeWrapper(contents); try { vm.runInThisContext(contents, fs.realpathSync(url)); } catch (e) { err = new Error('Evaluating ' + url + ' as module "' + moduleName + '" failed with error: ' + e); err.originalError = e; err.moduleName = moduleName; err.requireModules = [moduleName]; err.fileName = url; return context.onError(err); } } else { def(moduleName, function () { //Get the original name, since relative requires may be //resolved differently in node (issue #202). Also, if relative, //make it relative to the URL of the item requesting it //(issue #393) var dirName, map = hasProp(context.registry, moduleName) && context.registry[moduleName].map, parentMap = map && map.parentMap, originalName = map && map.originalName; if (originalName.charAt(0) === '.' && parentMap) { dirName = parentMap.url.split('/'); dirName.pop(); originalName = dirName.join('/') + '/' + originalName; } try { return (context.config.nodeRequire || req.nodeRequire)(originalName); } catch (e) { err = new Error('Tried loading "' + moduleName + '" at ' + url + ' then tried node\'s require("' + originalName + '") and it failed ' + 'with error: ' + e); err.originalError = e; err.moduleName = originalName; err.requireModules = [moduleName]; throw err; } }); } //Support anonymous modules. context.completeLoad(moduleName); }; //Override to provide the function wrapper for define/require. req.exec = function (text) { /*jslint evil: true */ text = req.makeNodeWrapper(text); return eval(text); }; }()); } else if (env === 'xpconnect') { /*jslint */ /*global require, load */ (function () { 'use strict'; require.load = function (context, moduleName, url) { load(url); //Support anonymous modules. context.completeLoad(moduleName); }; }()); } //Support a default file name to execute. Useful for hosted envs //like Joyent where it defaults to a server.js as the only executed //script. But only do it if this is not an optimization run. if (commandOption !== 'o' && (!fileName || !jsSuffixRegExp.test(fileName))) { fileName = 'main.js'; } /** * Loads the library files that can be used for the optimizer, or for other * tasks. */ function loadLib() { /*jslint strict: false */ /*global Packages: false, process: false, window: false, navigator: false, document: false, define: false */ /** * A plugin that modifies any /env/ path to be the right path based on * the host environment. Right now only works for Node, Rhino and browser. */ (function () { var pathRegExp = /(\/|^)env\/|\{env\}/, env = 'unknown'; if (typeof process !== 'undefined' && process.versions && !!process.versions.node) { env = 'node'; } else if (typeof Packages !== 'undefined') { env = 'rhino'; } else if ((typeof navigator !== 'undefined' && typeof document !== 'undefined') || (typeof importScripts !== 'undefined' && typeof self !== 'undefined')) { env = 'browser'; } else if (typeof Components !== 'undefined' && Components.classes && Components.interfaces) { env = 'xpconnect'; } define('env', { get: function () { return env; }, load: function (name, req, load, config) { //Allow override in the config. if (config.env) { env = config.env; } name = name.replace(pathRegExp, function (match, prefix) { if (match.indexOf('{') === -1) { return prefix + env + '/'; } else { return env; } }); req([name], function (mod) { load(mod); }); } }); }()); /*jslint plusplus: true */ /*global define, java */ define('lang', function () { 'use strict'; var lang, isJavaObj, hasOwn = Object.prototype.hasOwnProperty; function hasProp(obj, prop) { return hasOwn.call(obj, prop); } isJavaObj = function () { return false; }; //Rhino, but not Nashorn (detected by importPackage not existing) //Can have some strange foreign objects. if (typeof java !== 'undefined' && java.lang && java.lang.Object && typeof importPackage !== 'undefined') { isJavaObj = function (obj) { return obj instanceof java.lang.Object; }; } lang = { backSlashRegExp: /\\/g, ostring: Object.prototype.toString, isArray: Array.isArray || function (it) { return lang.ostring.call(it) === "[object Array]"; }, isFunction: function(it) { return lang.ostring.call(it) === "[object Function]"; }, isRegExp: function(it) { return it && it instanceof RegExp; }, hasProp: hasProp, //returns true if the object does not have an own property prop, //or if it does, it is a falsy value. falseProp: function (obj, prop) { return !hasProp(obj, prop) || !obj[prop]; }, //gets own property value for given prop on object getOwn: function (obj, prop) { return hasProp(obj, prop) && obj[prop]; }, _mixin: function(dest, source, override){ var name; for (name in source) { if(source.hasOwnProperty(name) && (override || !dest.hasOwnProperty(name))) { dest[name] = source[name]; } } return dest; // Object }, /** * mixin({}, obj1, obj2) is allowed. If the last argument is a boolean, * then the source objects properties are force copied over to dest. */ mixin: function(dest){ var parameters = Array.prototype.slice.call(arguments), override, i, l; if (!dest) { dest = {}; } if (parameters.length > 2 && typeof arguments[parameters.length-1] === 'boolean') { override = parameters.pop(); } for (i = 1, l = parameters.length; i < l; i++) { lang._mixin(dest, parameters[i], override); } return dest; // Object }, /** * Does a deep mix of source into dest, where source values override * dest values if a winner is needed. * @param {Object} dest destination object that receives the mixed * values. * @param {Object} source source object contributing properties to mix * in. * @return {[Object]} returns dest object with the modification. */ deepMix: function(dest, source) { lang.eachProp(source, function (value, prop) { if (typeof value === 'object' && value && !lang.isArray(value) && !lang.isFunction(value) && !(value instanceof RegExp)) { if (!dest[prop]) { dest[prop] = {}; } lang.deepMix(dest[prop], value); } else { dest[prop] = value; } }); return dest; }, /** * Does a type of deep copy. Do not give it anything fancy, best * for basic object copies of objects that also work well as * JSON-serialized things, or has properties pointing to functions. * For non-array/object values, just returns the same object. * @param {Object} obj copy properties from this object * @param {Object} [ignoredProps] optional object whose own properties * are keys that should be ignored. * @return {Object} */ deeplikeCopy: function (obj, ignoredProps) { var type, result; if (lang.isArray(obj)) { result = []; obj.forEach(function(value) { result.push(lang.deeplikeCopy(value, ignoredProps)); }); return result; } type = typeof obj; if (obj === null || obj === undefined || type === 'boolean' || type === 'string' || type === 'number' || lang.isFunction(obj) || lang.isRegExp(obj)|| isJavaObj(obj)) { return obj; } //Anything else is an object, hopefully. result = {}; lang.eachProp(obj, function(value, key) { if (!ignoredProps || !hasProp(ignoredProps, key)) { result[key] = lang.deeplikeCopy(value, ignoredProps); } }); return result; }, delegate: (function () { // boodman/crockford delegation w/ cornford optimization function TMP() {} return function (obj, props) { TMP.prototype = obj; var tmp = new TMP(); TMP.prototype = null; if (props) { lang.mixin(tmp, props); } return tmp; // Object }; }()), /** * Helper function for iterating over an array. If the func returns * a true value, it will break out of the loop. */ each: function each(ary, func) { if (ary) { var i; for (i = 0; i < ary.length; i += 1) { if (func(ary[i], i, ary)) { break; } } } }, /** * Cycles over properties in an object and calls a function for each * property value. If the function returns a truthy value, then the * iteration is stopped. */ eachProp: function eachProp(obj, func) { var prop; for (prop in obj) { if (hasProp(obj, prop)) { if (func(obj[prop], prop)) { break; } } } }, //Similar to Function.prototype.bind, but the "this" object is specified //first, since it is easier to read/figure out what "this" will be. bind: function bind(obj, fn) { return function () { return fn.apply(obj, arguments); }; }, //Escapes a content string to be be a string that has characters escaped //for inclusion as part of a JS string. jsEscape: function (content) { return content.replace(/(["'\\])/g, '\\$1') .replace(/[\f]/g, "\\f") .replace(/[\b]/g, "\\b") .replace(/[\n]/g, "\\n") .replace(/[\t]/g, "\\t") .replace(/[\r]/g, "\\r"); } }; return lang; }); /** * prim 0.0.1 Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved. * Available via the MIT or new BSD license. * see: http://github.com/requirejs/prim for details */ /*global setImmediate, process, setTimeout, define, module */ //Set prime.hideResolutionConflict = true to allow "resolution-races" //in promise-tests to pass. //Since the goal of prim is to be a small impl for trusted code, it is //more important to normally throw in this case so that we can find //logic errors quicker. var prim; (function () { 'use strict'; var op = Object.prototype, hasOwn = op.hasOwnProperty; function hasProp(obj, prop) { return hasOwn.call(obj, prop); } /** * Helper function for iterating over an array. If the func returns * a true value, it will break out of the loop. */ function each(ary, func) { if (ary) { var i; for (i = 0; i < ary.length; i += 1) { if (ary[i]) { func(ary[i], i, ary); } } } } function check(p) { if (hasProp(p, 'e') || hasProp(p, 'v')) { if (!prim.hideResolutionConflict) { throw new Error('Prim promise already resolved: ' + JSON.stringify(p)); } return false; } return true; } function notify(ary, value) { prim.nextTick(function () { each(ary, function (item) { item(value); }); }); } prim = function prim() { var p, ok = [], fail = []; return (p = { callback: function (yes, no) { if (no) { p.errback(no); } if (hasProp(p, 'v')) { prim.nextTick(function () { yes(p.v); }); } else { ok.push(yes); } }, errback: function (no) { if (hasProp(p, 'e')) { prim.nextTick(function () { no(p.e); }); } else { fail.push(no); } }, finished: function () { return hasProp(p, 'e') || hasProp(p, 'v'); }, rejected: function () { return hasProp(p, 'e'); }, resolve: function (v) { if (check(p)) { p.v = v; notify(ok, v); } return p; }, reject: function (e) { if (check(p)) { p.e = e; notify(fail, e); } return p; }, start: function (fn) { p.resolve(); return p.promise.then(fn); }, promise: { then: function (yes, no) { var next = prim(); p.callback(function (v) { try { if (yes && typeof yes === 'function') { v = yes(v); } if (v && v.then) { v.then(next.resolve, next.reject); } else { next.resolve(v); } } catch (e) { next.reject(e); } }, function (e) { var err; try { if (!no || typeof no !== 'function') { next.reject(e); } else { err = no(e); if (err && err.then) { err.then(next.resolve, next.reject); } else { next.resolve(err); } } } catch (e2) { next.reject(e2); } }); return next.promise; }, fail: function (no) { return p.promise.then(null, no); }, end: function () { p.errback(function (e) { throw e; }); } } }); }; prim.serial = function (ary) { var result = prim().resolve().promise; each(ary, function (item) { result = result.then(function () { return item(); }); }); return result; }; prim.nextTick = typeof setImmediate === 'function' ? setImmediate : (typeof process !== 'undefined' && process.nextTick ? process.nextTick : (typeof setTimeout !== 'undefined' ? function (fn) { setTimeout(fn, 0); } : function (fn) { fn(); })); if (typeof define === 'function' && define.amd) { define('prim', function () { return prim; }); } else if (typeof module !== 'undefined' && module.exports) { module.exports = prim; } }()); if(env === 'browser') { /*jslint strict: false */ /*global define: false, load: false */ //Just a stub for use with uglify's consolidator.js define('browser/assert', function () { return {}; }); } if(env === 'node') { /*jslint strict: false */ /*global define: false, load: false */ //Needed so that rhino/assert can return a stub for uglify's consolidator.js define('node/assert', ['assert'], function (assert) { return assert; }); } if(env === 'rhino') { /*jslint strict: false */ /*global define: false, load: false */ //Just a stub for use with uglify's consolidator.js define('rhino/assert', function () { return {}; }); } if(env === 'xpconnect') { /*jslint strict: false */ /*global define: false, load: false */ //Just a stub for use with uglify's consolidator.js define('xpconnect/assert', function () { return {}; }); } if(env === 'browser') { /*jslint strict: false */ /*global define: false, process: false */ define('browser/args', function () { //Always expect config via an API call return []; }); } if(env === 'node') { /*jslint strict: false */ /*global define: false, process: false */ define('node/args', function () { //Do not return the "node" or "r.js" arguments var args = process.argv.slice(2); //Ignore any command option used for main x.js branching if (args[0] && args[0].indexOf('-') === 0) { args = args.slice(1); } return args; }); } if(env === 'rhino') { /*jslint strict: false */ /*global define: false, process: false */ var jsLibRhinoArgs = (typeof rhinoArgs !== 'undefined' && rhinoArgs) || [].concat(Array.prototype.slice.call(arguments, 0)); define('rhino/args', function () { var args = jsLibRhinoArgs; //Ignore any command option used for main x.js branching if (args[0] && args[0].indexOf('-') === 0) { args = args.slice(1); } return args; }); } if(env === 'xpconnect') { /*jslint strict: false */ /*global define, xpconnectArgs */ var jsLibXpConnectArgs = (typeof xpconnectArgs !== 'undefined' && xpconnectArgs) || [].concat(Array.prototype.slice.call(arguments, 0)); define('xpconnect/args', function () { var args = jsLibXpConnectArgs; //Ignore any command option used for main x.js branching if (args[0] && args[0].indexOf('-') === 0) { args = args.slice(1); } return args; }); } if(env === 'browser') { /*jslint strict: false */ /*global define: false, console: false */ define('browser/load', ['./file'], function (file) { function load(fileName) { eval(file.readFile(fileName)); } return load; }); } if(env === 'node') { /*jslint strict: false */ /*global define: false, console: false */ define('node/load', ['fs'], function (fs) { function load(fileName) { var contents = fs.readFileSync(fileName, 'utf8'); process.compile(contents, fileName); } return load; }); } if(env === 'rhino') { /*jslint strict: false */ /*global define: false, load: false */ define('rhino/load', function () { return load; }); } if(env === 'xpconnect') { /*jslint strict: false */ /*global define: false, load: false */ define('xpconnect/load', function () { return load; }); } if(env === 'browser') { /*jslint sloppy: true, nomen: true */ /*global require, define, console, XMLHttpRequest, requirejs, location */ define('browser/file', ['prim'], function (prim) { var file, currDirRegExp = /^\.(\/|$)/; function frontSlash(path) { return path.replace(/\\/g, '/'); } function exists(path) { var status, xhr = new XMLHttpRequest(); //Oh yeah, that is right SYNC IO. Behold its glory //and horrible blocking behavior. xhr.open('HEAD', path, false); xhr.send(); status = xhr.status; return status === 200 || status === 304; } function mkDir(dir) { console.log('mkDir is no-op in browser'); } function mkFullDir(dir) { console.log('mkFullDir is no-op in browser'); } file = { backSlashRegExp: /\\/g, exclusionRegExp: /^\./, getLineSeparator: function () { return '/'; }, exists: function (fileName) { return exists(fileName); }, parent: function (fileName) { var parts = fileName.split('/'); parts.pop(); return parts.join('/'); }, /** * Gets the absolute file path as a string, normalized * to using front slashes for path separators. * @param {String} fileName */ absPath: function (fileName) { var dir; if (currDirRegExp.test(fileName)) { dir = frontSlash(location.href); if (dir.indexOf('/') !== -1) { dir = dir.split('/'); //Pull off protocol and host, just want //to allow paths (other build parts, like //require._isSupportedBuildUrl do not support //full URLs), but a full path from //the root. dir.splice(0, 3); dir.pop(); dir = '/' + dir.join('/'); } fileName = dir + fileName.substring(1); } return fileName; }, normalize: function (fileName) { return fileName; }, isFile: function (path) { return true; }, isDirectory: function (path) { return false; }, getFilteredFileList: function (startDir, regExpFilters, makeUnixPaths) { console.log('file.getFilteredFileList is no-op in browser'); }, copyDir: function (srcDir, destDir, regExpFilter, onlyCopyNew) { console.log('file.copyDir is no-op in browser'); }, copyFile: function (srcFileName, destFileName, onlyCopyNew) { console.log('file.copyFile is no-op in browser'); }, /** * Renames a file. May fail if "to" already exists or is on another drive. */ renameFile: function (from, to) { console.log('file.renameFile is no-op in browser'); }, /** * Reads a *text* file. */ readFile: function (path, encoding) { var xhr = new XMLHttpRequest(); //Oh yeah, that is right SYNC IO. Behold its glory //and horrible blocking behavior. xhr.open('GET', path, false); xhr.send(); return xhr.responseText; }, readFileAsync: function (path, encoding) { var xhr = new XMLHttpRequest(), d = prim(); xhr.open('GET', path, true); xhr.send(); xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status > 400) { d.reject(new Error('Status: ' + xhr.status + ': ' + xhr.statusText)); } else { d.resolve(xhr.responseText); } } }; return d.promise; }, saveUtf8File: function (fileName, fileContents) { //summary: saves a *text* file using UTF-8 encoding. file.saveFile(fileName, fileContents, "utf8"); }, saveFile: function (fileName, fileContents, encoding) { requirejs.browser.saveFile(fileName, fileContents, encoding); }, deleteFile: function (fileName) { console.log('file.deleteFile is no-op in browser'); }, /** * Deletes any empty directories under the given directory. */ deleteEmptyDirs: function (startDir) { console.log('file.deleteEmptyDirs is no-op in browser'); } }; return file; }); } if(env === 'node') { /*jslint plusplus: false, octal:false, strict: false */ /*global define: false, process: false */ define('node/file', ['fs', 'path', 'prim'], function (fs, path, prim) { var isWindows = process.platform === 'win32', windowsDriveRegExp = /^[a-zA-Z]\:\/$/, file; function frontSlash(path) { return path.replace(/\\/g, '/'); } function exists(path) { if (isWindows && path.charAt(path.length - 1) === '/' && path.charAt(path.length - 2) !== ':') { path = path.substring(0, path.length - 1); } try { fs.statSync(path); return true; } catch (e) { return false; } } function mkDir(dir) { if (!exists(dir) && (!isWindows || !windowsDriveRegExp.test(dir))) { fs.mkdirSync(dir, 511); } } function mkFullDir(dir) { var parts = dir.split('/'), currDir = '', first = true; parts.forEach(function (part) { //First part may be empty string if path starts with a slash. currDir += part + '/'; first = false; if (part) { mkDir(currDir); } }); } file = { backSlashRegExp: /\\/g, exclusionRegExp: /^\./, getLineSeparator: function () { return '/'; }, exists: function (fileName) { return exists(fileName); }, parent: function (fileName) { var parts = fileName.split('/'); parts.pop(); return parts.join('/'); }, /** * Gets the absolute file path as a string, normalized * to using front slashes for path separators. * @param {String} fileName */ absPath: function (fileName) { return frontSlash(path.normalize(frontSlash(fs.realpathSync(fileName)))); }, normalize: function (fileName) { return frontSlash(path.normalize(fileName)); }, isFile: function (path) { return fs.statSync(path).isFile(); }, isDirectory: function (path) { return fs.statSync(path).isDirectory(); }, getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths) { //summary: Recurses startDir and finds matches to the files that match regExpFilters.include //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters, //and it will be treated as the "include" case. //Ignores files/directories that start with a period (.) unless exclusionRegExp //is set to another value. var files = [], topDir, regExpInclude, regExpExclude, dirFileArray, i, stat, filePath, ok, dirFiles, fileName; topDir = startDir; regExpInclude = regExpFilters.include || regExpFilters; regExpExclude = regExpFilters.exclude || null; if (file.exists(topDir)) { dirFileArray = fs.readdirSync(topDir); for (i = 0; i < dirFileArray.length; i++) { fileName = dirFileArray[i]; filePath = path.join(topDir, fileName); stat = fs.statSync(filePath); if (stat.isFile()) { if (makeUnixPaths) { //Make sure we have a JS string. if (filePath.indexOf("/") === -1) { filePath = frontSlash(filePath); } } ok = true; if (regExpInclude) { ok = filePath.match(regExpInclude); } if (ok && regExpExclude) { ok = !filePath.match(regExpExclude); } if (ok && (!file.exclusionRegExp || !file.exclusionRegExp.test(fileName))) { files.push(filePath); } } else if (stat.isDirectory() && (!file.exclusionRegExp || !file.exclusionRegExp.test(fileName))) { dirFiles = this.getFilteredFileList(filePath, regExpFilters, makeUnixPaths); files.push.apply(files, dirFiles); } } } return files; //Array }, copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) { //summary: copies files from srcDir to destDir using the regExpFilter to determine if the //file should be copied. Returns a list file name strings of the destinations that were copied. regExpFilter = regExpFilter || /\w/; //Normalize th directory names, but keep front slashes. //path module on windows now returns backslashed paths. srcDir = frontSlash(path.normalize(srcDir)); destDir = frontSlash(path.normalize(destDir)); var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true), copiedFiles = [], i, srcFileName, destFileName; for (i = 0; i < fileNames.length; i++) { srcFileName = fileNames[i]; destFileName = srcFileName.replace(srcDir, destDir); if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) { copiedFiles.push(destFileName); } } return copiedFiles.length ? copiedFiles : null; //Array or null }, copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) { //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred. var parentDir; //logger.trace("Src filename: " + srcFileName); //logger.trace("Dest filename: " + destFileName); //If onlyCopyNew is true, then compare dates and only copy if the src is newer //than dest. if (onlyCopyNew) { if (file.exists(destFileName) && fs.statSync(destFileName).mtime.getTime() >= fs.statSync(srcFileName).mtime.getTime()) { return false; //Boolean } } //Make sure destination dir exists. parentDir = path.dirname(destFileName); if (!file.exists(parentDir)) { mkFullDir(parentDir); } fs.writeFileSync(destFileName, fs.readFileSync(srcFileName, 'binary'), 'binary'); return true; //Boolean }, /** * Renames a file. May fail if "to" already exists or is on another drive. */ renameFile: function (from, to) { return fs.renameSync(from, to); }, /** * Reads a *text* file. */ readFile: function (/*String*/path, /*String?*/encoding) { if (encoding === 'utf-8') { encoding = 'utf8'; } if (!encoding) { encoding = 'utf8'; } var text = fs.readFileSync(path, encoding); //Hmm, would not expect to get A BOM, but it seems to happen, //remove it just in case. if (text.indexOf('\uFEFF') === 0) { text = text.substring(1, text.length); } return text; }, readFileAsync: function (path, encoding) { var d = prim(); try { d.resolve(file.readFile(path, encoding)); } catch (e) { d.reject(e); } return d.promise; }, saveUtf8File: function (/*String*/fileName, /*String*/fileContents) { //summary: saves a *text* file using UTF-8 encoding. file.saveFile(fileName, fileContents, "utf8"); }, saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) { //summary: saves a *text* file. var parentDir; if (encoding === 'utf-8') { encoding = 'utf8'; } if (!encoding) { encoding = 'utf8'; } //Make sure destination directories exist. parentDir = path.dirname(fileName); if (!file.exists(parentDir)) { mkFullDir(parentDir); } fs.writeFileSync(fileName, fileContents, encoding); }, deleteFile: function (/*String*/fileName) { //summary: deletes a file or directory if it exists. var files, i, stat; if (file.exists(fileName)) { stat = fs.lstatSync(fileName); if (stat.isDirectory()) { files = fs.readdirSync(fileName); for (i = 0; i < files.length; i++) { this.deleteFile(path.join(fileName, files[i])); } fs.rmdirSync(fileName); } else { fs.unlinkSync(fileName); } } }, /** * Deletes any empty directories under the given directory. */ deleteEmptyDirs: function (startDir) { var dirFileArray, i, fileName, filePath, stat; if (file.exists(startDir)) { dirFileArray = fs.readdirSync(startDir); for (i = 0; i < dirFileArray.length; i++) { fileName = dirFileArray[i]; filePath = path.join(startDir, fileName); stat = fs.lstatSync(filePath); if (stat.isDirectory()) { file.deleteEmptyDirs(filePath); } } //If directory is now empty, remove it. if (fs.readdirSync(startDir).length === 0) { file.deleteFile(startDir); } } } }; return file; }); } if(env === 'rhino') { //Helper functions to deal with file I/O. /*jslint plusplus: false */ /*global java: false, define: false */ define('rhino/file', ['prim'], function (prim) { var file = { backSlashRegExp: /\\/g, exclusionRegExp: /^\./, getLineSeparator: function () { return file.lineSeparator; }, lineSeparator: java.lang.System.getProperty("line.separator"), //Java String exists: function (fileName) { return (new java.io.File(fileName)).exists(); }, parent: function (fileName) { return file.absPath((new java.io.File(fileName)).getParentFile()); }, normalize: function (fileName) { return file.absPath(fileName); }, isFile: function (path) { return (new java.io.File(path)).isFile(); }, isDirectory: function (path) { return (new java.io.File(path)).isDirectory(); }, /** * Gets the absolute file path as a string, normalized * to using front slashes for path separators. * @param {java.io.File||String} file */ absPath: function (fileObj) { if (typeof fileObj === "string") { fileObj = new java.io.File(fileObj); } return (fileObj.getCanonicalPath() + "").replace(file.backSlashRegExp, "/"); }, getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths, /*boolean?*/startDirIsJavaObject) { //summary: Recurses startDir and finds matches to the files that match regExpFilters.include //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters, //and it will be treated as the "include" case. //Ignores files/directories that start with a period (.) unless exclusionRegExp //is set to another value. var files = [], topDir, regExpInclude, regExpExclude, dirFileArray, i, fileObj, filePath, ok, dirFiles; topDir = startDir; if (!startDirIsJavaObject) { topDir = new java.io.File(startDir); } regExpInclude = regExpFilters.include || regExpFilters; regExpExclude = regExpFilters.exclude || null; if (topDir.exists()) { dirFileArray = topDir.listFiles(); for (i = 0; i < dirFileArray.length; i++) { fileObj = dirFileArray[i]; if (fileObj.isFile()) { filePath = fileObj.getPath(); if (makeUnixPaths) { //Make sure we have a JS string. filePath = String(filePath); if (filePath.indexOf("/") === -1) { filePath = filePath.replace(/\\/g, "/"); } } ok = true; if (regExpInclude) { ok = filePath.match(regExpInclude); } if (ok && regExpExclude) { ok = !filePath.match(regExpExclude); } if (ok && (!file.exclusionRegExp || !file.exclusionRegExp.test(fileObj.getName()))) { files.push(filePath); } } else if (fileObj.isDirectory() && (!file.exclusionRegExp || !file.exclusionRegExp.test(fileObj.getName()))) { dirFiles = this.getFilteredFileList(fileObj, regExpFilters, makeUnixPaths, true); files.push.apply(files, dirFiles); } } } return files; //Array }, copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) { //summary: copies files from srcDir to destDir using the regExpFilter to determine if the //file should be copied. Returns a list file name strings of the destinations that were copied. regExpFilter = regExpFilter || /\w/; var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true), copiedFiles = [], i, srcFileName, destFileName; for (i = 0; i < fileNames.length; i++) { srcFileName = fileNames[i]; destFileName = srcFileName.replace(srcDir, destDir); if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) { copiedFiles.push(destFileName); } } return copiedFiles.length ? copiedFiles : null; //Array or null }, copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) { //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred. var destFile = new java.io.File(destFileName), srcFile, parentDir, srcChannel, destChannel; //logger.trace("Src filename: " + srcFileName); //logger.trace("Dest filename: " + destFileName); //If onlyCopyNew is true, then compare dates and only copy if the src is newer //than dest. if (onlyCopyNew) { srcFile = new java.io.File(srcFileName); if (destFile.exists() && destFile.lastModified() >= srcFile.lastModified()) { return false; //Boolean } } //Make sure destination dir exists. parentDir = destFile.getParentFile(); if (!parentDir.exists()) { if (!parentDir.mkdirs()) { throw "Could not create directory: " + parentDir.getCanonicalPath(); } } //Java's version of copy file. srcChannel = new java.io.FileInputStream(srcFileName).getChannel(); destChannel = new java.io.FileOutputStream(destFileName).getChannel(); destChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); destChannel.close(); return true; //Boolean }, /** * Renames a file. May fail if "to" already exists or is on another drive. */ renameFile: function (from, to) { return (new java.io.File(from)).renameTo((new java.io.File(to))); }, readFile: function (/*String*/path, /*String?*/encoding) { //A file read function that can deal with BOMs encoding = encoding || "utf-8"; var fileObj = new java.io.File(path), input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(fileObj), encoding)), stringBuffer, line; try { stringBuffer = new java.lang.StringBuffer(); line = input.readLine(); // Byte Order Mark (BOM) - The Unicode Standard, version 3.0, page 324 // http://www.unicode.org/faq/utf_bom.html // Note that when we use utf-8, the BOM should appear as "EF BB BF", but it doesn't due to this bug in the JDK: // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058 if (line && line.length() && line.charAt(0) === 0xfeff) { // Eat the BOM, since we've already found the encoding on this file, // and we plan to concatenating this buffer with others; the BOM should // only appear at the top of a file. line = line.substring(1); } while (line !== null) { stringBuffer.append(line); stringBuffer.append(file.lineSeparator); line = input.readLine(); } //Make sure we return a JavaScript string and not a Java string. return String(stringBuffer.toString()); //String } finally { input.close(); } }, readFileAsync: function (path, encoding) { var d = prim(); try { d.resolve(file.readFile(path, encoding)); } catch (e) { d.reject(e); } return d.promise; }, saveUtf8File: function (/*String*/fileName, /*String*/fileContents) { //summary: saves a file using UTF-8 encoding. file.saveFile(fileName, fileContents, "utf-8"); }, saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) { //summary: saves a file. var outFile = new java.io.File(fileName), outWriter, parentDir, os; parentDir = outFile.getAbsoluteFile().getParentFile(); if (!parentDir.exists()) { if (!parentDir.mkdirs()) { throw "Could not create directory: " + parentDir.getAbsolutePath(); } } if (encoding) { outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile), encoding); } else { outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile)); } os = new java.io.BufferedWriter(outWriter); try { //If in Nashorn, need to coerce the JS string to a Java string so that //writer.write method dispatch correctly detects the type. if (typeof importPackage !== 'undefined') { os.write(fileContents); } else { os.write(new java.lang.String(fileContents)); } } finally { os.close(); } }, deleteFile: function (/*String*/fileName) { //summary: deletes a file or directory if it exists. var fileObj = new java.io.File(fileName), files, i; if (fileObj.exists()) { if (fileObj.isDirectory()) { files = fileObj.listFiles(); for (i = 0; i < files.length; i++) { this.deleteFile(files[i]); } } fileObj["delete"](); } }, /** * Deletes any empty directories under the given directory. * The startDirIsJavaObject is private to this implementation's * recursion needs. */ deleteEmptyDirs: function (startDir, startDirIsJavaObject) { var topDir = startDir, dirFileArray, i, fileObj; if (!startDirIsJavaObject) { topDir = new java.io.File(startDir); } if (topDir.exists()) { dirFileArray = topDir.listFiles(); for (i = 0; i < dirFileArray.length; i++) { fileObj = dirFileArray[i]; if (fileObj.isDirectory()) { file.deleteEmptyDirs(fileObj, true); } } //If the directory is empty now, delete it. if (topDir.listFiles().length === 0) { file.deleteFile(String(topDir.getPath())); } } } }; return file; }); } if(env === 'xpconnect') { //Helper functions to deal with file I/O. /*jslint plusplus: false */ /*global define, Components, xpcUtil */ define('xpconnect/file', ['prim'], function (prim) { var file, Cc = Components.classes, Ci = Components.interfaces, //Depends on xpcUtil which is set up in x.js xpfile = xpcUtil.xpfile; function mkFullDir(dirObj) { //1 is DIRECTORY_TYPE, 511 is 0777 permissions if (!dirObj.exists()) { dirObj.create(1, 511); } } file = { backSlashRegExp: /\\/g, exclusionRegExp: /^\./, getLineSeparator: function () { return file.lineSeparator; }, lineSeparator: ('@mozilla.org/windows-registry-key;1' in Cc) ? '\r\n' : '\n', exists: function (fileName) { return xpfile(fileName).exists(); }, parent: function (fileName) { return xpfile(fileName).parent; }, normalize: function (fileName) { return file.absPath(fileName); }, isFile: function (path) { return xpfile(path).isFile(); }, isDirectory: function (path) { return xpfile(path).isDirectory(); }, /** * Gets the absolute file path as a string, normalized * to using front slashes for path separators. * @param {java.io.File||String} file */ absPath: function (fileObj) { if (typeof fileObj === "string") { fileObj = xpfile(fileObj); } return fileObj.path; }, getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths, /*boolean?*/startDirIsObject) { //summary: Recurses startDir and finds matches to the files that match regExpFilters.include //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters, //and it will be treated as the "include" case. //Ignores files/directories that start with a period (.) unless exclusionRegExp //is set to another value. var files = [], topDir, regExpInclude, regExpExclude, dirFileArray, fileObj, filePath, ok, dirFiles; topDir = startDir; if (!startDirIsObject) { topDir = xpfile(startDir); } regExpInclude = regExpFilters.include || regExpFilters; regExpExclude = regExpFilters.exclude || null; if (topDir.exists()) { dirFileArray = topDir.directoryEntries; while (dirFileArray.hasMoreElements()) { fileObj = dirFileArray.getNext().QueryInterface(Ci.nsILocalFile); if (fileObj.isFile()) { filePath = fileObj.path; if (makeUnixPaths) { if (filePath.indexOf("/") === -1) { filePath = filePath.replace(/\\/g, "/"); } } ok = true; if (regExpInclude) { ok = filePath.match(regExpInclude); } if (ok && regExpExclude) { ok = !filePath.match(regExpExclude); } if (ok && (!file.exclusionRegExp || !file.exclusionRegExp.test(fileObj.leafName))) { files.push(filePath); } } else if (fileObj.isDirectory() && (!file.exclusionRegExp || !file.exclusionRegExp.test(fileObj.leafName))) { dirFiles = this.getFilteredFileList(fileObj, regExpFilters, makeUnixPaths, true); files.push.apply(files, dirFiles); } } } return files; //Array }, copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) { //summary: copies files from srcDir to destDir using the regExpFilter to determine if the //file should be copied. Returns a list file name strings of the destinations that were copied. regExpFilter = regExpFilter || /\w/; var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true), copiedFiles = [], i, srcFileName, destFileName; for (i = 0; i < fileNames.length; i += 1) { srcFileName = fileNames[i]; destFileName = srcFileName.replace(srcDir, destDir); if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) { copiedFiles.push(destFileName); } } return copiedFiles.length ? copiedFiles : null; //Array or null }, copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) { //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred. var destFile = xpfile(destFileName), srcFile = xpfile(srcFileName); //logger.trace("Src filename: " + srcFileName); //logger.trace("Dest filename: " + destFileName); //If onlyCopyNew is true, then compare dates and only copy if the src is newer //than dest. if (onlyCopyNew) { if (destFile.exists() && destFile.lastModifiedTime >= srcFile.lastModifiedTime) { return false; //Boolean } } srcFile.copyTo(destFile.parent, destFile.leafName); return true; //Boolean }, /** * Renames a file. May fail if "to" already exists or is on another drive. */ renameFile: function (from, to) { var toFile = xpfile(to); return xpfile(from).moveTo(toFile.parent, toFile.leafName); }, readFile: xpcUtil.readFile, readFileAsync: function (path, encoding) { var d = prim(); try { d.resolve(file.readFile(path, encoding)); } catch (e) { d.reject(e); } return d.promise; }, saveUtf8File: function (/*String*/fileName, /*String*/fileContents) { //summary: saves a file using UTF-8 encoding. file.saveFile(fileName, fileContents, "utf-8"); }, saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) { var outStream, convertStream, fileObj = xpfile(fileName); mkFullDir(fileObj.parent); try { outStream = Cc['@mozilla.org/network/file-output-stream;1'] .createInstance(Ci.nsIFileOutputStream); //438 is decimal for 0777 outStream.init(fileObj, 0x02 | 0x08 | 0x20, 511, 0); convertStream = Cc['@mozilla.org/intl/converter-output-stream;1'] .createInstance(Ci.nsIConverterOutputStream); convertStream.init(outStream, encoding, 0, 0); convertStream.writeString(fileContents); } catch (e) { throw new Error((fileObj && fileObj.path || '') + ': ' + e); } finally { if (convertStream) { convertStream.close(); } if (outStream) { outStream.close(); } } }, deleteFile: function (/*String*/fileName) { //summary: deletes a file or directory if it exists. var fileObj = xpfile(fileName); if (fileObj.exists()) { fileObj.remove(true); } }, /** * Deletes any empty directories under the given directory. * The startDirIsJavaObject is private to this implementation's * recursion needs. */ deleteEmptyDirs: function (startDir, startDirIsObject) { var topDir = startDir, dirFileArray, fileObj; if (!startDirIsObject) { topDir = xpfile(startDir); } if (topDir.exists()) { dirFileArray = topDir.directoryEntries; while (dirFileArray.hasMoreElements()) { fileObj = dirFileArray.getNext().QueryInterface(Ci.nsILocalFile); if (fileObj.isDirectory()) { file.deleteEmptyDirs(fileObj, true); } } //If the directory is empty now, delete it. dirFileArray = topDir.directoryEntries; if (!dirFileArray.hasMoreElements()) { file.deleteFile(topDir.path); } } } }; return file; }); } if(env === 'browser') { /*global process */ define('browser/quit', function () { 'use strict'; return function (code) { }; }); } if(env === 'node') { /*global process */ define('node/quit', function () { 'use strict'; return function (code) { var draining = 0; var exit = function () { if (draining === 0) { process.exit(code); } else { draining -= 1; } }; if (process.stdout.bufferSize) { draining += 1; process.stdout.once('drain', exit); } if (process.stderr.bufferSize) { draining += 1; process.stderr.once('drain', exit); } exit(); }; }); } if(env === 'rhino') { /*global quit */ define('rhino/quit', function () { 'use strict'; return function (code) { return quit(code); }; }); } if(env === 'xpconnect') { /*global quit */ define('xpconnect/quit', function () { 'use strict'; return function (code) { return quit(code); }; }); } if(env === 'browser') { /*jslint strict: false */ /*global define: false, console: false */ define('browser/print', function () { function print(msg) { console.log(msg); } return print; }); } if(env === 'node') { /*jslint strict: false */ /*global define: false, console: false */ define('node/print', function () { function print(msg) { console.log(msg); } return print; }); } if(env === 'rhino') { /*jslint strict: false */ /*global define: false, print: false */ define('rhino/print', function () { return print; }); } if(env === 'xpconnect') { /*jslint strict: false */ /*global define: false, print: false */ define('xpconnect/print', function () { return print; }); } /*jslint nomen: false, strict: false */ /*global define: false */ define('logger', ['env!env/print'], function (print) { var logger = { TRACE: 0, INFO: 1, WARN: 2, ERROR: 3, SILENT: 4, level: 0, logPrefix: "", logLevel: function( level ) { this.level = level; }, trace: function (message) { if (this.level <= this.TRACE) { this._print(message); } }, info: function (message) { if (this.level <= this.INFO) { this._print(message); } }, warn: function (message) { if (this.level <= this.WARN) { this._print(message); } }, error: function (message) { if (this.level <= this.ERROR) { this._print(message); } }, _print: function (message) { this._sysPrint((this.logPrefix ? (this.logPrefix + " ") : "") + message); }, _sysPrint: function (message) { print(message); } }; return logger; }); //Just a blank file to use when building the optimizer with the optimizer, //so that the build does not attempt to inline some env modules, //like Node's fs and path. /* Copyright (c) jQuery Foundation, Inc. and Contributors, All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ (function (root, factory) { 'use strict'; // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, // Rhino, and plain browser loading. /* istanbul ignore next */ if (typeof define === 'function' && define.amd) { define('esprima', ['exports'], factory); } else if (typeof exports !== 'undefined') { factory(exports); } else { factory((root.esprima = {})); } }(this, function (exports) { 'use strict'; var Token, TokenName, FnExprTokens, Syntax, PlaceHolders, Messages, Regex, source, strict, index, lineNumber, lineStart, hasLineTerminator, lastIndex, lastLineNumber, lastLineStart, startIndex, startLineNumber, startLineStart, scanning, length, lookahead, state, extra, isBindingElement, isAssignmentTarget, firstCoverInitializedNameError; Token = { BooleanLiteral: 1, EOF: 2, Identifier: 3, Keyword: 4, NullLiteral: 5, NumericLiteral: 6, Punctuator: 7, StringLiteral: 8, RegularExpression: 9, Template: 10 }; TokenName = {}; TokenName[Token.BooleanLiteral] = 'Boolean'; TokenName[Token.EOF] = '<end>'; TokenName[Token.Identifier] = 'Identifier'; TokenName[Token.Keyword] = 'Keyword'; TokenName[Token.NullLiteral] = 'Null'; TokenName[Token.NumericLiteral] = 'Numeric'; TokenName[Token.Punctuator] = 'Punctuator'; TokenName[Token.StringLiteral] = 'String'; TokenName[Token.RegularExpression] = 'RegularExpression'; TokenName[Token.Template] = 'Template'; // A function following one of those tokens is an expression. FnExprTokens = ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new', 'return', 'case', 'delete', 'throw', 'void', // assignment operators '=', '+=', '-=', '*=', '/=', '%=', '<<=', '>>=', '>>>=', '&=', '|=', '^=', ',', // binary/unary operators '+', '-', '*', '/', '%', '++', '--', '<<', '>>', '>>>', '&', '|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=', '<=', '<', '>', '!=', '!==']; Syntax = { AssignmentExpression: 'AssignmentExpression', AssignmentPattern: 'AssignmentPattern', ArrayExpression: 'ArrayExpression', ArrayPattern: 'ArrayPattern', ArrowFunctionExpression: 'ArrowFunctionExpression', BlockStatement: 'BlockStatement', BinaryExpression: 'BinaryExpression', BreakStatement: 'BreakStatement', CallExpression: 'CallExpression', CatchClause: 'CatchClause', ClassBody: 'ClassBody', ClassDeclaration: 'ClassDeclaration', ClassExpression: 'ClassExpression', ConditionalExpression: 'ConditionalExpression', ContinueStatement: 'ContinueStatement', DoWhileStatement: 'DoWhileStatement', DebuggerStatement: 'DebuggerStatement', EmptyStatement: 'EmptyStatement', ExportAllDeclaration: 'ExportAllDeclaration', ExportDefaultDeclaration: 'ExportDefaultDeclaration', ExportNamedDeclaration: 'ExportNamedDeclaration', ExportSpecifier: 'ExportSpecifier', ExpressionStatement: 'ExpressionStatement', ForStatement: 'ForStatement', ForOfStatement: 'ForOfStatement', ForInStatement: 'ForInStatement', FunctionDeclaration: 'FunctionDeclaration', FunctionExpression: 'FunctionExpression', Identifier: 'Identifier', IfStatement: 'IfStatement', ImportDeclaration: 'ImportDeclaration', ImportDefaultSpecifier: 'ImportDefaultSpecifier', ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', ImportSpecifier: 'ImportSpecifier', Literal: 'Literal', LabeledStatement: 'LabeledStatement', LogicalExpression: 'LogicalExpression', MemberExpression: 'MemberExpression', MetaProperty: 'MetaProperty', MethodDefinition: 'MethodDefinition', NewExpression: 'NewExpression', ObjectExpression: 'ObjectExpression', ObjectPattern: 'ObjectPattern', Program: 'Program', Property: 'Property', RestElement: 'RestElement', ReturnStatement: 'ReturnStatement', SequenceExpression: 'SequenceExpression', SpreadElement: 'SpreadElement', Super: 'Super', SwitchCase: 'SwitchCase', SwitchStatement: 'SwitchStatement', TaggedTemplateExpression: 'TaggedTemplateExpression', TemplateElement: 'TemplateElement', TemplateLiteral: 'TemplateLiteral', ThisExpression: 'ThisExpression', ThrowStatement: 'ThrowStatement', TryStatement: 'TryStatement', UnaryExpression: 'UnaryExpression', UpdateExpression: 'UpdateExpression', VariableDeclaration: 'VariableDeclaration', VariableDeclarator: 'VariableDeclarator', WhileStatement: 'WhileStatement', WithStatement: 'WithStatement', YieldExpression: 'YieldExpression' }; PlaceHolders = { ArrowParameterPlaceHolder: 'ArrowParameterPlaceHolder' }; // Error messages should be identical to V8. Messages = { UnexpectedToken: 'Unexpected token %0', UnexpectedNumber: 'Unexpected number', UnexpectedString: 'Unexpected string', UnexpectedIdentifier: 'Unexpected identifier', UnexpectedReserved: 'Unexpected reserved word', UnexpectedTemplate: 'Unexpected quasi %0', UnexpectedEOS: 'Unexpected end of input', NewlineAfterThrow: 'Illegal newline after throw', InvalidRegExp: 'Invalid regular expression', UnterminatedRegExp: 'Invalid regular expression: missing /', InvalidLHSInAssignment: 'Invalid left-hand side in assignment', InvalidLHSInForIn: 'Invalid left-hand side in for-in', InvalidLHSInForLoop: 'Invalid left-hand side in for-loop', MultipleDefaultsInSwitch: 'More than one default clause in switch statement', NoCatchOrFinally: 'Missing catch or finally after try', UnknownLabel: 'Undefined label \'%0\'', Redeclaration: '%0 \'%1\' has already been declared', IllegalContinue: 'Illegal continue statement', IllegalBreak: 'Illegal break statement', IllegalReturn: 'Illegal return statement', StrictModeWith: 'Strict mode code may not include a with statement', StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode', StrictVarName: 'Variable name may not be eval or arguments in strict mode', StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode', StrictParamDupe: 'Strict mode function may not have duplicate parameter names', StrictFunctionName: 'Function name may not be eval or arguments in strict mode', StrictOctalLiteral: 'Octal literals are not allowed in strict mode.', StrictDelete: 'Delete of an unqualified identifier in strict mode.', StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode', StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode', StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode', StrictReservedWord: 'Use of future reserved word in strict mode', TemplateOctalLiteral: 'Octal literals are not allowed in template strings.', ParameterAfterRestParameter: 'Rest parameter must be last formal parameter', DefaultRestParameter: 'Unexpected token =', ObjectPatternAsRestParameter: 'Unexpected token {', DuplicateProtoProperty: 'Duplicate __proto__ fields are not allowed in object literals', ConstructorSpecialMethod: 'Class constructor may not be an accessor', DuplicateConstructor: 'A class may only have one constructor', StaticPrototype: 'Classes may not have static property named prototype', MissingFromClause: 'Unexpected token', NoAsAfterImportNamespace: 'Unexpected token', InvalidModuleSpecifier: 'Unexpected token', IllegalImportDeclaration: 'Unexpected token', IllegalExportDeclaration: 'Unexpected token', DuplicateBinding: 'Duplicate binding %0' }; // See also tools/generate-unicode-regex.js. Regex = { // ECMAScript 6/Unicode v7.0.0 NonAsciiIdentifierStart: NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDE00-\uDE11\uDE13-\uDE2B\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDE00-\uDE2F\uDE44\uDE80-\uDEAA]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]/, // ECMAScript 6/Unicode v7.0.0 NonAsciiIdentifierPart: NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0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A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA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802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDD0-\uDDDA\uDE00-\uDE11\uDE13-\uDE37\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF01-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\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ensure the condition is true, otherwise throw an error. // This is only to have a better contract semantic, i.e. another safety net // to catch a logic error. The condition shall be fulfilled in normal case. // Do NOT use this to enforce a certain condition on any user input. function assert(condition, message) { /* istanbul ignore if */ if (!condition) { throw new Error('ASSERT: ' + message); } } function isDecimalDigit(ch) { return (ch >= 0x30 && ch <= 0x39); // 0..9 } function isHexDigit(ch) { return '0123456789abcdefABCDEF'.indexOf(ch) >= 0; } function isOctalDigit(ch) { return '01234567'.indexOf(ch) >= 0; } function octalToDecimal(ch) { // \0 is not octal escape sequence var octal = (ch !== '0'), code = '01234567'.indexOf(ch); if (index < length && isOctalDigit(source[index])) { octal = true; code = code * 8 + '01234567'.indexOf(source[index++]); // 3 digits are only allowed when string starts // with 0, 1, 2, 3 if ('0123'.indexOf(ch) >= 0 && index < length && isOctalDigit(source[index])) { code = code * 8 + '01234567'.indexOf(source[index++]); } } return { code: code, octal: octal }; } // ECMA-262 11.2 White Space function isWhiteSpace(ch) { return (ch === 0x20) || (ch === 0x09) || (ch === 0x0B) || (ch === 0x0C) || (ch === 0xA0) || (ch >= 0x1680 && [0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(ch) >= 0); } // ECMA-262 11.3 Line Terminators function isLineTerminator(ch) { return (ch === 0x0A) || (ch === 0x0D) || (ch === 0x2028) || (ch === 0x2029); } // ECMA-262 11.6 Identifier Names and Identifiers function fromCodePoint(cp) { return (cp < 0x10000) ? String.fromCharCode(cp) : String.fromCharCode(0xD800 + ((cp - 0x10000) >> 10)) + String.fromCharCode(0xDC00 + ((cp - 0x10000) & 1023)); } function isIdentifierStart(ch) { return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore) (ch >= 0x41 && ch <= 0x5A) || // A..Z (ch >= 0x61 && ch <= 0x7A) || // a..z (ch === 0x5C) || // \ (backslash) ((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch))); } function isIdentifierPart(ch) { return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore) (ch >= 0x41 && ch <= 0x5A) || // A..Z (ch >= 0x61 && ch <= 0x7A) || // a..z (ch >= 0x30 && ch <= 0x39) || // 0..9 (ch === 0x5C) || // \ (backslash) ((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch))); } // ECMA-262 11.6.2.2 Future Reserved Words function isFutureReservedWord(id) { switch (id) { case 'enum': case 'export': case 'import': case 'super': return true; default: return false; } } function isStrictModeReservedWord(id) { switch (id) { case 'implements': case 'interface': case 'package': case 'private': case 'protected': case 'public': case 'static': case 'yield': case 'let': return true; default: return false; } } function isRestrictedWord(id) { return id === 'eval' || id === 'arguments'; } // ECMA-262 11.6.2.1 Keywords function isKeyword(id) { switch (id.length) { case 2: return (id === 'if') || (id === 'in') || (id === 'do'); case 3: return (id === 'var') || (id === 'for') || (id === 'new') || (id === 'try') || (id === 'let'); case 4: return (id === 'this') || (id === 'else') || (id === 'case') || (id === 'void') || (id === 'with') || (id === 'enum'); case 5: return (id === 'while') || (id === 'break') || (id === 'catch') || (id === 'throw') || (id === 'const') || (id === 'yield') || (id === 'class') || (id === 'super'); case 6: return (id === 'return') || (id === 'typeof') || (id === 'delete') || (id === 'switch') || (id === 'export') || (id === 'import'); case 7: return (id === 'default') || (id === 'finally') || (id === 'extends'); case 8: return (id === 'function') || (id === 'continue') || (id === 'debugger'); case 10: return (id === 'instanceof'); default: return false; } } // ECMA-262 11.4 Comments function addComment(type, value, start, end, loc) { var comment; assert(typeof start === 'number', 'Comment must have valid position'); state.lastCommentStart = start; comment = { type: type, value: value }; if (extra.range) { comment.range = [start, end]; } if (extra.loc) { comment.loc = loc; } extra.comments.push(comment); if (extra.attachComment) { extra.leadingComments.push(comment); extra.trailingComments.push(comment); } if (extra.tokenize) { comment.type = comment.type + 'Comment'; if (extra.delegate) { comment = extra.delegate(comment); } extra.tokens.push(comment); } } function skipSingleLineComment(offset) { var start, loc, ch, comment; start = index - offset; loc = { start: { line: lineNumber, column: index - lineStart - offset } }; while (index < length) { ch = source.charCodeAt(index); ++index; if (isLineTerminator(ch)) { hasLineTerminator = true; if (extra.comments) { comment = source.slice(start + offset, index - 1); loc.end = { line: lineNumber, column: index - lineStart - 1 }; addComment('Line', comment, start, index - 1, loc); } if (ch === 13 && source.charCodeAt(index) === 10) { ++index; } ++lineNumber; lineStart = index; return; } } if (extra.comments) { comment = source.slice(start + offset, index); loc.end = { line: lineNumber, column: index - lineStart }; addComment('Line', comment, start, index, loc); } } function skipMultiLineComment() { var start, loc, ch, comment; if (extra.comments) { start = index - 2; loc = { start: { line: lineNumber, column: index - lineStart - 2 } }; } while (index < length) { ch = source.charCodeAt(index); if (isLineTerminator(ch)) { if (ch === 0x0D && source.charCodeAt(index + 1) === 0x0A) { ++index; } hasLineTerminator = true; ++lineNumber; ++index; lineStart = index; } else if (ch === 0x2A) { // Block comment ends with '*/'. if (source.charCodeAt(index + 1) === 0x2F) { ++index; ++index; if (extra.comments) { comment = source.slice(start + 2, index - 2); loc.end = { line: lineNumber, column: index - lineStart }; addComment('Block', comment, start, index, loc); } return; } ++index; } else { ++index; } } // Ran off the end of the file - the whole thing is a comment if (extra.comments) { loc.end = { line: lineNumber, column: index - lineStart }; comment = source.slice(start + 2, index); addComment('Block', comment, start, index, loc); } tolerateUnexpectedToken(); } function skipComment() { var ch, start; hasLineTerminator = false; start = (index === 0); while (index < length) { ch = source.charCodeAt(index); if (isWhiteSpace(ch)) { ++index; } else if (isLineTerminator(ch)) { hasLineTerminator = true; ++index; if (ch === 0x0D && source.charCodeAt(index) === 0x0A) { ++index; } ++lineNumber; lineStart = index; start = true; } else if (ch === 0x2F) { // U+002F is '/' ch = source.charCodeAt(index + 1); if (ch === 0x2F) { ++index; ++index; skipSingleLineComment(2); start = true; } else if (ch === 0x2A) { // U+002A is '*' ++index; ++index; skipMultiLineComment(); } else { break; } } else if (start && ch === 0x2D) { // U+002D is '-' // U+003E is '>' if ((source.charCodeAt(index + 1) === 0x2D) && (source.charCodeAt(index + 2) === 0x3E)) { // '-->' is a single-line comment index += 3; skipSingleLineComment(3); } else { break; } } else if (ch === 0x3C) { // U+003C is '<' if (source.slice(index + 1, index + 4) === '!--') { ++index; // `<` ++index; // `!` ++index; // `-` ++index; // `-` skipSingleLineComment(4); } else { break; } } else { break; } } } function scanHexEscape(prefix) { var i, len, ch, code = 0; len = (prefix === 'u') ? 4 : 2; for (i = 0; i < len; ++i) { if (index < length && isHexDigit(source[index])) { ch = source[index++]; code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); } else { return ''; } } return String.fromCharCode(code); } function scanUnicodeCodePointEscape() { var ch, code; ch = source[index]; code = 0; // At least, one hex digit is required. if (ch === '}') { throwUnexpectedToken(); } while (index < length) { ch = source[index++]; if (!isHexDigit(ch)) { break; } code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); } if (code > 0x10FFFF || ch !== '}') { throwUnexpectedToken(); } return fromCodePoint(code); } function codePointAt(i) { var cp, first, second; cp = source.charCodeAt(i); if (cp >= 0xD800 && cp <= 0xDBFF) { second = source.charCodeAt(i + 1); if (second >= 0xDC00 && second <= 0xDFFF) { first = cp; cp = (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; } } return cp; } function getComplexIdentifier() { var cp, ch, id; cp = codePointAt(index); id = fromCodePoint(cp); index += id.length; // '\u' (U+005C, U+0075) denotes an escaped character. if (cp === 0x5C) { if (source.charCodeAt(index) !== 0x75) { throwUnexpectedToken(); } ++index; if (source[index] === '{') { ++index; ch = scanUnicodeCodePointEscape(); } else { ch = scanHexEscape('u'); cp = ch.charCodeAt(0); if (!ch || ch === '\\' || !isIdentifierStart(cp)) { throwUnexpectedToken(); } } id = ch; } while (index < length) { cp = codePointAt(index); if (!isIdentifierPart(cp)) { break; } ch = fromCodePoint(cp); id += ch; index += ch.length; // '\u' (U+005C, U+0075) denotes an escaped character. if (cp === 0x5C) { id = id.substr(0, id.length - 1); if (source.charCodeAt(index) !== 0x75) { throwUnexpectedToken(); } ++index; if (source[index] === '{') { ++index; ch = scanUnicodeCodePointEscape(); } else { ch = scanHexEscape('u'); cp = ch.charCodeAt(0); if (!ch || ch === '\\' || !isIdentifierPart(cp)) { throwUnexpectedToken(); } } id += ch; } } return id; } function getIdentifier() { var start, ch; start = index++; while (index < length) { ch = source.charCodeAt(index); if (ch === 0x5C) { // Blackslash (U+005C) marks Unicode escape sequence. index = start; return getComplexIdentifier(); } else if (ch >= 0xD800 && ch < 0xDFFF) { // Need to handle surrogate pairs. index = start; return getComplexIdentifier(); } if (isIdentifierPart(ch)) { ++index; } else { break; } } return source.slice(start, index); } function scanIdentifier() { var start, id, type; start = index; // Backslash (U+005C) starts an escaped character. id = (source.charCodeAt(index) === 0x5C) ? getComplexIdentifier() : getIdentifier(); // There is no keyword or literal with only one character. // Thus, it must be an identifier. if (id.length === 1) { type = Token.Identifier; } else if (isKeyword(id)) { type = Token.Keyword; } else if (id === 'null') { type = Token.NullLiteral; } else if (id === 'true' || id === 'false') { type = Token.BooleanLiteral; } else { type = Token.Identifier; } return { type: type, value: id, lineNumber: lineNumber, lineStart: lineStart, start: start, end: index }; } // ECMA-262 11.7 Punctuators function scanPunctuator() { var token, str; token = { type: Token.Punctuator, value: '', lineNumber: lineNumber, lineStart: lineStart, start: index, end: index }; // Check for most common single-character punctuators. str = source[index]; switch (str) { case '(': if (extra.tokenize) { extra.openParenToken = extra.tokenValues.length; } ++index; break; case '{': if (extra.tokenize) { extra.openCurlyToken = extra.tokenValues.length; } state.curlyStack.push('{'); ++index; break; case '.': ++index; if (source[index] === '.' && source[index + 1] === '.') { // Spread operator: ... index += 2; str = '...'; } break; case '}': ++index; state.curlyStack.pop(); break; case ')': case ';': case ',': case '[': case ']': case ':': case '?': case '~': ++index; break; default: // 4-character punctuator. str = source.substr(index, 4); if (str === '>>>=') { index += 4; } else { // 3-character punctuators. str = str.substr(0, 3); if (str === '===' || str === '!==' || str === '>>>' || str === '<<=' || str === '>>=') { index += 3; } else { // 2-character punctuators. str = str.substr(0, 2); if (str === '&&' || str === '||' || str === '==' || str === '!=' || str === '+=' || str === '-=' || str === '*=' || str === '/=' || str === '++' || str === '--' || str === '<<' || str === '>>' || str === '&=' || str === '|=' || str === '^=' || str === '%=' || str === '<=' || str === '>=' || str === '=>') { index += 2; } else { // 1-character punctuators. str = source[index]; if ('<>=!+-*%&|^/'.indexOf(str) >= 0) { ++index; } } } } } if (index === token.start) { throwUnexpectedToken(); } token.end = index; token.value = str; return token; } // ECMA-262 11.8.3 Numeric Literals function scanHexLiteral(start) { var number = ''; while (index < length) { if (!isHexDigit(source[index])) { break; } number += source[index++]; } if (number.length === 0) { throwUnexpectedToken(); } if (isIdentifierStart(source.charCodeAt(index))) { throwUnexpectedToken(); } return { type: Token.NumericLiteral, value: parseInt('0x' + number, 16), lineNumber: lineNumber, lineStart: lineStart, start: start, end: index }; } function scanBinaryLiteral(start) { var ch, number; number = ''; while (index < length) { ch = source[index]; if (ch !== '0' && ch !== '1') { break; } number += source[index++]; } if (number.length === 0) { // only 0b or 0B throwUnexpectedToken(); } if (index < length) { ch = source.charCodeAt(index); /* istanbul ignore else */ if (isIdentifierStart(ch) || isDecimalDigit(ch)) { throwUnexpectedToken(); } } return { type: Token.NumericLiteral, value: parseInt(number, 2), lineNumber: lineNumber, lineStart: lineStart, start: start, end: index }; } function scanOctalLiteral(prefix, start) { var number, octal; if (isOctalDigit(prefix)) { octal = true; number = '0' + source[index++]; } else { octal = false; ++index; number = ''; } while (index < length) { if (!isOctalDigit(source[index])) { break; } number += source[index++]; } if (!octal && number.length === 0) { // only 0o or 0O throwUnexpectedToken(); } if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) { throwUnexpectedToken(); } return { type: Token.NumericLiteral, value: parseInt(number, 8), octal: octal, lineNumber: lineNumber, lineStart: lineStart, start: start, end: index }; } function isImplicitOctalLiteral() { var i, ch; // Implicit octal, unless there is a non-octal digit. // (Annex B.1.1 on Numeric Literals) for (i = index + 1; i < length; ++i) { ch = source[i]; if (ch === '8' || ch === '9') { return false; } if (!isOctalDigit(ch)) { return true; } } return true; } function scanNumericLiteral() { var number, start, ch; ch = source[index]; assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'), 'Numeric literal must start with a decimal digit or a decimal point'); start = index; number = ''; if (ch !== '.') { number = source[index++]; ch = source[index]; // Hex number starts with '0x'. // Octal number starts with '0'. // Octal number in ES6 starts with '0o'. // Binary number in ES6 starts with '0b'. if (number === '0') { if (ch === 'x' || ch === 'X') { ++index; return scanHexLiteral(start); } if (ch === 'b' || ch === 'B') { ++index; return scanBinaryLiteral(start); } if (ch === 'o' || ch === 'O') { return scanOctalLiteral(ch, start); } if (isOctalDigit(ch)) { if (isImplicitOctalLiteral()) { return scanOctalLiteral(ch, start); } } } while (isDecimalDigit(source.charCodeAt(index))) { number += source[index++]; } ch = source[index]; } if (ch === '.') { number += source[index++]; while (isDecimalDigit(source.charCodeAt(index))) { number += source[index++]; } ch = source[index]; } if (ch === 'e' || ch === 'E') { number += source[index++]; ch = source[index]; if (ch === '+' || ch === '-') { number += source[index++]; } if (isDecimalDigit(source.charCodeAt(index))) { while (isDecimalDigit(source.charCodeAt(index))) { number += source[index++]; } } else { throwUnexpectedToken(); } } if (isIdentifierStart(source.charCodeAt(index))) { throwUnexpectedToken(); } return { type: Token.NumericLiteral, value: parseFloat(number), lineNumber: lineNumber, lineStart: lineStart, start: start, end: index }; } // ECMA-262 11.8.4 String Literals function scanStringLiteral() { var str = '', quote, start, ch, unescaped, octToDec, octal = false; quote = source[index]; assert((quote === '\'' || quote === '"'), 'String literal must starts with a quote'); start = index; ++index; while (index < length) { ch = source[index++]; if (ch === quote) { quote = ''; break; } else if (ch === '\\') { ch = source[index++]; if (!ch || !isLineTerminator(ch.charCodeAt(0))) { switch (ch) { case 'u': case 'x': if (source[index] === '{') { ++index; str += scanUnicodeCodePointEscape(); } else { unescaped = scanHexEscape(ch); if (!unescaped) { throw throwUnexpectedToken(); } str += unescaped; } break; case 'n': str += '\n'; break; case 'r': str += '\r'; break; case 't': str += '\t'; break; case 'b': str += '\b'; break; case 'f': str += '\f'; break; case 'v': str += '\x0B'; break; case '8': case '9': str += ch; tolerateUnexpectedToken(); break; default: if (isOctalDigit(ch)) { octToDec = octalToDecimal(ch); octal = octToDec.octal || octal; str += String.fromCharCode(octToDec.code); } else { str += ch; } break; } } else { ++lineNumber; if (ch === '\r' && source[index] === '\n') { ++index; } lineStart = index; } } else if (isLineTerminator(ch.charCodeAt(0))) { break; } else { str += ch; } } if (quote !== '') { index = start; throwUnexpectedToken(); } return { type: Token.StringLiteral, value: str, octal: octal, lineNumber: startLineNumber, lineStart: startLineStart, start: start, end: index }; } // ECMA-262 11.8.6 Template Literal Lexical Components function scanTemplate() { var cooked = '', ch, start, rawOffset, terminated, head, tail, restore, unescaped; terminated = false; tail = false; start = index; head = (source[index] === '`'); rawOffset = 2; ++index; while (index < length) { ch = source[index++]; if (ch === '`') { rawOffset = 1; tail = true; terminated = true; break; } else if (ch === '$') { if (source[index] === '{') { state.curlyStack.push('${'); ++index; terminated = true; break; } cooked += ch; } else if (ch === '\\') { ch = source[index++]; if (!isLineTerminator(ch.charCodeAt(0))) { switch (ch) { case 'n': cooked += '\n'; break; case 'r': cooked += '\r'; break; case 't': cooked += '\t'; break; case 'u': case 'x': if (source[index] === '{') { ++index; cooked += scanUnicodeCodePointEscape(); } else { restore = index; unescaped = scanHexEscape(ch); if (unescaped) { cooked += unescaped; } else { index = restore; cooked += ch; } } break; case 'b': cooked += '\b'; break; case 'f': cooked += '\f'; break; case 'v': cooked += '\v'; break; default: if (ch === '0') { if (isDecimalDigit(source.charCodeAt(index))) { // Illegal: \01 \02 and so on throwError(Messages.TemplateOctalLiteral); } cooked += '\0'; } else if (isOctalDigit(ch)) { // Illegal: \1 \2 throwError(Messages.TemplateOctalLiteral); } else { cooked += ch; } break; } } else { ++lineNumber; if (ch === '\r' && source[index] === '\n') { ++index; } lineStart = index; } } else if (isLineTerminator(ch.charCodeAt(0))) { ++lineNumber; if (ch === '\r' && source[index] === '\n') { ++index; } lineStart = index; cooked += '\n'; } else { cooked += ch; } } if (!terminated) { throwUnexpectedToken(); } if (!head) { state.curlyStack.pop(); } return { type: Token.Template, value: { cooked: cooked, raw: source.slice(start + 1, index - rawOffset) }, head: head, tail: tail, lineNumber: lineNumber, lineStart: lineStart, start: start, end: index }; } // ECMA-262 11.8.5 Regular Expression Literals function testRegExp(pattern, flags) { // The BMP character to use as a replacement for astral symbols when // translating an ES6 "u"-flagged pattern to an ES5-compatible // approximation. // Note: replacing with '\uFFFF' enables false positives in unlikely // scenarios. For example, `[\u{1044f}-\u{10440}]` is an invalid // pattern that would not be detected by this substitution. var astralSubstitute = '\uFFFF', tmp = pattern; if (flags.indexOf('u') >= 0) { tmp = tmp // Replace every Unicode escape sequence with the equivalent // BMP character or a constant ASCII code point in the case of // astral symbols. (See the above note on `astralSubstitute` // for more information.) .replace(/\\u\{([0-9a-fA-F]+)\}|\\u([a-fA-F0-9]{4})/g, function ($0, $1, $2) { var codePoint = parseInt($1 || $2, 16); if (codePoint > 0x10FFFF) { throwUnexpectedToken(null, Messages.InvalidRegExp); } if (codePoint <= 0xFFFF) { return String.fromCharCode(codePoint); } return astralSubstitute; }) // Replace each paired surrogate with a single ASCII symbol to // avoid throwing on regular expressions that are only valid in // combination with the "u" flag. .replace( /[\uD800-\uDBFF][\uDC00-\uDFFF]/g, astralSubstitute ); } // First, detect invalid regular expressions. try { RegExp(tmp); } catch (e) { throwUnexpectedToken(null, Messages.InvalidRegExp); } // Return a regular expression object for this pattern-flag pair, or // `null` in case the current environment doesn't support the flags it // uses. try { return new RegExp(pattern, flags); } catch (exception) { return null; } } function scanRegExpBody() { var ch, str, classMarker, terminated, body; ch = source[index]; assert(ch === '/', 'Regular expression literal must start with a slash'); str = source[index++]; classMarker = false; terminated = false; while (index < length) { ch = source[index++]; str += ch; if (ch === '\\') { ch = source[index++]; // ECMA-262 7.8.5 if (isLineTerminator(ch.charCodeAt(0))) { throwUnexpectedToken(null, Messages.UnterminatedRegExp); } str += ch; } else if (isLineTerminator(ch.charCodeAt(0))) { throwUnexpectedToken(null, Messages.UnterminatedRegExp); } else if (classMarker) { if (ch === ']') { classMarker = false; } } else { if (ch === '/') { terminated = true; break; } else if (ch === '[') { classMarker = true; } } } if (!terminated) { throwUnexpectedToken(null, Messages.UnterminatedRegExp); } // Exclude leading and trailing slash. body = str.substr(1, str.length - 2); return { value: body, literal: str }; } function scanRegExpFlags() { var ch, str, flags, restore; str = ''; flags = ''; while (index < length) { ch = source[index]; if (!isIdentifierPart(ch.charCodeAt(0))) { break; } ++index; if (ch === '\\' && index < length) { ch = source[index]; if (ch === 'u') { ++index; restore = index; ch = scanHexEscape('u'); if (ch) { flags += ch; for (str += '\\u'; restore < index; ++restore) { str += source[restore]; } } else { index = restore; flags += 'u'; str += '\\u'; } tolerateUnexpectedToken(); } else { str += '\\'; tolerateUnexpectedToken(); } } else { flags += ch; str += ch; } } return { value: flags, literal: str }; } function scanRegExp() { var start, body, flags, value; scanning = true; lookahead = null; skipComment(); start = index; body = scanRegExpBody(); flags = scanRegExpFlags(); value = testRegExp(body.value, flags.value); scanning = false; if (extra.tokenize) { return { type: Token.RegularExpression, value: value, regex: { pattern: body.value, flags: flags.value }, lineNumber: lineNumber, lineStart: lineStart, start: start, end: index }; } return { literal: body.literal + flags.literal, value: value, regex: { pattern: body.value, flags: flags.value }, start: start, end: index }; } function collectRegex() { var pos, loc, regex, token; skipComment(); pos = index; loc = { start: { line: lineNumber, column: index - lineStart } }; regex = scanRegExp(); loc.end = { line: lineNumber, column: index - lineStart }; /* istanbul ignore next */ if (!extra.tokenize) { // Pop the previous token, which is likely '/' or '/=' if (extra.tokens.length > 0) { token = extra.tokens[extra.tokens.length - 1]; if (token.range[0] === pos && token.type === 'Punctuator') { if (token.value === '/' || token.value === '/=') { extra.tokens.pop(); } } } extra.tokens.push({ type: 'RegularExpression', value: regex.literal, regex: regex.regex, range: [pos, index], loc: loc }); } return regex; } function isIdentifierName(token) { return token.type === Token.Identifier || token.type === Token.Keyword || token.type === Token.BooleanLiteral || token.type === Token.NullLiteral; } // Using the following algorithm: // https://github.com/mozilla/sweet.js/wiki/design function advanceSlash() { var regex, previous, check; function testKeyword(value) { return value && (value.length > 1) && (value[0] >= 'a') && (value[0] <= 'z'); } previous = extra.tokenValues[extra.tokens.length - 1]; regex = (previous !== null); switch (previous) { case 'this': case ']': regex = false; break; case ')': check = extra.tokenValues[extra.openParenToken - 1]; regex = (check === 'if' || check === 'while' || check === 'for' || check === 'with'); break; case '}': // Dividing a function by anything makes little sense, // but we have to check for that. regex = false; if (testKeyword(extra.tokenValues[extra.openCurlyToken - 3])) { // Anonymous function, e.g. function(){} /42 check = extra.tokenValues[extra.openCurlyToken - 4]; regex = check ? (FnExprTokens.indexOf(check) < 0) : false; } else if (testKeyword(extra.tokenValues[extra.openCurlyToken - 4])) { // Named function, e.g. function f(){} /42/ check = extra.tokenValues[extra.openCurlyToken - 5]; regex = check ? (FnExprTokens.indexOf(check) < 0) : true; } } return regex ? collectRegex() : scanPunctuator(); } function advance() { var cp, token; if (index >= length) { return { type: Token.EOF, lineNumber: lineNumber, lineStart: lineStart, start: index, end: index }; } cp = source.charCodeAt(index); if (isIdentifierStart(cp)) { token = scanIdentifier(); if (strict && isStrictModeReservedWord(token.value)) { token.type = Token.Keyword; } return token; } // Very common: ( and ) and ; if (cp === 0x28 || cp === 0x29 || cp === 0x3B) { return scanPunctuator(); } // String literal starts with single quote (U+0027) or double quote (U+0022). if (cp === 0x27 || cp === 0x22) { return scanStringLiteral(); } // Dot (.) U+002E can also start a floating-point number, hence the need // to check the next character. if (cp === 0x2E) { if (isDecimalDigit(source.charCodeAt(index + 1))) { return scanNumericLiteral(); } return scanPunctuator(); } if (isDecimalDigit(cp)) { return scanNumericLiteral(); } // Slash (/) U+002F can also start a regex. if (extra.tokenize && cp === 0x2F) { return advanceSlash(); } // Template literals start with ` (U+0060) for template head // or } (U+007D) for template middle or template tail. if (cp === 0x60 || (cp === 0x7D && state.curlyStack[state.curlyStack.length - 1] === '${')) { return scanTemplate(); } // Possible identifier start in a surrogate pair. if (cp >= 0xD800 && cp < 0xDFFF) { cp = codePointAt(index); if (isIdentifierStart(cp)) { return scanIdentifier(); } } return scanPunctuator(); } function collectToken() { var loc, token, value, entry; loc = { start: { line: lineNumber, column: index - lineStart } }; token = advance(); loc.end = { line: lineNumber, column: index - lineStart }; if (token.type !== Token.EOF) { value = source.slice(token.start, token.end); entry = { type: TokenName[token.type], value: value, range: [token.start, token.end], loc: loc }; if (token.regex) { entry.regex = { pattern: token.regex.pattern, flags: token.regex.flags }; } if (extra.tokenValues) { extra.tokenValues.push((entry.type === 'Punctuator' || entry.type === 'Keyword') ? entry.value : null); } if (extra.tokenize) { if (!extra.range) { delete entry.range; } if (!extra.loc) { delete entry.loc; } if (extra.delegate) { entry = extra.delegate(entry); } } extra.tokens.push(entry); } return token; } function lex() { var token; scanning = true; lastIndex = index; lastLineNumber = lineNumber; lastLineStart = lineStart; skipComment(); token = lookahead; startIndex = index; startLineNumber = lineNumber; startLineStart = lineStart; lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance(); scanning = false; return token; } function peek() { scanning = true; skipComment(); lastIndex = index; lastLineNumber = lineNumber; lastLineStart = lineStart; startIndex = index; startLineNumber = lineNumber; startLineStart = lineStart; lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance(); scanning = false; } function Position() { this.line = startLineNumber; this.column = startIndex - startLineStart; } function SourceLocation() { this.start = new Position(); this.end = null; } function WrappingSourceLocation(startToken) { this.start = { line: startToken.lineNumber, column: startToken.start - startToken.lineStart }; this.end = null; } function Node() { if (extra.range) { this.range = [startIndex, 0]; } if (extra.loc) { this.loc = new SourceLocation(); } } function WrappingNode(startToken) { if (extra.range) { this.range = [startToken.start, 0]; } if (extra.loc) { this.loc = new WrappingSourceLocation(startToken); } } WrappingNode.prototype = Node.prototype = { processComment: function () { var lastChild, innerComments, leadingComments, trailingComments, bottomRight = extra.bottomRightStack, i, comment, last = bottomRight[bottomRight.length - 1]; if (this.type === Syntax.Program) { if (this.body.length > 0) { return; } } /** * patch innnerComments for properties empty block * `function a() {/** comments **\/}` */ if (this.type === Syntax.BlockStatement && this.body.length === 0) { innerComments = []; for (i = extra.leadingComments.length - 1; i >= 0; --i) { comment = extra.leadingComments[i]; if (this.range[1] >= comment.range[1]) { innerComments.unshift(comment); extra.leadingComments.splice(i, 1); extra.trailingComments.splice(i, 1); } } if (innerComments.length) { this.innerComments = innerComments; //bottomRight.push(this); return; } } if (extra.trailingComments.length > 0) { trailingComments = []; for (i = extra.trailingComments.length - 1; i >= 0; --i) { comment = extra.trailingComments[i]; if (comment.range[0] >= this.range[1]) { trailingComments.unshift(comment); extra.trailingComments.splice(i, 1); } } extra.trailingComments = []; } else { if (last && last.trailingComments && last.trailingComments[0].range[0] >= this.range[1]) { trailingComments = last.trailingComments; delete last.trailingComments; } } // Eating the stack. while (last && last.range[0] >= this.range[0]) { lastChild = bottomRight.pop(); last = bottomRight[bottomRight.length - 1]; } if (lastChild) { if (lastChild.leadingComments) { leadingComments = []; for (i = lastChild.leadingComments.length - 1; i >= 0; --i) { comment = lastChild.leadingComments[i]; if (comment.range[1] <= this.range[0]) { leadingComments.unshift(comment); lastChild.leadingComments.splice(i, 1); } } if (!lastChild.leadingComments.length) { lastChild.leadingComments = undefined; } } } else if (extra.leadingComments.length > 0) { leadingComments = []; for (i = extra.leadingComments.length - 1; i >= 0; --i) { comment = extra.leadingComments[i]; if (comment.range[1] <= this.range[0]) { leadingComments.unshift(comment); extra.leadingComments.splice(i, 1); } } } if (leadingComments && leadingComments.length > 0) { this.leadingComments = leadingComments; } if (trailingComments && trailingComments.length > 0) { this.trailingComments = trailingComments; } bottomRight.push(this); }, finish: function () { if (extra.range) { this.range[1] = lastIndex; } if (extra.loc) { this.loc.end = { line: lastLineNumber, column: lastIndex - lastLineStart }; if (extra.source) { this.loc.source = extra.source; } } if (extra.attachComment) { this.processComment(); } }, finishArrayExpression: function (elements) { this.type = Syntax.ArrayExpression; this.elements = elements; this.finish(); return this; }, finishArrayPattern: function (elements) { this.type = Syntax.ArrayPattern; this.elements = elements; this.finish(); return this; }, finishArrowFunctionExpression: function (params, defaults, body, expression) { this.type = Syntax.ArrowFunctionExpression; this.id = null; this.params = params; this.defaults = defaults; this.body = body; this.generator = false; this.expression = expression; this.finish(); return this; }, finishAssignmentExpression: function (operator, left, right) { this.type = Syntax.AssignmentExpression; this.operator = operator; this.left = left; this.right = right; this.finish(); return this; }, finishAssignmentPattern: function (left, right) { this.type = Syntax.AssignmentPattern; this.left = left; this.right = right; this.finish(); return this; }, finishBinaryExpression: function (operator, left, right) { this.type = (operator === '||' || operator === '&&') ? Syntax.LogicalExpression : Syntax.BinaryExpression; this.operator = operator; this.left = left; this.right = right; this.finish(); return this; }, finishBlockStatement: function (body) { this.type = Syntax.BlockStatement; this.body = body; this.finish(); return this; }, finishBreakStatement: function (label) { this.type = Syntax.BreakStatement; this.label = label; this.finish(); return this; }, finishCallExpression: function (callee, args) { this.type = Syntax.CallExpression; this.callee = callee; this.arguments = args; this.finish(); return this; }, finishCatchClause: function (param, body) { this.type = Syntax.CatchClause; this.param = param; this.body = body; this.finish(); return this; }, finishClassBody: function (body) { this.type = Syntax.ClassBody; this.body = body; this.finish(); return this; }, finishClassDeclaration: function (id, superClass, body) { this.type = Syntax.ClassDeclaration; this.id = id; this.superClass = superClass; this.body = body; this.finish(); return this; }, finishClassExpression: function (id, superClass, body) { this.type = Syntax.ClassExpression; this.id = id; this.superClass = superClass; this.body = body; this.finish(); return this; }, finishConditionalExpression: function (test, consequent, alternate) { this.type = Syntax.ConditionalExpression; this.test = test; this.consequent = consequent; this.alternate = alternate; this.finish(); return this; }, finishContinueStatement: function (label) { this.type = Syntax.ContinueStatement; this.label = label; this.finish(); return this; }, finishDebuggerStatement: function () { this.type = Syntax.DebuggerStatement; this.finish(); return this; }, finishDoWhileStatement: function (body, test) { this.type = Syntax.DoWhileStatement; this.body = body; this.test = test; this.finish(); return this; }, finishEmptyStatement: function () { this.type = Syntax.EmptyStatement; this.finish(); return this; }, finishExpressionStatement: function (expression) { this.type = Syntax.ExpressionStatement; this.expression = expression; this.finish(); return this; }, finishForStatement: function (init, test, update, body) { this.type = Syntax.ForStatement; this.init = init; this.test = test; this.update = update; this.body = body; this.finish(); return this; }, finishForOfStatement: function (left, right, body) { this.type = Syntax.ForOfStatement; this.left = left; this.right = right; this.body = body; this.finish(); return this; }, finishForInStatement: function (left, right, body) { this.type = Syntax.ForInStatement; this.left = left; this.right = right; this.body = body; this.each = false; this.finish(); return this; }, finishFunctionDeclaration: function (id, params, defaults, body, generator) { this.type = Syntax.FunctionDeclaration; this.id = id; this.params = params; this.defaults = defaults; this.body = body; this.generator = generator; this.expression = false; this.finish(); return this; }, finishFunctionExpression: function (id, params, defaults, body, generator) { this.type = Syntax.FunctionExpression; this.id = id; this.params = params; this.defaults = defaults; this.body = body; this.generator = generator; this.expression = false; this.finish(); return this; }, finishIdentifier: function (name) { this.type = Syntax.Identifier; this.name = name; this.finish(); return this; }, finishIfStatement: function (test, consequent, alternate) { this.type = Syntax.IfStatement; this.test = test; this.consequent = consequent; this.alternate = alternate; this.finish(); return this; }, finishLabeledStatement: function (label, body) { this.type = Syntax.LabeledStatement; this.label = label; this.body = body; this.finish(); return this; }, finishLiteral: function (token) { this.type = Syntax.Literal; this.value = token.value; this.raw = source.slice(token.start, token.end); if (token.regex) { this.regex = token.regex; } this.finish(); return this; }, finishMemberExpression: function (accessor, object, property) { this.type = Syntax.MemberExpression; this.computed = accessor === '['; this.object = object; this.property = property; this.finish(); return this; }, finishMetaProperty: function (meta, property) { this.type = Syntax.MetaProperty; this.meta = meta; this.property = property; this.finish(); return this; }, finishNewExpression: function (callee, args) { this.type = Syntax.NewExpression; this.callee = callee; this.arguments = args; this.finish(); return this; }, finishObjectExpression: function (properties) { this.type = Syntax.ObjectExpression; this.properties = properties; this.finish(); return this; }, finishObjectPattern: function (properties) { this.type = Syntax.ObjectPattern; this.properties = properties; this.finish(); return this; }, finishPostfixExpression: function (operator, argument) { this.type = Syntax.UpdateExpression; this.operator = operator; this.argument = argument; this.prefix = false; this.finish(); return this; }, finishProgram: function (body, sourceType) { this.type = Syntax.Program; this.body = body; this.sourceType = sourceType; this.finish(); return this; }, finishProperty: function (kind, key, computed, value, method, shorthand) { this.type = Syntax.Property; this.key = key; this.computed = computed; this.value = value; this.kind = kind; this.method = method; this.shorthand = shorthand; this.finish(); return this; }, finishRestElement: function (argument) { this.type = Syntax.RestElement; this.argument = argument; this.finish(); return this; }, finishReturnStatement: function (argument) { this.type = Syntax.ReturnStatement; this.argument = argument; this.finish(); return this; }, finishSequenceExpression: function (expressions) { this.type = Syntax.SequenceExpression; this.expressions = expressions; this.finish(); return this; }, finishSpreadElement: function (argument) { this.type = Syntax.SpreadElement; this.argument = argument; this.finish(); return this; }, finishSwitchCase: function (test, consequent) { this.type = Syntax.SwitchCase; this.test = test; this.consequent = consequent; this.finish(); return this; }, finishSuper: function () { this.type = Syntax.Super; this.finish(); return this; }, finishSwitchStatement: function (discriminant, cases) { this.type = Syntax.SwitchStatement; this.discriminant = discriminant; this.cases = cases; this.finish(); return this; }, finishTaggedTemplateExpression: function (tag, quasi) { this.type = Syntax.TaggedTemplateExpression; this.tag = tag; this.quasi = quasi; this.finish(); return this; }, finishTemplateElement: function (value, tail) { this.type = Syntax.TemplateElement; this.value = value; this.tail = tail; this.finish(); return this; }, finishTemplateLiteral: function (quasis, expressions) { this.type = Syntax.TemplateLiteral; this.quasis = quasis; this.expressions = expressions; this.finish(); return this; }, finishThisExpression: function () { this.type = Syntax.ThisExpression; this.finish(); return this; }, finishThrowStatement: function (argument) { this.type = Syntax.ThrowStatement; this.argument = argument; this.finish(); return this; }, finishTryStatement: function (block, handler, finalizer) { this.type = Syntax.TryStatement; this.block = block; this.guardedHandlers = []; this.handlers = handler ? [handler] : []; this.handler = handler; this.finalizer = finalizer; this.finish(); return this; }, finishUnaryExpression: function (operator, argument) { this.type = (operator === '++' || operator === '--') ? Syntax.UpdateExpression : Syntax.UnaryExpression; this.operator = operator; this.argument = argument; this.prefix = true; this.finish(); return this; }, finishVariableDeclaration: function (declarations) { this.type = Syntax.VariableDeclaration; this.declarations = declarations; this.kind = 'var'; this.finish(); return this; }, finishLexicalDeclaration: function (declarations, kind) { this.type = Syntax.VariableDeclaration; this.declarations = declarations; this.kind = kind; this.finish(); return this; }, finishVariableDeclarator: function (id, init) { this.type = Syntax.VariableDeclarator; this.id = id; this.init = init; this.finish(); return this; }, finishWhileStatement: function (test, body) { this.type = Syntax.WhileStatement; this.test = test; this.body = body; this.finish(); return this; }, finishWithStatement: function (object, body) { this.type = Syntax.WithStatement; this.object = object; this.body = body; this.finish(); return this; }, finishExportSpecifier: function (local, exported) { this.type = Syntax.ExportSpecifier; this.exported = exported || local; this.local = local; this.finish(); return this; }, finishImportDefaultSpecifier: function (local) { this.type = Syntax.ImportDefaultSpecifier; this.local = local; this.finish(); return this; }, finishImportNamespaceSpecifier: function (local) { this.type = Syntax.ImportNamespaceSpecifier; this.local = local; this.finish(); return this; }, finishExportNamedDeclaration: function (declaration, specifiers, src) { this.type = Syntax.ExportNamedDeclaration; this.declaration = declaration; this.specifiers = specifiers; this.source = src; this.finish(); return this; }, finishExportDefaultDeclaration: function (declaration) { this.type = Syntax.ExportDefaultDeclaration; this.declaration = declaration; this.finish(); return this; }, finishExportAllDeclaration: function (src) { this.type = Syntax.ExportAllDeclaration; this.source = src; this.finish(); return this; }, finishImportSpecifier: function (local, imported) { this.type = Syntax.ImportSpecifier; this.local = local || imported; this.imported = imported; this.finish(); return this; }, finishImportDeclaration: function (specifiers, src) { this.type = Syntax.ImportDeclaration; this.specifiers = specifiers; this.source = src; this.finish(); return this; }, finishYieldExpression: function (argument, delegate) { this.type = Syntax.YieldExpression; this.argument = argument; this.delegate = delegate; this.finish(); return this; } }; function recordError(error) { var e, existing; for (e = 0; e < extra.errors.length; e++) { existing = extra.errors[e]; // Prevent duplicated error. /* istanbul ignore next */ if (existing.index === error.index && existing.message === error.message) { return; } } extra.errors.push(error); } function constructError(msg, column) { var error = new Error(msg); try { throw error; } catch (base) { /* istanbul ignore else */ if (Object.create && Object.defineProperty) { error = Object.create(base); Object.defineProperty(error, 'column', { value: column }); } } finally { return error; } } function createError(line, pos, description) { var msg, column, error; msg = 'Line ' + line + ': ' + description; column = pos - (scanning ? lineStart : lastLineStart) + 1; error = constructError(msg, column); error.lineNumber = line; error.description = description; error.index = pos; return error; } // Throw an exception function throwError(messageFormat) { var args, msg; args = Array.prototype.slice.call(arguments, 1); msg = messageFormat.replace(/%(\d)/g, function (whole, idx) { assert(idx < args.length, 'Message reference must be in range'); return args[idx]; } ); throw createError(lastLineNumber, lastIndex, msg); } function tolerateError(messageFormat) { var args, msg, error; args = Array.prototype.slice.call(arguments, 1); /* istanbul ignore next */ msg = messageFormat.replace(/%(\d)/g, function (whole, idx) { assert(idx < args.length, 'Message reference must be in range'); return args[idx]; } ); error = createError(lineNumber, lastIndex, msg); if (extra.errors) { recordError(error); } else { throw error; } } // Throw an exception because of the token. function unexpectedTokenError(token, message) { var value, msg = message || Messages.UnexpectedToken; if (token) { if (!message) { msg = (token.type === Token.EOF) ? Messages.UnexpectedEOS : (token.type === Token.Identifier) ? Messages.UnexpectedIdentifier : (token.type === Token.NumericLiteral) ? Messages.UnexpectedNumber : (token.type === Token.StringLiteral) ? Messages.UnexpectedString : (token.type === Token.Template) ? Messages.UnexpectedTemplate : Messages.UnexpectedToken; if (token.type === Token.Keyword) { if (isFutureReservedWord(token.value)) { msg = Messages.UnexpectedReserved; } else if (strict && isStrictModeReservedWord(token.value)) { msg = Messages.StrictReservedWord; } } } value = (token.type === Token.Template) ? token.value.raw : token.value; } else { value = 'ILLEGAL'; } msg = msg.replace('%0', value); return (token && typeof token.lineNumber === 'number') ? createError(token.lineNumber, token.start, msg) : createError(scanning ? lineNumber : lastLineNumber, scanning ? index : lastIndex, msg); } function throwUnexpectedToken(token, message) { throw unexpectedTokenError(token, message); } function tolerateUnexpectedToken(token, message) { var error = unexpectedTokenError(token, message); if (extra.errors) { recordError(error); } else { throw error; } } // Expect the next token to match the specified punctuator. // If not, an exception will be thrown. function expect(value) { var token = lex(); if (token.type !== Token.Punctuator || token.value !== value) { throwUnexpectedToken(token); } } /** * @name expectCommaSeparator * @description Quietly expect a comma when in tolerant mode, otherwise delegates * to <code>expect(value)</code> * @since 2.0 */ function expectCommaSeparator() { var token; if (extra.errors) { token = lookahead; if (token.type === Token.Punctuator && token.value === ',') { lex(); } else if (token.type === Token.Punctuator && token.value === ';') { lex(); tolerateUnexpectedToken(token); } else { tolerateUnexpectedToken(token, Messages.UnexpectedToken); } } else { expect(','); } } // Expect the next token to match the specified keyword. // If not, an exception will be thrown. function expectKeyword(keyword) { var token = lex(); if (token.type !== Token.Keyword || token.value !== keyword) { throwUnexpectedToken(token); } } // Return true if the next token matches the specified punctuator. function match(value) { return lookahead.type === Token.Punctuator && lookahead.value === value; } // Return true if the next token matches the specified keyword function matchKeyword(keyword) { return lookahead.type === Token.Keyword && lookahead.value === keyword; } // Return true if the next token matches the specified contextual keyword // (where an identifier is sometimes a keyword depending on the context) function matchContextualKeyword(keyword) { return lookahead.type === Token.Identifier && lookahead.value === keyword; } // Return true if the next token is an assignment operator function matchAssign() { var op; if (lookahead.type !== Token.Punctuator) { return false; } op = lookahead.value; return op === '=' || op === '*=' || op === '/=' || op === '%=' || op === '+=' || op === '-=' || op === '<<=' || op === '>>=' || op === '>>>=' || op === '&=' || op === '^=' || op === '|='; } function consumeSemicolon() { // Catch the very common case first: immediately a semicolon (U+003B). if (source.charCodeAt(startIndex) === 0x3B || match(';')) { lex(); return; } if (hasLineTerminator) { return; } // FIXME(ikarienator): this is seemingly an issue in the previous location info convention. lastIndex = startIndex; lastLineNumber = startLineNumber; lastLineStart = startLineStart; if (lookahead.type !== Token.EOF && !match('}')) { throwUnexpectedToken(lookahead); } } // Cover grammar support. // // When an assignment expression position starts with an left parenthesis, the determination of the type // of the syntax is to be deferred arbitrarily long until the end of the parentheses pair (plus a lookahead) // or the first comma. This situation also defers the determination of all the expressions nested in the pair. // // There are three productions that can be parsed in a parentheses pair that needs to be determined // after the outermost pair is closed. They are: // // 1. AssignmentExpression // 2. BindingElements // 3. AssignmentTargets // // In order to avoid exponential backtracking, we use two flags to denote if the production can be // binding element or assignment target. // // The three productions have the relationship: // // BindingElements ⊆ AssignmentTargets ⊆ AssignmentExpression // // with a single exception that CoverInitializedName when used directly in an Expression, generates // an early error. Therefore, we need the third state, firstCoverInitializedNameError, to track the // first usage of CoverInitializedName and report it when we reached the end of the parentheses pair. // // isolateCoverGrammar function runs the given parser function with a new cover grammar context, and it does not // effect the current flags. This means the production the parser parses is only used as an expression. Therefore // the CoverInitializedName check is conducted. // // inheritCoverGrammar function runs the given parse function with a new cover grammar context, and it propagates // the flags outside of the parser. This means the production the parser parses is used as a part of a potential // pattern. The CoverInitializedName check is deferred. function isolateCoverGrammar(parser) { var oldIsBindingElement = isBindingElement, oldIsAssignmentTarget = isAssignmentTarget, oldFirstCoverInitializedNameError = firstCoverInitializedNameError, result; isBindingElement = true; isAssignmentTarget = true; firstCoverInitializedNameError = null; result = parser(); if (firstCoverInitializedNameError !== null) { throwUnexpectedToken(firstCoverInitializedNameError); } isBindingElement = oldIsBindingElement; isAssignmentTarget = oldIsAssignmentTarget; firstCoverInitializedNameError = oldFirstCoverInitializedNameError; return result; } function inheritCoverGrammar(parser) { var oldIsBindingElement = isBindingElement, oldIsAssignmentTarget = isAssignmentTarget, oldFirstCoverInitializedNameError = firstCoverInitializedNameError, result; isBindingElement = true; isAssignmentTarget = true; firstCoverInitializedNameError = null; result = parser(); isBindingElement = isBindingElement && oldIsBindingElement; isAssignmentTarget = isAssignmentTarget && oldIsAssignmentTarget; firstCoverInitializedNameError = oldFirstCoverInitializedNameError || firstCoverInitializedNameError; return result; } // ECMA-262 13.3.3 Destructuring Binding Patterns function parseArrayPattern(params, kind) { var node = new Node(), elements = [], rest, restNode; expect('['); while (!match(']')) { if (match(',')) { lex(); elements.push(null); } else { if (match('...')) { restNode = new Node(); lex(); params.push(lookahead); rest = parseVariableIdentifier(kind); elements.push(restNode.finishRestElement(rest)); break; } else { elements.push(parsePatternWithDefault(params, kind)); } if (!match(']')) { expect(','); } } } expect(']'); return node.finishArrayPattern(elements); } function parsePropertyPattern(params, kind) { var node = new Node(), key, keyToken, computed = match('['), init; if (lookahead.type === Token.Identifier) { keyToken = lookahead; key = parseVariableIdentifier(); if (match('=')) { params.push(keyToken); lex(); init = parseAssignmentExpression(); return node.finishProperty( 'init', key, false, new WrappingNode(keyToken).finishAssignmentPattern(key, init), false, true); } else if (!match(':')) { params.push(keyToken); return node.finishProperty('init', key, false, key, false, true); } } else { key = parseObjectPropertyKey(); } expect(':'); init = parsePatternWithDefault(params, kind); return node.finishProperty('init', key, computed, init, false, false); } function parseObjectPattern(params, kind) { var node = new Node(), properties = []; expect('{'); while (!match('}')) { properties.push(parsePropertyPattern(params, kind)); if (!match('}')) { expect(','); } } lex(); return node.finishObjectPattern(properties); } function parsePattern(params, kind) { if (match('[')) { return parseArrayPattern(params, kind); } else if (match('{')) { return parseObjectPattern(params, kind); } else if (matchKeyword('let')) { if (kind === 'const' || kind === 'let') { tolerateUnexpectedToken(lookahead, Messages.UnexpectedToken); } } params.push(lookahead); return parseVariableIdentifier(kind); } function parsePatternWithDefault(params, kind) { var startToken = lookahead, pattern, previousAllowYield, right; pattern = parsePattern(params, kind); if (match('=')) { lex(); previousAllowYield = state.allowYield; state.allowYield = true; right = isolateCoverGrammar(parseAssignmentExpression); state.allowYield = previousAllowYield; pattern = new WrappingNode(startToken).finishAssignmentPattern(pattern, right); } return pattern; } // ECMA-262 12.2.5 Array Initializer function parseArrayInitializer() { var elements = [], node = new Node(), restSpread; expect('['); while (!match(']')) { if (match(',')) { lex(); elements.push(null); } else if (match('...')) { restSpread = new Node(); lex(); restSpread.finishSpreadElement(inheritCoverGrammar(parseAssignmentExpression)); if (!match(']')) { isAssignmentTarget = isBindingElement = false; expect(','); } elements.push(restSpread); } else { elements.push(inheritCoverGrammar(parseAssignmentExpression)); if (!match(']')) { expect(','); } } } lex(); return node.finishArrayExpression(elements); } // ECMA-262 12.2.6 Object Initializer function parsePropertyFunction(node, paramInfo, isGenerator) { var previousStrict, body; isAssignmentTarget = isBindingElement = false; previousStrict = strict; body = isolateCoverGrammar(parseFunctionSourceElements); if (strict && paramInfo.firstRestricted) { tolerateUnexpectedToken(paramInfo.firstRestricted, paramInfo.message); } if (strict && paramInfo.stricted) { tolerateUnexpectedToken(paramInfo.stricted, paramInfo.message); } strict = previousStrict; return node.finishFunctionExpression(null, paramInfo.params, paramInfo.defaults, body, isGenerator); } function parsePropertyMethodFunction() { var params, method, node = new Node(), previousAllowYield = state.allowYield; state.allowYield = false; params = parseParams(); state.allowYield = previousAllowYield; state.allowYield = false; method = parsePropertyFunction(node, params, false); state.allowYield = previousAllowYield; return method; } function parseObjectPropertyKey() { var token, node = new Node(), expr; token = lex(); // Note: This function is called only from parseObjectProperty(), where // EOF and Punctuator tokens are already filtered out. switch (token.type) { case Token.StringLiteral: case Token.NumericLiteral: if (strict && token.octal) { tolerateUnexpectedToken(token, Messages.StrictOctalLiteral); } return node.finishLiteral(token); case Token.Identifier: case Token.BooleanLiteral: case Token.NullLiteral: case Token.Keyword: return node.finishIdentifier(token.value); case Token.Punctuator: if (token.value === '[') { expr = isolateCoverGrammar(parseAssignmentExpression); expect(']'); return expr; } break; } throwUnexpectedToken(token); } function lookaheadPropertyName() { switch (lookahead.type) { case Token.Identifier: case Token.StringLiteral: case Token.BooleanLiteral: case Token.NullLiteral: case Token.NumericLiteral: case Token.Keyword: return true; case Token.Punctuator: return lookahead.value === '['; } return false; } // This function is to try to parse a MethodDefinition as defined in 14.3. But in the case of object literals, // it might be called at a position where there is in fact a short hand identifier pattern or a data property. // This can only be determined after we consumed up to the left parentheses. // // In order to avoid back tracking, it returns `null` if the position is not a MethodDefinition and the caller // is responsible to visit other options. function tryParseMethodDefinition(token, key, computed, node) { var value, options, methodNode, params, previousAllowYield = state.allowYield; if (token.type === Token.Identifier) { // check for `get` and `set`; if (token.value === 'get' && lookaheadPropertyName()) { computed = match('['); key = parseObjectPropertyKey(); methodNode = new Node(); expect('('); expect(')'); state.allowYield = false; value = parsePropertyFunction(methodNode, { params: [], defaults: [], stricted: null, firstRestricted: null, message: null }, false); state.allowYield = previousAllowYield; return node.finishProperty('get', key, computed, value, false, false); } else if (token.value === 'set' && lookaheadPropertyName()) { computed = match('['); key = parseObjectPropertyKey(); methodNode = new Node(); expect('('); options = { params: [], defaultCount: 0, defaults: [], firstRestricted: null, paramSet: {} }; if (match(')')) { tolerateUnexpectedToken(lookahead); } else { state.allowYield = false; parseParam(options); state.allowYield = previousAllowYield; if (options.defaultCount === 0) { options.defaults = []; } } expect(')'); state.allowYield = false; value = parsePropertyFunction(methodNode, options, false); state.allowYield = previousAllowYield; return node.finishProperty('set', key, computed, value, false, false); } } else if (token.type === Token.Punctuator && token.value === '*' && lookaheadPropertyName()) { computed = match('['); key = parseObjectPropertyKey(); methodNode = new Node(); state.allowYield = true; params = parseParams(); state.allowYield = previousAllowYield; state.allowYield = false; value = parsePropertyFunction(methodNode, params, true); state.allowYield = previousAllowYield; return node.finishProperty('init', key, computed, value, true, false); } if (key && match('(')) { value = parsePropertyMethodFunction(); return node.finishProperty('init', key, computed, value, true, false); } // Not a MethodDefinition. return null; } function parseObjectProperty(hasProto) { var token = lookahead, node = new Node(), computed, key, maybeMethod, proto, value; computed = match('['); if (match('*')) { lex(); } else { key = parseObjectPropertyKey(); } maybeMethod = tryParseMethodDefinition(token, key, computed, node); if (maybeMethod) { return maybeMethod; } if (!key) { throwUnexpectedToken(lookahead); } // Check for duplicated __proto__ if (!computed) { proto = (key.type === Syntax.Identifier && key.name === '__proto__') || (key.type === Syntax.Literal && key.value === '__proto__'); if (hasProto.value && proto) { tolerateError(Messages.DuplicateProtoProperty); } hasProto.value |= proto; } if (match(':')) { lex(); value = inheritCoverGrammar(parseAssignmentExpression); return node.finishProperty('init', key, computed, value, false, false); } if (token.type === Token.Identifier) { if (match('=')) { firstCoverInitializedNameError = lookahead; lex(); value = isolateCoverGrammar(parseAssignmentExpression); return node.finishProperty('init', key, computed, new WrappingNode(token).finishAssignmentPattern(key, value), false, true); } return node.finishProperty('init', key, computed, key, false, true); } throwUnexpectedToken(lookahead); } function parseObjectInitializer() { var properties = [], hasProto = {value: false}, node = new Node(); expect('{'); while (!match('}')) { properties.push(parseObjectProperty(hasProto)); if (!match('}')) { expectCommaSeparator(); } } expect('}'); return node.finishObjectExpression(properties); } function reinterpretExpressionAsPattern(expr) { var i; switch (expr.type) { case Syntax.Identifier: case Syntax.MemberExpression: case Syntax.RestElement: case Syntax.AssignmentPattern: break; case Syntax.SpreadElement: expr.type = Syntax.RestElement; reinterpretExpressionAsPattern(expr.argument); break; case Syntax.ArrayExpression: expr.type = Syntax.ArrayPattern; for (i = 0; i < expr.elements.length; i++) { if (expr.elements[i] !== null) { reinterpretExpressionAsPattern(expr.elements[i]); } } break; case Syntax.ObjectExpression: expr.type = Syntax.ObjectPattern; for (i = 0; i < expr.properties.length; i++) { reinterpretExpressionAsPattern(expr.properties[i].value); } break; case Syntax.AssignmentExpression: expr.type = Syntax.AssignmentPattern; reinterpretExpressionAsPattern(expr.left); break; default: // Allow other node type for tolerant parsing. break; } } // ECMA-262 12.2.9 Template Literals function parseTemplateElement(option) { var node, token; if (lookahead.type !== Token.Template || (option.head && !lookahead.head)) { throwUnexpectedToken(); } node = new Node(); token = lex(); return node.finishTemplateElement({ raw: token.value.raw, cooked: token.value.cooked }, token.tail); } function parseTemplateLiteral() { var quasi, quasis, expressions, node = new Node(); quasi = parseTemplateElement({ head: true }); quasis = [quasi]; expressions = []; while (!quasi.tail) { expressions.push(parseExpression()); quasi = parseTemplateElement({ head: false }); quasis.push(quasi); } return node.finishTemplateLiteral(quasis, expressions); } // ECMA-262 12.2.10 The Grouping Operator function parseGroupExpression() { var expr, expressions, startToken, i, params = []; expect('('); if (match(')')) { lex(); if (!match('=>')) { expect('=>'); } return { type: PlaceHolders.ArrowParameterPlaceHolder, params: [], rawParams: [] }; } startToken = lookahead; if (match('...')) { expr = parseRestElement(params); expect(')'); if (!match('=>')) { expect('=>'); } return { type: PlaceHolders.ArrowParameterPlaceHolder, params: [expr] }; } isBindingElement = true; expr = inheritCoverGrammar(parseAssignmentExpression); if (match(',')) { isAssignmentTarget = false; expressions = [expr]; while (startIndex < length) { if (!match(',')) { break; } lex(); if (match('...')) { if (!isBindingElement) { throwUnexpectedToken(lookahead); } expressions.push(parseRestElement(params)); expect(')'); if (!match('=>')) { expect('=>'); } isBindingElement = false; for (i = 0; i < expressions.length; i++) { reinterpretExpressionAsPattern(expressions[i]); } return { type: PlaceHolders.ArrowParameterPlaceHolder, params: expressions }; } expressions.push(inheritCoverGrammar(parseAssignmentExpression)); } expr = new WrappingNode(startToken).finishSequenceExpression(expressions); } expect(')'); if (match('=>')) { if (expr.type === Syntax.Identifier && expr.name === 'yield') { return { type: PlaceHolders.ArrowParameterPlaceHolder, params: [expr] }; } if (!isBindingElement) { throwUnexpectedToken(lookahead); } if (expr.type === Syntax.SequenceExpression) { for (i = 0; i < expr.expressions.length; i++) { reinterpretExpressionAsPattern(expr.expressions[i]); } } else { reinterpretExpressionAsPattern(expr); } expr = { type: PlaceHolders.ArrowParameterPlaceHolder, params: expr.type === Syntax.SequenceExpression ? expr.expressions : [expr] }; } isBindingElement = false; return expr; } // ECMA-262 12.2 Primary Expressions function parsePrimaryExpression() { var type, token, expr, node; if (match('(')) { isBindingElement = false; return inheritCoverGrammar(parseGroupExpression); } if (match('[')) { return inheritCoverGrammar(parseArrayInitializer); } if (match('{')) { return inheritCoverGrammar(parseObjectInitializer); } type = lookahead.type; node = new Node(); if (type === Token.Identifier) { if (state.sourceType === 'module' && lookahead.value === 'await') { tolerateUnexpectedToken(lookahead); } expr = node.finishIdentifier(lex().value); } else if (type === Token.StringLiteral || type === Token.NumericLiteral) { isAssignmentTarget = isBindingElement = false; if (strict && lookahead.octal) { tolerateUnexpectedToken(lookahead, Messages.StrictOctalLiteral); } expr = node.finishLiteral(lex()); } else if (type === Token.Keyword) { if (!strict && state.allowYield && matchKeyword('yield')) { return parseNonComputedProperty(); } if (!strict && matchKeyword('let')) { return node.finishIdentifier(lex().value); } isAssignmentTarget = isBindingElement = false; if (matchKeyword('function')) { return parseFunctionExpression(); } if (matchKeyword('this')) { lex(); return node.finishThisExpression(); } if (matchKeyword('class')) { return parseClassExpression(); } throwUnexpectedToken(lex()); } else if (type === Token.BooleanLiteral) { isAssignmentTarget = isBindingElement = false; token = lex(); token.value = (token.value === 'true'); expr = node.finishLiteral(token); } else if (type === Token.NullLiteral) { isAssignmentTarget = isBindingElement = false; token = lex(); token.value = null; expr = node.finishLiteral(token); } else if (match('/') || match('/=')) { isAssignmentTarget = isBindingElement = false; index = startIndex; if (typeof extra.tokens !== 'undefined') { token = collectRegex(); } else { token = scanRegExp(); } lex(); expr = node.finishLiteral(token); } else if (type === Token.Template) { expr = parseTemplateLiteral(); } else { throwUnexpectedToken(lex()); } return expr; } // ECMA-262 12.3 Left-Hand-Side Expressions function parseArguments() { var args = [], expr; expect('('); if (!match(')')) { while (startIndex < length) { if (match('...')) { expr = new Node(); lex(); expr.finishSpreadElement(isolateCoverGrammar(parseAssignmentExpression)); } else { expr = isolateCoverGrammar(parseAssignmentExpression); } args.push(expr); if (match(')')) { break; } expectCommaSeparator(); } } expect(')'); return args; } function parseNonComputedProperty() { var token, node = new Node(); token = lex(); if (!isIdentifierName(token)) { throwUnexpectedToken(token); } return node.finishIdentifier(token.value); } function parseNonComputedMember() { expect('.'); return parseNonComputedProperty(); } function parseComputedMember() { var expr; expect('['); expr = isolateCoverGrammar(parseExpression); expect(']'); return expr; } // ECMA-262 12.3.3 The new Operator function parseNewExpression() { var callee, args, node = new Node(); expectKeyword('new'); if (match('.')) { lex(); if (lookahead.type === Token.Identifier && lookahead.value === 'target') { if (state.inFunctionBody) { lex(); return node.finishMetaProperty('new', 'target'); } } throwUnexpectedToken(lookahead); } callee = isolateCoverGrammar(parseLeftHandSideExpression); args = match('(') ? parseArguments() : []; isAssignmentTarget = isBindingElement = false; return node.finishNewExpression(callee, args); } // ECMA-262 12.3.4 Function Calls function parseLeftHandSideExpressionAllowCall() { var quasi, expr, args, property, startToken, previousAllowIn = state.allowIn; startToken = lookahead; state.allowIn = true; if (matchKeyword('super') && state.inFunctionBody) { expr = new Node(); lex(); expr = expr.finishSuper(); if (!match('(') && !match('.') && !match('[')) { throwUnexpectedToken(lookahead); } } else { expr = inheritCoverGrammar(matchKeyword('new') ? parseNewExpression : parsePrimaryExpression); } for (;;) { if (match('.')) { isBindingElement = false; isAssignmentTarget = true; property = parseNonComputedMember(); expr = new WrappingNode(startToken).finishMemberExpression('.', expr, property); } else if (match('(')) { isBindingElement = false; isAssignmentTarget = false; args = parseArguments(); expr = new WrappingNode(startToken).finishCallExpression(expr, args); } else if (match('[')) { isBindingElement = false; isAssignmentTarget = true; property = parseComputedMember(); expr = new WrappingNode(startToken).finishMemberExpression('[', expr, property); } else if (lookahead.type === Token.Template && lookahead.head) { quasi = parseTemplateLiteral(); expr = new WrappingNode(startToken).finishTaggedTemplateExpression(expr, quasi); } else { break; } } state.allowIn = previousAllowIn; return expr; } // ECMA-262 12.3 Left-Hand-Side Expressions function parseLeftHandSideExpression() { var quasi, expr, property, startToken; assert(state.allowIn, 'callee of new expression always allow in keyword.'); startToken = lookahead; if (matchKeyword('super') && state.inFunctionBody) { expr = new Node(); lex(); expr = expr.finishSuper(); if (!match('[') && !match('.')) { throwUnexpectedToken(lookahead); } } else { expr = inheritCoverGrammar(matchKeyword('new') ? parseNewExpression : parsePrimaryExpression); } for (;;) { if (match('[')) { isBindingElement = false; isAssignmentTarget = true; property = parseComputedMember(); expr = new WrappingNode(startToken).finishMemberExpression('[', expr, property); } else if (match('.')) { isBindingElement = false; isAssignmentTarget = true; property = parseNonComputedMember(); expr = new WrappingNode(startToken).finishMemberExpression('.', expr, property); } else if (lookahead.type === Token.Template && lookahead.head) { quasi = parseTemplateLiteral(); expr = new WrappingNode(startToken).finishTaggedTemplateExpression(expr, quasi); } else { break; } } return expr; } // ECMA-262 12.4 Postfix Expressions function parsePostfixExpression() { var expr, token, startToken = lookahead; expr = inheritCoverGrammar(parseLeftHandSideExpressionAllowCall); if (!hasLineTerminator && lookahead.type === Token.Punctuator) { if (match('++') || match('--')) { // ECMA-262 11.3.1, 11.3.2 if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { tolerateError(Messages.StrictLHSPostfix); } if (!isAssignmentTarget) { tolerateError(Messages.InvalidLHSInAssignment); } isAssignmentTarget = isBindingElement = false; token = lex(); expr = new WrappingNode(startToken).finishPostfixExpression(token.value, expr); } } return expr; } // ECMA-262 12.5 Unary Operators function parseUnaryExpression() { var token, expr, startToken; if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) { expr = parsePostfixExpression(); } else if (match('++') || match('--')) { startToken = lookahead; token = lex(); expr = inheritCoverGrammar(parseUnaryExpression); // ECMA-262 11.4.4, 11.4.5 if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { tolerateError(Messages.StrictLHSPrefix); } if (!isAssignmentTarget) { tolerateError(Messages.InvalidLHSInAssignment); } expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr); isAssignmentTarget = isBindingElement = false; } else if (match('+') || match('-') || match('~') || match('!')) { startToken = lookahead; token = lex(); expr = inheritCoverGrammar(parseUnaryExpression); expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr); isAssignmentTarget = isBindingElement = false; } else if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) { startToken = lookahead; token = lex(); expr = inheritCoverGrammar(parseUnaryExpression); expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr); if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) { tolerateError(Messages.StrictDelete); } isAssignmentTarget = isBindingElement = false; } else { expr = parsePostfixExpression(); } return expr; } function binaryPrecedence(token, allowIn) { var prec = 0; if (token.type !== Token.Punctuator && token.type !== Token.Keyword) { return 0; } switch (token.value) { case '||': prec = 1; break; case '&&': prec = 2; break; case '|': prec = 3; break; case '^': prec = 4; break; case '&': prec = 5; break; case '==': case '!=': case '===': case '!==': prec = 6; break; case '<': case '>': case '<=': case '>=': case 'instanceof': prec = 7; break; case 'in': prec = allowIn ? 7 : 0; break; case '<<': case '>>': case '>>>': prec = 8; break; case '+': case '-': prec = 9; break; case '*': case '/': case '%': prec = 11; break; default: break; } return prec; } // ECMA-262 12.6 Multiplicative Operators // ECMA-262 12.7 Additive Operators // ECMA-262 12.8 Bitwise Shift Operators // ECMA-262 12.9 Relational Operators // ECMA-262 12.10 Equality Operators // ECMA-262 12.11 Binary Bitwise Operators // ECMA-262 12.12 Binary Logical Operators function parseBinaryExpression() { var marker, markers, expr, token, prec, stack, right, operator, left, i; marker = lookahead; left = inheritCoverGrammar(parseUnaryExpression); token = lookahead; prec = binaryPrecedence(token, state.allowIn); if (prec === 0) { return left; } isAssignmentTarget = isBindingElement = false; token.prec = prec; lex(); markers = [marker, lookahead]; right = isolateCoverGrammar(parseUnaryExpression); stack = [left, token, right]; while ((prec = binaryPrecedence(lookahead, state.allowIn)) > 0) { // Reduce: make a binary expression from the three topmost entries. while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) { right = stack.pop(); operator = stack.pop().value; left = stack.pop(); markers.pop(); expr = new WrappingNode(markers[markers.length - 1]).finishBinaryExpression(operator, left, right); stack.push(expr); } // Shift. token = lex(); token.prec = prec; stack.push(token); markers.push(lookahead); expr = isolateCoverGrammar(parseUnaryExpression); stack.push(expr); } // Final reduce to clean-up the stack. i = stack.length - 1; expr = stack[i]; markers.pop(); while (i > 1) { expr = new WrappingNode(markers.pop()).finishBinaryExpression(stack[i - 1].value, stack[i - 2], expr); i -= 2; } return expr; } // ECMA-262 12.13 Conditional Operator function parseConditionalExpression() { var expr, previousAllowIn, consequent, alternate, startToken; startToken = lookahead; expr = inheritCoverGrammar(parseBinaryExpression); if (match('?')) { lex(); previousAllowIn = state.allowIn; state.allowIn = true; consequent = isolateCoverGrammar(parseAssignmentExpression); state.allowIn = previousAllowIn; expect(':'); alternate = isolateCoverGrammar(parseAssignmentExpression); expr = new WrappingNode(startToken).finishConditionalExpression(expr, consequent, alternate); isAssignmentTarget = isBindingElement = false; } return expr; } // ECMA-262 14.2 Arrow Function Definitions function parseConciseBody() { if (match('{')) { return parseFunctionSourceElements(); } return isolateCoverGrammar(parseAssignmentExpression); } function checkPatternParam(options, param) { var i; switch (param.type) { case Syntax.Identifier: validateParam(options, param, param.name); break; case Syntax.RestElement: checkPatternParam(options, param.argument); break; case Syntax.AssignmentPattern: checkPatternParam(options, param.left); break; case Syntax.ArrayPattern: for (i = 0; i < param.elements.length; i++) { if (param.elements[i] !== null) { checkPatternParam(options, param.elements[i]); } } break; case Syntax.YieldExpression: break; default: assert(param.type === Syntax.ObjectPattern, 'Invalid type'); for (i = 0; i < param.properties.length; i++) { checkPatternParam(options, param.properties[i].value); } break; } } function reinterpretAsCoverFormalsList(expr) { var i, len, param, params, defaults, defaultCount, options, token; defaults = []; defaultCount = 0; params = [expr]; switch (expr.type) { case Syntax.Identifier: break; case PlaceHolders.ArrowParameterPlaceHolder: params = expr.params; break; default: return null; } options = { paramSet: {} }; for (i = 0, len = params.length; i < len; i += 1) { param = params[i]; switch (param.type) { case Syntax.AssignmentPattern: params[i] = param.left; if (param.right.type === Syntax.YieldExpression) { if (param.right.argument) { throwUnexpectedToken(lookahead); } param.right.type = Syntax.Identifier; param.right.name = 'yield'; delete param.right.argument; delete param.right.delegate; } defaults.push(param.right); ++defaultCount; checkPatternParam(options, param.left); break; default: checkPatternParam(options, param); params[i] = param; defaults.push(null); break; } } if (strict || !state.allowYield) { for (i = 0, len = params.length; i < len; i += 1) { param = params[i]; if (param.type === Syntax.YieldExpression) { throwUnexpectedToken(lookahead); } } } if (options.message === Messages.StrictParamDupe) { token = strict ? options.stricted : options.firstRestricted; throwUnexpectedToken(token, options.message); } if (defaultCount === 0) { defaults = []; } return { params: params, defaults: defaults, stricted: options.stricted, firstRestricted: options.firstRestricted, message: options.message }; } function parseArrowFunctionExpression(options, node) { var previousStrict, previousAllowYield, body; if (hasLineTerminator) { tolerateUnexpectedToken(lookahead); } expect('=>'); previousStrict = strict; previousAllowYield = state.allowYield; state.allowYield = true; body = parseConciseBody(); if (strict && options.firstRestricted) { throwUnexpectedToken(options.firstRestricted, options.message); } if (strict && options.stricted) { tolerateUnexpectedToken(options.stricted, options.message); } strict = previousStrict; state.allowYield = previousAllowYield; return node.finishArrowFunctionExpression(options.params, options.defaults, body, body.type !== Syntax.BlockStatement); } // ECMA-262 14.4 Yield expression function parseYieldExpression() { var argument, expr, delegate, previousAllowYield; argument = null; expr = new Node(); delegate = false; expectKeyword('yield'); if (!hasLineTerminator) { previousAllowYield = state.allowYield; state.allowYield = false; delegate = match('*'); if (delegate) { lex(); argument = parseAssignmentExpression(); } else { if (!match(';') && !match('}') && !match(')') && lookahead.type !== Token.EOF) { argument = parseAssignmentExpression(); } } state.allowYield = previousAllowYield; } return expr.finishYieldExpression(argument, delegate); } // ECMA-262 12.14 Assignment Operators function parseAssignmentExpression() { var token, expr, right, list, startToken; startToken = lookahead; token = lookahead; if (!state.allowYield && matchKeyword('yield')) { return parseYieldExpression(); } expr = parseConditionalExpression(); if (expr.type === PlaceHolders.ArrowParameterPlaceHolder || match('=>')) { isAssignmentTarget = isBindingElement = false; list = reinterpretAsCoverFormalsList(expr); if (list) { firstCoverInitializedNameError = null; return parseArrowFunctionExpression(list, new WrappingNode(startToken)); } return expr; } if (matchAssign()) { if (!isAssignmentTarget) { tolerateError(Messages.InvalidLHSInAssignment); } // ECMA-262 12.1.1 if (strict && expr.type === Syntax.Identifier) { if (isRestrictedWord(expr.name)) { tolerateUnexpectedToken(token, Messages.StrictLHSAssignment); } if (isStrictModeReservedWord(expr.name)) { tolerateUnexpectedToken(token, Messages.StrictReservedWord); } } if (!match('=')) { isAssignmentTarget = isBindingElement = false; } else { reinterpretExpressionAsPattern(expr); } token = lex(); right = isolateCoverGrammar(parseAssignmentExpression); expr = new WrappingNode(startToken).finishAssignmentExpression(token.value, expr, right); firstCoverInitializedNameError = null; } return expr; } // ECMA-262 12.15 Comma Operator function parseExpression() { var expr, startToken = lookahead, expressions; expr = isolateCoverGrammar(parseAssignmentExpression); if (match(',')) { expressions = [expr]; while (startIndex < length) { if (!match(',')) { break; } lex(); expressions.push(isolateCoverGrammar(parseAssignmentExpression)); } expr = new WrappingNode(startToken).finishSequenceExpression(expressions); } return expr; } // ECMA-262 13.2 Block function parseStatementListItem() { if (lookahead.type === Token.Keyword) { switch (lookahead.value) { case 'export': if (state.sourceType !== 'module') { tolerateUnexpectedToken(lookahead, Messages.IllegalExportDeclaration); } return parseExportDeclaration(); case 'import': if (state.sourceType !== 'module') { tolerateUnexpectedToken(lookahead, Messages.IllegalImportDeclaration); } return parseImportDeclaration(); case 'const': return parseLexicalDeclaration({inFor: false}); case 'function': return parseFunctionDeclaration(new Node()); case 'class': return parseClassDeclaration(); } } if (matchKeyword('let') && isLexicalDeclaration()) { return parseLexicalDeclaration({inFor: false}); } return parseStatement(); } function parseStatementList() { var list = []; while (startIndex < length) { if (match('}')) { break; } list.push(parseStatementListItem()); } return list; } function parseBlock() { var block, node = new Node(); expect('{'); block = parseStatementList(); expect('}'); return node.finishBlockStatement(block); } // ECMA-262 13.3.2 Variable Statement function parseVariableIdentifier(kind) { var token, node = new Node(); token = lex(); if (token.type === Token.Keyword && token.value === 'yield') { if (strict) { tolerateUnexpectedToken(token, Messages.StrictReservedWord); } if (!state.allowYield) { throwUnexpectedToken(token); } } else if (token.type !== Token.Identifier) { if (strict && token.type === Token.Keyword && isStrictModeReservedWord(token.value)) { tolerateUnexpectedToken(token, Messages.StrictReservedWord); } else { if (strict || token.value !== 'let' || kind !== 'var') { throwUnexpectedToken(token); } } } else if (state.sourceType === 'module' && token.type === Token.Identifier && token.value === 'await') { tolerateUnexpectedToken(token); } return node.finishIdentifier(token.value); } function parseVariableDeclaration(options) { var init = null, id, node = new Node(), params = []; id = parsePattern(params, 'var'); // ECMA-262 12.2.1 if (strict && isRestrictedWord(id.name)) { tolerateError(Messages.StrictVarName); } if (match('=')) { lex(); init = isolateCoverGrammar(parseAssignmentExpression); } else if (id.type !== Syntax.Identifier && !options.inFor) { expect('='); } return node.finishVariableDeclarator(id, init); } function parseVariableDeclarationList(options) { var opt, list; opt = { inFor: options.inFor }; list = [parseVariableDeclaration(opt)]; while (match(',')) { lex(); list.push(parseVariableDeclaration(opt)); } return list; } function parseVariableStatement(node) { var declarations; expectKeyword('var'); declarations = parseVariableDeclarationList({ inFor: false }); consumeSemicolon(); return node.finishVariableDeclaration(declarations); } // ECMA-262 13.3.1 Let and Const Declarations function parseLexicalBinding(kind, options) { var init = null, id, node = new Node(), params = []; id = parsePattern(params, kind); // ECMA-262 12.2.1 if (strict && id.type === Syntax.Identifier && isRestrictedWord(id.name)) { tolerateError(Messages.StrictVarName); } if (kind === 'const') { if (!matchKeyword('in') && !matchContextualKeyword('of')) { expect('='); init = isolateCoverGrammar(parseAssignmentExpression); } } else if ((!options.inFor && id.type !== Syntax.Identifier) || match('=')) { expect('='); init = isolateCoverGrammar(parseAssignmentExpression); } return node.finishVariableDeclarator(id, init); } function parseBindingList(kind, options) { var list = [parseLexicalBinding(kind, options)]; while (match(',')) { lex(); list.push(parseLexicalBinding(kind, options)); } return list; } function tokenizerState() { return { index: index, lineNumber: lineNumber, lineStart: lineStart, hasLineTerminator: hasLineTerminator, lastIndex: lastIndex, lastLineNumber: lastLineNumber, lastLineStart: lastLineStart, startIndex: startIndex, startLineNumber: startLineNumber, startLineStart: startLineStart, lookahead: lookahead, tokenCount: extra.tokens ? extra.tokens.length : 0 }; } function resetTokenizerState(ts) { index = ts.index; lineNumber = ts.lineNumber; lineStart = ts.lineStart; hasLineTerminator = ts.hasLineTerminator; lastIndex = ts.lastIndex; lastLineNumber = ts.lastLineNumber; lastLineStart = ts.lastLineStart; startIndex = ts.startIndex; startLineNumber = ts.startLineNumber; startLineStart = ts.startLineStart; lookahead = ts.lookahead; if (extra.tokens) { extra.tokens.splice(ts.tokenCount, extra.tokens.length); } } function isLexicalDeclaration() { var lexical, ts; ts = tokenizerState(); lex(); lexical = (lookahead.type === Token.Identifier) || match('[') || match('{') || matchKeyword('let') || matchKeyword('yield'); resetTokenizerState(ts); return lexical; } function parseLexicalDeclaration(options) { var kind, declarations, node = new Node(); kind = lex().value; assert(kind === 'let' || kind === 'const', 'Lexical declaration must be either let or const'); declarations = parseBindingList(kind, options); consumeSemicolon(); return node.finishLexicalDeclaration(declarations, kind); } function parseRestElement(params) { var param, node = new Node(); lex(); if (match('{')) { throwError(Messages.ObjectPatternAsRestParameter); } params.push(lookahead); param = parseVariableIdentifier(); if (match('=')) { throwError(Messages.DefaultRestParameter); } if (!match(')')) { throwError(Messages.ParameterAfterRestParameter); } return node.finishRestElement(param); } // ECMA-262 13.4 Empty Statement function parseEmptyStatement(node) { expect(';'); return node.finishEmptyStatement(); } // ECMA-262 12.4 Expression Statement function parseExpressionStatement(node) { var expr = parseExpression(); consumeSemicolon(); return node.finishExpressionStatement(expr); } // ECMA-262 13.6 If statement function parseIfStatement(node) { var test, consequent, alternate; expectKeyword('if'); expect('('); test = parseExpression(); expect(')'); consequent = parseStatement(); if (matchKeyword('else')) { lex(); alternate = parseStatement(); } else { alternate = null; } return node.finishIfStatement(test, consequent, alternate); } // ECMA-262 13.7 Iteration Statements function parseDoWhileStatement(node) { var body, test, oldInIteration; expectKeyword('do'); oldInIteration = state.inIteration; state.inIteration = true; body = parseStatement(); state.inIteration = oldInIteration; expectKeyword('while'); expect('('); test = parseExpression(); expect(')'); if (match(';')) { lex(); } return node.finishDoWhileStatement(body, test); } function parseWhileStatement(node) { var test, body, oldInIteration; expectKeyword('while'); expect('('); test = parseExpression(); expect(')'); oldInIteration = state.inIteration; state.inIteration = true; body = parseStatement(); state.inIteration = oldInIteration; return node.finishWhileStatement(test, body); } function parseForStatement(node) { var init, forIn, initSeq, initStartToken, test, update, left, right, kind, declarations, body, oldInIteration, previousAllowIn = state.allowIn; init = test = update = null; forIn = true; expectKeyword('for'); expect('('); if (match(';')) { lex(); } else { if (matchKeyword('var')) { init = new Node(); lex(); state.allowIn = false; declarations = parseVariableDeclarationList({ inFor: true }); state.allowIn = previousAllowIn; if (declarations.length === 1 && matchKeyword('in')) { init = init.finishVariableDeclaration(declarations); lex(); left = init; right = parseExpression(); init = null; } else if (declarations.length === 1 && declarations[0].init === null && matchContextualKeyword('of')) { init = init.finishVariableDeclaration(declarations); lex(); left = init; right = parseAssignmentExpression(); init = null; forIn = false; } else { init = init.finishVariableDeclaration(declarations); expect(';'); } } else if (matchKeyword('const') || matchKeyword('let')) { init = new Node(); kind = lex().value; if (!strict && lookahead.value === 'in') { init = init.finishIdentifier(kind); lex(); left = init; right = parseExpression(); init = null; } else { state.allowIn = false; declarations = parseBindingList(kind, {inFor: true}); state.allowIn = previousAllowIn; if (declarations.length === 1 && declarations[0].init === null && matchKeyword('in')) { init = init.finishLexicalDeclaration(declarations, kind); lex(); left = init; right = parseExpression(); init = null; } else if (declarations.length === 1 && declarations[0].init === null && matchContextualKeyword('of')) { init = init.finishLexicalDeclaration(declarations, kind); lex(); left = init; right = parseAssignmentExpression(); init = null; forIn = false; } else { consumeSemicolon(); init = init.finishLexicalDeclaration(declarations, kind); } } } else { initStartToken = lookahead; state.allowIn = false; init = inheritCoverGrammar(parseAssignmentExpression); state.allowIn = previousAllowIn; if (matchKeyword('in')) { if (!isAssignmentTarget) { tolerateError(Messages.InvalidLHSInForIn); } lex(); reinterpretExpressionAsPattern(init); left = init; right = parseExpression(); init = null; } else if (matchContextualKeyword('of')) { if (!isAssignmentTarget) { tolerateError(Messages.InvalidLHSInForLoop); } lex(); reinterpretExpressionAsPattern(init); left = init; right = parseAssignmentExpression(); init = null; forIn = false; } else { if (match(',')) { initSeq = [init]; while (match(',')) { lex(); initSeq.push(isolateCoverGrammar(parseAssignmentExpression)); } init = new WrappingNode(initStartToken).finishSequenceExpression(initSeq); } expect(';'); } } } if (typeof left === 'undefined') { if (!match(';')) { test = parseExpression(); } expect(';'); if (!match(')')) { update = parseExpression(); } } expect(')'); oldInIteration = state.inIteration; state.inIteration = true; body = isolateCoverGrammar(parseStatement); state.inIteration = oldInIteration; return (typeof left === 'undefined') ? node.finishForStatement(init, test, update, body) : forIn ? node.finishForInStatement(left, right, body) : node.finishForOfStatement(left, right, body); } // ECMA-262 13.8 The continue statement function parseContinueStatement(node) { var label = null, key; expectKeyword('continue'); // Optimize the most common form: 'continue;'. if (source.charCodeAt(startIndex) === 0x3B) { lex(); if (!state.inIteration) { throwError(Messages.IllegalContinue); } return node.finishContinueStatement(null); } if (hasLineTerminator) { if (!state.inIteration) { throwError(Messages.IllegalContinue); } return node.finishContinueStatement(null); } if (lookahead.type === Token.Identifier) { label = parseVariableIdentifier(); key = '$' + label.name; if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) { throwError(Messages.UnknownLabel, label.name); } } consumeSemicolon(); if (label === null && !state.inIteration) { throwError(Messages.IllegalContinue); } return node.finishContinueStatement(label); } // ECMA-262 13.9 The break statement function parseBreakStatement(node) { var label = null, key; expectKeyword('break'); // Catch the very common case first: immediately a semicolon (U+003B). if (source.charCodeAt(lastIndex) === 0x3B) { lex(); if (!(state.inIteration || state.inSwitch)) { throwError(Messages.IllegalBreak); } return node.finishBreakStatement(null); } if (hasLineTerminator) { if (!(state.inIteration || state.inSwitch)) { throwError(Messages.IllegalBreak); } } else if (lookahead.type === Token.Identifier) { label = parseVariableIdentifier(); key = '$' + label.name; if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) { throwError(Messages.UnknownLabel, label.name); } } consumeSemicolon(); if (label === null && !(state.inIteration || state.inSwitch)) { throwError(Messages.IllegalBreak); } return node.finishBreakStatement(label); } // ECMA-262 13.10 The return statement function parseReturnStatement(node) { var argument = null; expectKeyword('return'); if (!state.inFunctionBody) { tolerateError(Messages.IllegalReturn); } // 'return' followed by a space and an identifier is very common. if (source.charCodeAt(lastIndex) === 0x20) { if (isIdentifierStart(source.charCodeAt(lastIndex + 1))) { argument = parseExpression(); consumeSemicolon(); return node.finishReturnStatement(argument); } } if (hasLineTerminator) { // HACK return node.finishReturnStatement(null); } if (!match(';')) { if (!match('}') && lookahead.type !== Token.EOF) { argument = parseExpression(); } } consumeSemicolon(); return node.finishReturnStatement(argument); } // ECMA-262 13.11 The with statement function parseWithStatement(node) { var object, body; if (strict) { tolerateError(Messages.StrictModeWith); } expectKeyword('with'); expect('('); object = parseExpression(); expect(')'); body = parseStatement(); return node.finishWithStatement(object, body); } // ECMA-262 13.12 The switch statement function parseSwitchCase() { var test, consequent = [], statement, node = new Node(); if (matchKeyword('default')) { lex(); test = null; } else { expectKeyword('case'); test = parseExpression(); } expect(':'); while (startIndex < length) { if (match('}') || matchKeyword('default') || matchKeyword('case')) { break; } statement = parseStatementListItem(); consequent.push(statement); } return node.finishSwitchCase(test, consequent); } function parseSwitchStatement(node) { var discriminant, cases, clause, oldInSwitch, defaultFound; expectKeyword('switch'); expect('('); discriminant = parseExpression(); expect(')'); expect('{'); cases = []; if (match('}')) { lex(); return node.finishSwitchStatement(discriminant, cases); } oldInSwitch = state.inSwitch; state.inSwitch = true; defaultFound = false; while (startIndex < length) { if (match('}')) { break; } clause = parseSwitchCase(); if (clause.test === null) { if (defaultFound) { throwError(Messages.MultipleDefaultsInSwitch); } defaultFound = true; } cases.push(clause); } state.inSwitch = oldInSwitch; expect('}'); return node.finishSwitchStatement(discriminant, cases); } // ECMA-262 13.14 The throw statement function parseThrowStatement(node) { var argument; expectKeyword('throw'); if (hasLineTerminator) { throwError(Messages.NewlineAfterThrow); } argument = parseExpression(); consumeSemicolon(); return node.finishThrowStatement(argument); } // ECMA-262 13.15 The try statement function parseCatchClause() { var param, params = [], paramMap = {}, key, i, body, node = new Node(); expectKeyword('catch'); expect('('); if (match(')')) { throwUnexpectedToken(lookahead); } param = parsePattern(params); for (i = 0; i < params.length; i++) { key = '$' + params[i].value; if (Object.prototype.hasOwnProperty.call(paramMap, key)) { tolerateError(Messages.DuplicateBinding, params[i].value); } paramMap[key] = true; } // ECMA-262 12.14.1 if (strict && isRestrictedWord(param.name)) { tolerateError(Messages.StrictCatchVariable); } expect(')'); body = parseBlock(); return node.finishCatchClause(param, body); } function parseTryStatement(node) { var block, handler = null, finalizer = null; expectKeyword('try'); block = parseBlock(); if (matchKeyword('catch')) { handler = parseCatchClause(); } if (matchKeyword('finally')) { lex(); finalizer = parseBlock(); } if (!handler && !finalizer) { throwError(Messages.NoCatchOrFinally); } return node.finishTryStatement(block, handler, finalizer); } // ECMA-262 13.16 The debugger statement function parseDebuggerStatement(node) { expectKeyword('debugger'); consumeSemicolon(); return node.finishDebuggerStatement(); } // 13 Statements function parseStatement() { var type = lookahead.type, expr, labeledBody, key, node; if (type === Token.EOF) { throwUnexpectedToken(lookahead); } if (type === Token.Punctuator && lookahead.value === '{') { return parseBlock(); } isAssignmentTarget = isBindingElement = true; node = new Node(); if (type === Token.Punctuator) { switch (lookahead.value) { case ';': return parseEmptyStatement(node); case '(': return parseExpressionStatement(node); default: break; } } else if (type === Token.Keyword) { switch (lookahead.value) { case 'break': return parseBreakStatement(node); case 'continue': return parseContinueStatement(node); case 'debugger': return parseDebuggerStatement(node); case 'do': return parseDoWhileStatement(node); case 'for': return parseForStatement(node); case 'function': return parseFunctionDeclaration(node); case 'if': return parseIfStatement(node); case 'return': return parseReturnStatement(node); case 'switch': return parseSwitchStatement(node); case 'throw': return parseThrowStatement(node); case 'try': return parseTryStatement(node); case 'var': return parseVariableStatement(node); case 'while': return parseWhileStatement(node); case 'with': return parseWithStatement(node); default: break; } } expr = parseExpression(); // ECMA-262 12.12 Labelled Statements if ((expr.type === Syntax.Identifier) && match(':')) { lex(); key = '$' + expr.name; if (Object.prototype.hasOwnProperty.call(state.labelSet, key)) { throwError(Messages.Redeclaration, 'Label', expr.name); } state.labelSet[key] = true; labeledBody = parseStatement(); delete state.labelSet[key]; return node.finishLabeledStatement(expr, labeledBody); } consumeSemicolon(); return node.finishExpressionStatement(expr); } // ECMA-262 14.1 Function Definition function parseFunctionSourceElements() { var statement, body = [], token, directive, firstRestricted, oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, node = new Node(); expect('{'); while (startIndex < length) { if (lookahead.type !== Token.StringLiteral) { break; } token = lookahead; statement = parseStatementListItem(); body.push(statement); if (statement.expression.type !== Syntax.Literal) { // this is not directive break; } directive = source.slice(token.start + 1, token.end - 1); if (directive === 'use strict') { strict = true; if (firstRestricted) { tolerateUnexpectedToken(firstRestricted, Messages.StrictOctalLiteral); } } else { if (!firstRestricted && token.octal) { firstRestricted = token; } } } oldLabelSet = state.labelSet; oldInIteration = state.inIteration; oldInSwitch = state.inSwitch; oldInFunctionBody = state.inFunctionBody; state.labelSet = {}; state.inIteration = false; state.inSwitch = false; state.inFunctionBody = true; while (startIndex < length) { if (match('}')) { break; } body.push(parseStatementListItem()); } expect('}'); state.labelSet = oldLabelSet; state.inIteration = oldInIteration; state.inSwitch = oldInSwitch; state.inFunctionBody = oldInFunctionBody; return node.finishBlockStatement(body); } function validateParam(options, param, name) { var key = '$' + name; if (strict) { if (isRestrictedWord(name)) { options.stricted = param; options.message = Messages.StrictParamName; } if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) { options.stricted = param; options.message = Messages.StrictParamDupe; } } else if (!options.firstRestricted) { if (isRestrictedWord(name)) { options.firstRestricted = param; options.message = Messages.StrictParamName; } else if (isStrictModeReservedWord(name)) { options.firstRestricted = param; options.message = Messages.StrictReservedWord; } else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) { options.stricted = param; options.message = Messages.StrictParamDupe; } } options.paramSet[key] = true; } function parseParam(options) { var token, param, params = [], i, def; token = lookahead; if (token.value === '...') { param = parseRestElement(params); validateParam(options, param.argument, param.argument.name); options.params.push(param); options.defaults.push(null); return false; } param = parsePatternWithDefault(params); for (i = 0; i < params.length; i++) { validateParam(options, params[i], params[i].value); } if (param.type === Syntax.AssignmentPattern) { def = param.right; param = param.left; ++options.defaultCount; } options.params.push(param); options.defaults.push(def); return !match(')'); } function parseParams(firstRestricted) { var options; options = { params: [], defaultCount: 0, defaults: [], firstRestricted: firstRestricted }; expect('('); if (!match(')')) { options.paramSet = {}; while (startIndex < length) { if (!parseParam(options)) { break; } expect(','); } } expect(')'); if (options.defaultCount === 0) { options.defaults = []; } return { params: options.params, defaults: options.defaults, stricted: options.stricted, firstRestricted: options.firstRestricted, message: options.message }; } function parseFunctionDeclaration(node, identifierIsOptional) { var id = null, params = [], defaults = [], body, token, stricted, tmp, firstRestricted, message, previousStrict, isGenerator, previousAllowYield; previousAllowYield = state.allowYield; expectKeyword('function'); isGenerator = match('*'); if (isGenerator) { lex(); } if (!identifierIsOptional || !match('(')) { token = lookahead; id = parseVariableIdentifier(); if (strict) { if (isRestrictedWord(token.value)) { tolerateUnexpectedToken(token, Messages.StrictFunctionName); } } else { if (isRestrictedWord(token.value)) { firstRestricted = token; message = Messages.StrictFunctionName; } else if (isStrictModeReservedWord(token.value)) { firstRestricted = token; message = Messages.StrictReservedWord; } } } state.allowYield = !isGenerator; tmp = parseParams(firstRestricted); params = tmp.params; defaults = tmp.defaults; stricted = tmp.stricted; firstRestricted = tmp.firstRestricted; if (tmp.message) { message = tmp.message; } previousStrict = strict; body = parseFunctionSourceElements(); if (strict && firstRestricted) { throwUnexpectedToken(firstRestricted, message); } if (strict && stricted) { tolerateUnexpectedToken(stricted, message); } strict = previousStrict; state.allowYield = previousAllowYield; return node.finishFunctionDeclaration(id, params, defaults, body, isGenerator); } function parseFunctionExpression() { var token, id = null, stricted, firstRestricted, message, tmp, params = [], defaults = [], body, previousStrict, node = new Node(), isGenerator, previousAllowYield; previousAllowYield = state.allowYield; expectKeyword('function'); isGenerator = match('*'); if (isGenerator) { lex(); } state.allowYield = !isGenerator; if (!match('(')) { token = lookahead; id = (!strict && !isGenerator && matchKeyword('yield')) ? parseNonComputedProperty() : parseVariableIdentifier(); if (strict) { if (isRestrictedWord(token.value)) { tolerateUnexpectedToken(token, Messages.StrictFunctionName); } } else { if (isRestrictedWord(token.value)) { firstRestricted = token; message = Messages.StrictFunctionName; } else if (isStrictModeReservedWord(token.value)) { firstRestricted = token; message = Messages.StrictReservedWord; } } } tmp = parseParams(firstRestricted); params = tmp.params; defaults = tmp.defaults; stricted = tmp.stricted; firstRestricted = tmp.firstRestricted; if (tmp.message) { message = tmp.message; } previousStrict = strict; body = parseFunctionSourceElements(); if (strict && firstRestricted) { throwUnexpectedToken(firstRestricted, message); } if (strict && stricted) { tolerateUnexpectedToken(stricted, message); } strict = previousStrict; state.allowYield = previousAllowYield; return node.finishFunctionExpression(id, params, defaults, body, isGenerator); } // ECMA-262 14.5 Class Definitions function parseClassBody() { var classBody, token, isStatic, hasConstructor = false, body, method, computed, key; classBody = new Node(); expect('{'); body = []; while (!match('}')) { if (match(';')) { lex(); } else { method = new Node(); token = lookahead; isStatic = false; computed = match('['); if (match('*')) { lex(); } else { key = parseObjectPropertyKey(); if (key.name === 'static' && (lookaheadPropertyName() || match('*'))) { token = lookahead; isStatic = true; computed = match('['); if (match('*')) { lex(); } else { key = parseObjectPropertyKey(); } } } method = tryParseMethodDefinition(token, key, computed, method); if (method) { method['static'] = isStatic; // jscs:ignore requireDotNotation if (method.kind === 'init') { method.kind = 'method'; } if (!isStatic) { if (!method.computed && (method.key.name || method.key.value.toString()) === 'constructor') { if (method.kind !== 'method' || !method.method || method.value.generator) { throwUnexpectedToken(token, Messages.ConstructorSpecialMethod); } if (hasConstructor) { throwUnexpectedToken(token, Messages.DuplicateConstructor); } else { hasConstructor = true; } method.kind = 'constructor'; } } else { if (!method.computed && (method.key.name || method.key.value.toString()) === 'prototype') { throwUnexpectedToken(token, Messages.StaticPrototype); } } method.type = Syntax.MethodDefinition; delete method.method; delete method.shorthand; body.push(method); } else { throwUnexpectedToken(lookahead); } } } lex(); return classBody.finishClassBody(body); } function parseClassDeclaration(identifierIsOptional) { var id = null, superClass = null, classNode = new Node(), classBody, previousStrict = strict; strict = true; expectKeyword('class'); if (!identifierIsOptional || lookahead.type === Token.Identifier) { id = parseVariableIdentifier(); } if (matchKeyword('extends')) { lex(); superClass = isolateCoverGrammar(parseLeftHandSideExpressionAllowCall); } classBody = parseClassBody(); strict = previousStrict; return classNode.finishClassDeclaration(id, superClass, classBody); } function parseClassExpression() { var id = null, superClass = null, classNode = new Node(), classBody, previousStrict = strict; strict = true; expectKeyword('class'); if (lookahead.type === Token.Identifier) { id = parseVariableIdentifier(); } if (matchKeyword('extends')) { lex(); superClass = isolateCoverGrammar(parseLeftHandSideExpressionAllowCall); } classBody = parseClassBody(); strict = previousStrict; return classNode.finishClassExpression(id, superClass, classBody); } // ECMA-262 15.2 Modules function parseModuleSpecifier() { var node = new Node(); if (lookahead.type !== Token.StringLiteral) { throwError(Messages.InvalidModuleSpecifier); } return node.finishLiteral(lex()); } // ECMA-262 15.2.3 Exports function parseExportSpecifier() { var exported, local, node = new Node(), def; if (matchKeyword('default')) { // export {default} from 'something'; def = new Node(); lex(); local = def.finishIdentifier('default'); } else { local = parseVariableIdentifier(); } if (matchContextualKeyword('as')) { lex(); exported = parseNonComputedProperty(); } return node.finishExportSpecifier(local, exported); } function parseExportNamedDeclaration(node) { var declaration = null, isExportFromIdentifier, src = null, specifiers = []; // non-default export if (lookahead.type === Token.Keyword) { // covers: // export var f = 1; switch (lookahead.value) { case 'let': case 'const': declaration = parseLexicalDeclaration({inFor: false}); return node.finishExportNamedDeclaration(declaration, specifiers, null); case 'var': case 'class': case 'function': declaration = parseStatementListItem(); return node.finishExportNamedDeclaration(declaration, specifiers, null); } } expect('{'); while (!match('}')) { isExportFromIdentifier = isExportFromIdentifier || matchKeyword('default'); specifiers.push(parseExportSpecifier()); if (!match('}')) { expect(','); if (match('}')) { break; } } } expect('}'); if (matchContextualKeyword('from')) { // covering: // export {default} from 'foo'; // export {foo} from 'foo'; lex(); src = parseModuleSpecifier(); consumeSemicolon(); } else if (isExportFromIdentifier) { // covering: // export {default}; // missing fromClause throwError(lookahead.value ? Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value); } else { // cover // export {foo}; consumeSemicolon(); } return node.finishExportNamedDeclaration(declaration, specifiers, src); } function parseExportDefaultDeclaration(node) { var declaration = null, expression = null; // covers: // export default ... expectKeyword('default'); if (matchKeyword('function')) { // covers: // export default function foo () {} // export default function () {} declaration = parseFunctionDeclaration(new Node(), true); return node.finishExportDefaultDeclaration(declaration); } if (matchKeyword('class')) { declaration = parseClassDeclaration(true); return node.finishExportDefaultDeclaration(declaration); } if (matchContextualKeyword('from')) { throwError(Messages.UnexpectedToken, lookahead.value); } // covers: // export default {}; // export default []; // export default (1 + 2); if (match('{')) { expression = parseObjectInitializer(); } else if (match('[')) { expression = parseArrayInitializer(); } else { expression = parseAssignmentExpression(); } consumeSemicolon(); return node.finishExportDefaultDeclaration(expression); } function parseExportAllDeclaration(node) { var src; // covers: // export * from 'foo'; expect('*'); if (!matchContextualKeyword('from')) { throwError(lookahead.value ? Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value); } lex(); src = parseModuleSpecifier(); consumeSemicolon(); return node.finishExportAllDeclaration(src); } function parseExportDeclaration() { var node = new Node(); if (state.inFunctionBody) { throwError(Messages.IllegalExportDeclaration); } expectKeyword('export'); if (matchKeyword('default')) { return parseExportDefaultDeclaration(node); } if (match('*')) { return parseExportAllDeclaration(node); } return parseExportNamedDeclaration(node); } // ECMA-262 15.2.2 Imports function parseImportSpecifier() { // import {<foo as bar>} ...; var local, imported, node = new Node(); imported = parseNonComputedProperty(); if (matchContextualKeyword('as')) { lex(); local = parseVariableIdentifier(); } return node.finishImportSpecifier(local, imported); } function parseNamedImports() { var specifiers = []; // {foo, bar as bas} expect('{'); while (!match('}')) { specifiers.push(parseImportSpecifier()); if (!match('}')) { expect(','); if (match('}')) { break; } } } expect('}'); return specifiers; } function parseImportDefaultSpecifier() { // import <foo> ...; var local, node = new Node(); local = parseNonComputedProperty(); return node.finishImportDefaultSpecifier(local); } function parseImportNamespaceSpecifier() { // import <* as foo> ...; var local, node = new Node(); expect('*'); if (!matchContextualKeyword('as')) { throwError(Messages.NoAsAfterImportNamespace); } lex(); local = parseNonComputedProperty(); return node.finishImportNamespaceSpecifier(local); } function parseImportDeclaration() { var specifiers = [], src, node = new Node(); if (state.inFunctionBody) { throwError(Messages.IllegalImportDeclaration); } expectKeyword('import'); if (lookahead.type === Token.StringLiteral) { // import 'foo'; src = parseModuleSpecifier(); } else { if (match('{')) { // import {bar} specifiers = specifiers.concat(parseNamedImports()); } else if (match('*')) { // import * as foo specifiers.push(parseImportNamespaceSpecifier()); } else if (isIdentifierName(lookahead) && !matchKeyword('default')) { // import foo specifiers.push(parseImportDefaultSpecifier()); if (match(',')) { lex(); if (match('*')) { // import foo, * as foo specifiers.push(parseImportNamespaceSpecifier()); } else if (match('{')) { // import foo, {bar} specifiers = specifiers.concat(parseNamedImports()); } else { throwUnexpectedToken(lookahead); } } } else { throwUnexpectedToken(lex()); } if (!matchContextualKeyword('from')) { throwError(lookahead.value ? Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value); } lex(); src = parseModuleSpecifier(); } consumeSemicolon(); return node.finishImportDeclaration(specifiers, src); } // ECMA-262 15.1 Scripts function parseScriptBody() { var statement, body = [], token, directive, firstRestricted; while (startIndex < length) { token = lookahead; if (token.type !== Token.StringLiteral) { break; } statement = parseStatementListItem(); body.push(statement); if (statement.expression.type !== Syntax.Literal) { // this is not directive break; } directive = source.slice(token.start + 1, token.end - 1); if (directive === 'use strict') { strict = true; if (firstRestricted) { tolerateUnexpectedToken(firstRestricted, Messages.StrictOctalLiteral); } } else { if (!firstRestricted && token.octal) { firstRestricted = token; } } } while (startIndex < length) { statement = parseStatementListItem(); /* istanbul ignore if */ if (typeof statement === 'undefined') { break; } body.push(statement); } return body; } function parseProgram() { var body, node; peek(); node = new Node(); body = parseScriptBody(); return node.finishProgram(body, state.sourceType); } function filterTokenLocation() { var i, entry, token, tokens = []; for (i = 0; i < extra.tokens.length; ++i) { entry = extra.tokens[i]; token = { type: entry.type, value: entry.value }; if (entry.regex) { token.regex = { pattern: entry.regex.pattern, flags: entry.regex.flags }; } if (extra.range) { token.range = entry.range; } if (extra.loc) { token.loc = entry.loc; } tokens.push(token); } extra.tokens = tokens; } function tokenize(code, options, delegate) { var toString, tokens; toString = String; if (typeof code !== 'string' && !(code instanceof String)) { code = toString(code); } source = code; index = 0; lineNumber = (source.length > 0) ? 1 : 0; lineStart = 0; startIndex = index; startLineNumber = lineNumber; startLineStart = lineStart; length = source.length; lookahead = null; state = { allowIn: true, allowYield: true, labelSet: {}, inFunctionBody: false, inIteration: false, inSwitch: false, lastCommentStart: -1, curlyStack: [] }; extra = {}; // Options matching. options = options || {}; // Of course we collect tokens here. options.tokens = true; extra.tokens = []; extra.tokenValues = []; extra.tokenize = true; extra.delegate = delegate; // The following two fields are necessary to compute the Regex tokens. extra.openParenToken = -1; extra.openCurlyToken = -1; extra.range = (typeof options.range === 'boolean') && options.range; extra.loc = (typeof options.loc === 'boolean') && options.loc; if (typeof options.comment === 'boolean' && options.comment) { extra.comments = []; } if (typeof options.tolerant === 'boolean' && options.tolerant) { extra.errors = []; } try { peek(); if (lookahead.type === Token.EOF) { return extra.tokens; } lex(); while (lookahead.type !== Token.EOF) { try { lex(); } catch (lexError) { if (extra.errors) { recordError(lexError); // We have to break on the first error // to avoid infinite loops. break; } else { throw lexError; } } } tokens = extra.tokens; if (typeof extra.errors !== 'undefined') { tokens.errors = extra.errors; } } catch (e) { throw e; } finally { extra = {}; } return tokens; } function parse(code, options) { var program, toString; toString = String; if (typeof code !== 'string' && !(code instanceof String)) { code = toString(code); } source = code; index = 0; lineNumber = (source.length > 0) ? 1 : 0; lineStart = 0; startIndex = index; startLineNumber = lineNumber; startLineStart = lineStart; length = source.length; lookahead = null; state = { allowIn: true, allowYield: true, labelSet: {}, inFunctionBody: false, inIteration: false, inSwitch: false, lastCommentStart: -1, curlyStack: [], sourceType: 'script' }; strict = false; extra = {}; if (typeof options !== 'undefined') { extra.range = (typeof options.range === 'boolean') && options.range; extra.loc = (typeof options.loc === 'boolean') && options.loc; extra.attachComment = (typeof options.attachComment === 'boolean') && options.attachComment; if (extra.loc && options.source !== null && options.source !== undefined) { extra.source = toString(options.source); } if (typeof options.tokens === 'boolean' && options.tokens) { extra.tokens = []; } if (typeof options.comment === 'boolean' && options.comment) { extra.comments = []; } if (typeof options.tolerant === 'boolean' && options.tolerant) { extra.errors = []; } if (extra.attachComment) { extra.range = true; extra.comments = []; extra.bottomRightStack = []; extra.trailingComments = []; extra.leadingComments = []; } if (options.sourceType === 'module') { // very restrictive condition for now state.sourceType = options.sourceType; strict = true; } } try { program = parseProgram(); if (typeof extra.comments !== 'undefined') { program.comments = extra.comments; } if (typeof extra.tokens !== 'undefined') { filterTokenLocation(); program.tokens = extra.tokens; } if (typeof extra.errors !== 'undefined') { program.errors = extra.errors; } } catch (e) { throw e; } finally { extra = {}; } return program; } // Sync with *.json manifests. exports.version = '2.7.2'; exports.tokenize = tokenize; exports.parse = parse; // Deep copy. /* istanbul ignore next */ exports.Syntax = (function () { var name, types = {}; if (typeof Object.create === 'function') { types = Object.create(null); } for (name in Syntax) { if (Syntax.hasOwnProperty(name)) { types[name] = Syntax[name]; } } if (typeof Object.freeze === 'function') { Object.freeze(types); } return types; }()); })); /* vim: set sw=4 ts=4 et tw=80 : */ /*global define, Reflect */ /* * xpcshell has a smaller stack on linux and windows (1MB vs 9MB on mac), * and the recursive nature of esprima can cause it to overflow pretty * quickly. So favor it built in Reflect parser: * https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API */ define('esprimaAdapter', ['./esprima', 'env'], function (esprima, env) { if (env.get() === 'xpconnect' && typeof Reflect !== 'undefined') { return Reflect; } else { return esprima; } }); (function webpackUniversalModuleDefinition(root, factory) { var exports, module; if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define('source-map', [], factory); else if(typeof exports === 'object') exports["sourceMap"] = factory(); else root["sourceMap"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { /* * Copyright 2009-2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE.txt or: * http://opensource.org/licenses/BSD-3-Clause */ exports.SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; exports.SourceMapConsumer = __webpack_require__(7).SourceMapConsumer; exports.SourceNode = __webpack_require__(10).SourceNode; /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ { var base64VLQ = __webpack_require__(2); var util = __webpack_require__(4); var ArraySet = __webpack_require__(5).ArraySet; var MappingList = __webpack_require__(6).MappingList; /** * An instance of the SourceMapGenerator represents a source map which is * being built incrementally. You may pass an object with the following * properties: * * - file: The filename of the generated source. * - sourceRoot: A root for all relative URLs in this source map. */ function SourceMapGenerator(aArgs) { if (!aArgs) { aArgs = {}; } this._file = util.getArg(aArgs, 'file', null); this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); this._skipValidation = util.getArg(aArgs, 'skipValidation', false); this._sources = new ArraySet(); this._names = new ArraySet(); this._mappings = new MappingList(); this._sourcesContents = null; } SourceMapGenerator.prototype._version = 3; /** * Creates a new SourceMapGenerator based on a SourceMapConsumer * * @param aSourceMapConsumer The SourceMap. */ SourceMapGenerator.fromSourceMap = function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { var sourceRoot = aSourceMapConsumer.sourceRoot; var generator = new SourceMapGenerator({ file: aSourceMapConsumer.file, sourceRoot: sourceRoot }); aSourceMapConsumer.eachMapping(function (mapping) { var newMapping = { generated: { line: mapping.generatedLine, column: mapping.generatedColumn } }; if (mapping.source != null) { newMapping.source = mapping.source; if (sourceRoot != null) { newMapping.source = util.relative(sourceRoot, newMapping.source); } newMapping.original = { line: mapping.originalLine, column: mapping.originalColumn }; if (mapping.name != null) { newMapping.name = mapping.name; } } generator.addMapping(newMapping); }); aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content != null) { generator.setSourceContent(sourceFile, content); } }); return generator; }; /** * Add a single mapping from original source line and column to the generated * source's line and column for this source map being created. The mapping * object should have the following properties: * * - generated: An object with the generated line and column positions. * - original: An object with the original line and column positions. * - source: The original source file (relative to the sourceRoot). * - name: An optional original token name for this mapping. */ SourceMapGenerator.prototype.addMapping = function SourceMapGenerator_addMapping(aArgs) { var generated = util.getArg(aArgs, 'generated'); var original = util.getArg(aArgs, 'original', null); var source = util.getArg(aArgs, 'source', null); var name = util.getArg(aArgs, 'name', null); if (!this._skipValidation) { this._validateMapping(generated, original, source, name); } if (source != null && !this._sources.has(source)) { this._sources.add(source); } if (name != null && !this._names.has(name)) { this._names.add(name); } this._mappings.add({ generatedLine: generated.line, generatedColumn: generated.column, originalLine: original != null && original.line, originalColumn: original != null && original.column, source: source, name: name }); }; /** * Set the source content for a source file. */ SourceMapGenerator.prototype.setSourceContent = function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { var source = aSourceFile; if (this._sourceRoot != null) { source = util.relative(this._sourceRoot, source); } if (aSourceContent != null) { // Add the source content to the _sourcesContents map. // Create a new _sourcesContents map if the property is null. if (!this._sourcesContents) { this._sourcesContents = {}; } this._sourcesContents[util.toSetString(source)] = aSourceContent; } else if (this._sourcesContents) { // Remove the source file from the _sourcesContents map. // If the _sourcesContents map is empty, set the property to null. delete this._sourcesContents[util.toSetString(source)]; if (Object.keys(this._sourcesContents).length === 0) { this._sourcesContents = null; } } }; /** * Applies the mappings of a sub-source-map for a specific source file to the * source map being generated. Each mapping to the supplied source file is * rewritten using the supplied source map. Note: The resolution for the * resulting mappings is the minimium of this map and the supplied map. * * @param aSourceMapConsumer The source map to be applied. * @param aSourceFile Optional. The filename of the source file. * If omitted, SourceMapConsumer's file property will be used. * @param aSourceMapPath Optional. The dirname of the path to the source map * to be applied. If relative, it is relative to the SourceMapConsumer. * This parameter is needed when the two source maps aren't in the same * directory, and the source map to be applied contains relative source * paths. If so, those relative source paths need to be rewritten * relative to the SourceMapGenerator. */ SourceMapGenerator.prototype.applySourceMap = function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { var sourceFile = aSourceFile; // If aSourceFile is omitted, we will use the file property of the SourceMap if (aSourceFile == null) { if (aSourceMapConsumer.file == null) { throw new Error( 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + 'or the source map\'s "file" property. Both were omitted.' ); } sourceFile = aSourceMapConsumer.file; } var sourceRoot = this._sourceRoot; // Make "sourceFile" relative if an absolute Url is passed. if (sourceRoot != null) { sourceFile = util.relative(sourceRoot, sourceFile); } // Applying the SourceMap can add and remove items from the sources and // the names array. var newSources = new ArraySet(); var newNames = new ArraySet(); // Find mappings for the "sourceFile" this._mappings.unsortedForEach(function (mapping) { if (mapping.source === sourceFile && mapping.originalLine != null) { // Check if it can be mapped by the source map, then update the mapping. var original = aSourceMapConsumer.originalPositionFor({ line: mapping.originalLine, column: mapping.originalColumn }); if (original.source != null) { // Copy mapping mapping.source = original.source; if (aSourceMapPath != null) { mapping.source = util.join(aSourceMapPath, mapping.source) } if (sourceRoot != null) { mapping.source = util.relative(sourceRoot, mapping.source); } mapping.originalLine = original.line; mapping.originalColumn = original.column; if (original.name != null) { mapping.name = original.name; } } } var source = mapping.source; if (source != null && !newSources.has(source)) { newSources.add(source); } var name = mapping.name; if (name != null && !newNames.has(name)) { newNames.add(name); } }, this); this._sources = newSources; this._names = newNames; // Copy sourcesContents of applied map. aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content != null) { if (aSourceMapPath != null) { sourceFile = util.join(aSourceMapPath, sourceFile); } if (sourceRoot != null) { sourceFile = util.relative(sourceRoot, sourceFile); } this.setSourceContent(sourceFile, content); } }, this); }; /** * A mapping can have one of the three levels of data: * * 1. Just the generated position. * 2. The Generated position, original position, and original source. * 3. Generated and original position, original source, as well as a name * token. * * To maintain consistency, we validate that any new mapping being added falls * in to one of these categories. */ SourceMapGenerator.prototype._validateMapping = function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, aName) { if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aGenerated.line > 0 && aGenerated.column >= 0 && !aOriginal && !aSource && !aName) { // Case 1. return; } else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aOriginal && 'line' in aOriginal && 'column' in aOriginal && aGenerated.line > 0 && aGenerated.column >= 0 && aOriginal.line > 0 && aOriginal.column >= 0 && aSource) { // Cases 2 and 3. return; } else { throw new Error('Invalid mapping: ' + JSON.stringify({ generated: aGenerated, source: aSource, original: aOriginal, name: aName })); } }; /** * Serialize the accumulated mappings in to the stream of base 64 VLQs * specified by the source map format. */ SourceMapGenerator.prototype._serializeMappings = function SourceMapGenerator_serializeMappings() { var previousGeneratedColumn = 0; var previousGeneratedLine = 1; var previousOriginalColumn = 0; var previousOriginalLine = 0; var previousName = 0; var previousSource = 0; var result = ''; var mapping; var nameIdx; var sourceIdx; var mappings = this._mappings.toArray(); for (var i = 0, len = mappings.length; i < len; i++) { mapping = mappings[i]; if (mapping.generatedLine !== previousGeneratedLine) { previousGeneratedColumn = 0; while (mapping.generatedLine !== previousGeneratedLine) { result += ';'; previousGeneratedLine++; } } else { if (i > 0) { if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { continue; } result += ','; } } result += base64VLQ.encode(mapping.generatedColumn - previousGeneratedColumn); previousGeneratedColumn = mapping.generatedColumn; if (mapping.source != null) { sourceIdx = this._sources.indexOf(mapping.source); result += base64VLQ.encode(sourceIdx - previousSource); previousSource = sourceIdx; // lines are stored 0-based in SourceMap spec version 3 result += base64VLQ.encode(mapping.originalLine - 1 - previousOriginalLine); previousOriginalLine = mapping.originalLine - 1; result += base64VLQ.encode(mapping.originalColumn - previousOriginalColumn); previousOriginalColumn = mapping.originalColumn; if (mapping.name != null) { nameIdx = this._names.indexOf(mapping.name); result += base64VLQ.encode(nameIdx - previousName); previousName = nameIdx; } } } return result; }; SourceMapGenerator.prototype._generateSourcesContent = function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { return aSources.map(function (source) { if (!this._sourcesContents) { return null; } if (aSourceRoot != null) { source = util.relative(aSourceRoot, source); } var key = util.toSetString(source); return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) ? this._sourcesContents[key] : null; }, this); }; /** * Externalize the source map. */ SourceMapGenerator.prototype.toJSON = function SourceMapGenerator_toJSON() { var map = { version: this._version, sources: this._sources.toArray(), names: this._names.toArray(), mappings: this._serializeMappings() }; if (this._file != null) { map.file = this._file; } if (this._sourceRoot != null) { map.sourceRoot = this._sourceRoot; } if (this._sourcesContents) { map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); } return map; }; /** * Render the source map being generated to a string. */ SourceMapGenerator.prototype.toString = function SourceMapGenerator_toString() { return JSON.stringify(this.toJSON()); }; exports.SourceMapGenerator = SourceMapGenerator; } /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause * * Based on the Base 64 VLQ implementation in Closure Compiler: * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java * * Copyright 2011 The Closure Compiler Authors. All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ { var base64 = __webpack_require__(3); // A single base 64 digit can contain 6 bits of data. For the base 64 variable // length quantities we use in the source map spec, the first bit is the sign, // the next four bits are the actual value, and the 6th bit is the // continuation bit. The continuation bit tells us whether there are more // digits in this value following this digit. // // Continuation // | Sign // | | // V V // 101011 var VLQ_BASE_SHIFT = 5; // binary: 100000 var VLQ_BASE = 1 << VLQ_BASE_SHIFT; // binary: 011111 var VLQ_BASE_MASK = VLQ_BASE - 1; // binary: 100000 var VLQ_CONTINUATION_BIT = VLQ_BASE; /** * Converts from a two-complement value to a value where the sign bit is * placed in the least significant bit. For example, as decimals: * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) */ function toVLQSigned(aValue) { return aValue < 0 ? ((-aValue) << 1) + 1 : (aValue << 1) + 0; } /** * Converts to a two-complement value from a value where the sign bit is * placed in the least significant bit. For example, as decimals: * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 */ function fromVLQSigned(aValue) { var isNegative = (aValue & 1) === 1; var shifted = aValue >> 1; return isNegative ? -shifted : shifted; } /** * Returns the base 64 VLQ encoded value. */ exports.encode = function base64VLQ_encode(aValue) { var encoded = ""; var digit; var vlq = toVLQSigned(aValue); do { digit = vlq & VLQ_BASE_MASK; vlq >>>= VLQ_BASE_SHIFT; if (vlq > 0) { // There are still more digits in this value, so we must make sure the // continuation bit is marked. digit |= VLQ_CONTINUATION_BIT; } encoded += base64.encode(digit); } while (vlq > 0); return encoded; }; /** * Decodes the next base 64 VLQ value from the given string and returns the * value and the rest of the string via the out parameter. */ exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { var strLen = aStr.length; var result = 0; var shift = 0; var continuation, digit; do { if (aIndex >= strLen) { throw new Error("Expected more digits in base 64 VLQ value."); } digit = base64.decode(aStr.charCodeAt(aIndex++)); if (digit === -1) { throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); } continuation = !!(digit & VLQ_CONTINUATION_BIT); digit &= VLQ_BASE_MASK; result = result + (digit << shift); shift += VLQ_BASE_SHIFT; } while (continuation); aOutParam.value = fromVLQSigned(result); aOutParam.rest = aIndex; }; } /***/ }, /* 3 */ /***/ function(module, exports) { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ { var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); /** * Encode an integer in the range of 0 to 63 to a single base 64 digit. */ exports.encode = function (number) { if (0 <= number && number < intToCharMap.length) { return intToCharMap[number]; } throw new TypeError("Must be between 0 and 63: " + number); }; /** * Decode a single base 64 character code digit to an integer. Returns -1 on * failure. */ exports.decode = function (charCode) { var bigA = 65; // 'A' var bigZ = 90; // 'Z' var littleA = 97; // 'a' var littleZ = 122; // 'z' var zero = 48; // '0' var nine = 57; // '9' var plus = 43; // '+' var slash = 47; // '/' var littleOffset = 26; var numberOffset = 52; // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ if (bigA <= charCode && charCode <= bigZ) { return (charCode - bigA); } // 26 - 51: abcdefghijklmnopqrstuvwxyz if (littleA <= charCode && charCode <= littleZ) { return (charCode - littleA + littleOffset); } // 52 - 61: 0123456789 if (zero <= charCode && charCode <= nine) { return (charCode - zero + numberOffset); } // 62: + if (charCode == plus) { return 62; } // 63: / if (charCode == slash) { return 63; } // Invalid base64 digit. return -1; }; } /***/ }, /* 4 */ /***/ function(module, exports) { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ { /** * This is a helper function for getting values from parameter/options * objects. * * @param args The object we are extracting values from * @param name The name of the property we are getting. * @param defaultValue An optional value to return if the property is missing * from the object. If this is not specified and the property is missing, an * error will be thrown. */ function getArg(aArgs, aName, aDefaultValue) { if (aName in aArgs) { return aArgs[aName]; } else if (arguments.length === 3) { return aDefaultValue; } else { throw new Error('"' + aName + '" is a required argument.'); } } exports.getArg = getArg; var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/; var dataUrlRegexp = /^data:.+\,.+$/; function urlParse(aUrl) { var match = aUrl.match(urlRegexp); if (!match) { return null; } return { scheme: match[1], auth: match[2], host: match[3], port: match[4], path: match[5] }; } exports.urlParse = urlParse; function urlGenerate(aParsedUrl) { var url = ''; if (aParsedUrl.scheme) { url += aParsedUrl.scheme + ':'; } url += '//'; if (aParsedUrl.auth) { url += aParsedUrl.auth + '@'; } if (aParsedUrl.host) { url += aParsedUrl.host; } if (aParsedUrl.port) { url += ":" + aParsedUrl.port } if (aParsedUrl.path) { url += aParsedUrl.path; } return url; } exports.urlGenerate = urlGenerate; /** * Normalizes a path, or the path portion of a URL: * * - Replaces consequtive slashes with one slash. * - Removes unnecessary '.' parts. * - Removes unnecessary '<dir>/..' parts. * * Based on code in the Node.js 'path' core module. * * @param aPath The path or url to normalize. */ function normalize(aPath) { var path = aPath; var url = urlParse(aPath); if (url) { if (!url.path) { return aPath; } path = url.path; } var isAbsolute = exports.isAbsolute(path); var parts = path.split(/\/+/); for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { part = parts[i]; if (part === '.') { parts.splice(i, 1); } else if (part === '..') { up++; } else if (up > 0) { if (part === '') { // The first part is blank if the path is absolute. Trying to go // above the root is a no-op. Therefore we can remove all '..' parts // directly after the root. parts.splice(i + 1, up); up = 0; } else { parts.splice(i, 2); up--; } } } path = parts.join('/'); if (path === '') { path = isAbsolute ? '/' : '.'; } if (url) { url.path = path; return urlGenerate(url); } return path; } exports.normalize = normalize; /** * Joins two paths/URLs. * * @param aRoot The root path or URL. * @param aPath The path or URL to be joined with the root. * * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a * scheme-relative URL: Then the scheme of aRoot, if any, is prepended * first. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion * is updated with the result and aRoot is returned. Otherwise the result * is returned. * - If aPath is absolute, the result is aPath. * - Otherwise the two paths are joined with a slash. * - Joining for example 'http://' and 'www.example.com' is also supported. */ function join(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } if (aPath === "") { aPath = "."; } var aPathUrl = urlParse(aPath); var aRootUrl = urlParse(aRoot); if (aRootUrl) { aRoot = aRootUrl.path || '/'; } // `join(foo, '//www.example.org')` if (aPathUrl && !aPathUrl.scheme) { if (aRootUrl) { aPathUrl.scheme = aRootUrl.scheme; } return urlGenerate(aPathUrl); } if (aPathUrl || aPath.match(dataUrlRegexp)) { return aPath; } // `join('http://', 'www.example.com')` if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { aRootUrl.host = aPath; return urlGenerate(aRootUrl); } var joined = aPath.charAt(0) === '/' ? aPath : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); if (aRootUrl) { aRootUrl.path = joined; return urlGenerate(aRootUrl); } return joined; } exports.join = join; exports.isAbsolute = function (aPath) { return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp); }; /** * Make a path relative to a URL or another path. * * @param aRoot The root path or URL. * @param aPath The path or URL to be made relative to aRoot. */ function relative(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } aRoot = aRoot.replace(/\/$/, ''); // It is possible for the path to be above the root. In this case, simply // checking whether the root is a prefix of the path won't work. Instead, we // need to remove components from the root one by one, until either we find // a prefix that fits, or we run out of components to remove. var level = 0; while (aPath.indexOf(aRoot + '/') !== 0) { var index = aRoot.lastIndexOf("/"); if (index < 0) { return aPath; } // If the only part of the root that is left is the scheme (i.e. http://, // file:///, etc.), one or more slashes (/), or simply nothing at all, we // have exhausted all components, so the path is not relative to the root. aRoot = aRoot.slice(0, index); if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { return aPath; } ++level; } // Make sure we add a "../" for each component we removed from the root. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); } exports.relative = relative; /** * Because behavior goes wacky when you set `__proto__` on objects, we * have to prefix all the strings in our set with an arbitrary character. * * See https://github.com/mozilla/source-map/pull/31 and * https://github.com/mozilla/source-map/issues/30 * * @param String aStr */ function toSetString(aStr) { return '$' + aStr; } exports.toSetString = toSetString; function fromSetString(aStr) { return aStr.substr(1); } exports.fromSetString = fromSetString; /** * Comparator between two mappings where the original positions are compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same original source/line/column, but different generated * line and column the same. Useful when searching for a mapping with a * stubbed out mapping. */ function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { var cmp = mappingA.source - mappingB.source; if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0 || onlyCompareOriginal) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } return mappingA.name - mappingB.name; } exports.compareByOriginalPositions = compareByOriginalPositions; /** * Comparator between two mappings with deflated source and name indices where * the generated positions are compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same generated line and column, but different * source/name/original line and column the same. Useful when searching for a * mapping with a stubbed out mapping. */ function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { var cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0 || onlyCompareGenerated) { return cmp; } cmp = mappingA.source - mappingB.source; if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return mappingA.name - mappingB.name; } exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; function strcmp(aStr1, aStr2) { if (aStr1 === aStr2) { return 0; } if (aStr1 > aStr2) { return 1; } return -1; } /** * Comparator between two mappings with inflated source and name strings where * the generated positions are compared. */ function compareByGeneratedPositionsInflated(mappingA, mappingB) { var cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; } /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ { var util = __webpack_require__(4); /** * A data structure which is a combination of an array and a set. Adding a new * member is O(1), testing for membership is O(1), and finding the index of an * element is O(1). Removing elements from the set is not supported. Only * strings are supported for membership. */ function ArraySet() { this._array = []; this._set = {}; } /** * Static method for creating ArraySet instances from an existing array. */ ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { var set = new ArraySet(); for (var i = 0, len = aArray.length; i < len; i++) { set.add(aArray[i], aAllowDuplicates); } return set; }; /** * Return how many unique items are in this ArraySet. If duplicates have been * added, than those do not count towards the size. * * @returns Number */ ArraySet.prototype.size = function ArraySet_size() { return Object.getOwnPropertyNames(this._set).length; }; /** * Add the given string to this set. * * @param String aStr */ ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { var sStr = util.toSetString(aStr); var isDuplicate = this._set.hasOwnProperty(sStr); var idx = this._array.length; if (!isDuplicate || aAllowDuplicates) { this._array.push(aStr); } if (!isDuplicate) { this._set[sStr] = idx; } }; /** * Is the given string a member of this set? * * @param String aStr */ ArraySet.prototype.has = function ArraySet_has(aStr) { var sStr = util.toSetString(aStr); return this._set.hasOwnProperty(sStr); }; /** * What is the index of the given string in the array? * * @param String aStr */ ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { var sStr = util.toSetString(aStr); if (this._set.hasOwnProperty(sStr)) { return this._set[sStr]; } throw new Error('"' + aStr + '" is not in the set.'); }; /** * What is the element at the given index? * * @param Number aIdx */ ArraySet.prototype.at = function ArraySet_at(aIdx) { if (aIdx >= 0 && aIdx < this._array.length) { return this._array[aIdx]; } throw new Error('No element indexed by ' + aIdx); }; /** * Returns the array representation of this set (which has the proper indices * indicated by indexOf). Note that this is a copy of the internal array used * for storing the members so that no one can mess with internal state. */ ArraySet.prototype.toArray = function ArraySet_toArray() { return this._array.slice(); }; exports.ArraySet = ArraySet; } /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2014 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ { var util = __webpack_require__(4); /** * Determine whether mappingB is after mappingA with respect to generated * position. */ function generatedPositionAfter(mappingA, mappingB) { // Optimized for most common case var lineA = mappingA.generatedLine; var lineB = mappingB.generatedLine; var columnA = mappingA.generatedColumn; var columnB = mappingB.generatedColumn; return lineB > lineA || lineB == lineA && columnB >= columnA || util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; } /** * A data structure to provide a sorted view of accumulated mappings in a * performance conscious manner. It trades a neglibable overhead in general * case for a large speedup in case of mappings being added in order. */ function MappingList() { this._array = []; this._sorted = true; // Serves as infimum this._last = {generatedLine: -1, generatedColumn: 0}; } /** * Iterate through internal items. This method takes the same arguments that * `Array.prototype.forEach` takes. * * NOTE: The order of the mappings is NOT guaranteed. */ MappingList.prototype.unsortedForEach = function MappingList_forEach(aCallback, aThisArg) { this._array.forEach(aCallback, aThisArg); }; /** * Add the given source mapping. * * @param Object aMapping */ MappingList.prototype.add = function MappingList_add(aMapping) { if (generatedPositionAfter(this._last, aMapping)) { this._last = aMapping; this._array.push(aMapping); } else { this._sorted = false; this._array.push(aMapping); } }; /** * Returns the flat, sorted array of mappings. The mappings are sorted by * generated position. * * WARNING: This method returns internal data without copying, for * performance. The return value must NOT be mutated, and should be treated as * an immutable borrow. If you want to take ownership, you must make your own * copy. */ MappingList.prototype.toArray = function MappingList_toArray() { if (!this._sorted) { this._array.sort(util.compareByGeneratedPositionsInflated); this._sorted = true; } return this._array; }; exports.MappingList = MappingList; } /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ { var util = __webpack_require__(4); var binarySearch = __webpack_require__(8); var ArraySet = __webpack_require__(5).ArraySet; var base64VLQ = __webpack_require__(2); var quickSort = __webpack_require__(9).quickSort; function SourceMapConsumer(aSourceMap) { var sourceMap = aSourceMap; if (typeof aSourceMap === 'string') { sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); } return sourceMap.sections != null ? new IndexedSourceMapConsumer(sourceMap) : new BasicSourceMapConsumer(sourceMap); } SourceMapConsumer.fromSourceMap = function(aSourceMap) { return BasicSourceMapConsumer.fromSourceMap(aSourceMap); } /** * The version of the source mapping spec that we are consuming. */ SourceMapConsumer.prototype._version = 3; // `__generatedMappings` and `__originalMappings` are arrays that hold the // parsed mapping coordinates from the source map's "mappings" attribute. They // are lazily instantiated, accessed via the `_generatedMappings` and // `_originalMappings` getters respectively, and we only parse the mappings // and create these arrays once queried for a source location. We jump through // these hoops because there can be many thousands of mappings, and parsing // them is expensive, so we only want to do it if we must. // // Each object in the arrays is of the form: // // { // generatedLine: The line number in the generated code, // generatedColumn: The column number in the generated code, // source: The path to the original source file that generated this // chunk of code, // originalLine: The line number in the original source that // corresponds to this chunk of generated code, // originalColumn: The column number in the original source that // corresponds to this chunk of generated code, // name: The name of the original symbol which generated this chunk of // code. // } // // All properties except for `generatedLine` and `generatedColumn` can be // `null`. // // `_generatedMappings` is ordered by the generated positions. // // `_originalMappings` is ordered by the original positions. SourceMapConsumer.prototype.__generatedMappings = null; Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { get: function () { if (!this.__generatedMappings) { this._parseMappings(this._mappings, this.sourceRoot); } return this.__generatedMappings; } }); SourceMapConsumer.prototype.__originalMappings = null; Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { get: function () { if (!this.__originalMappings) { this._parseMappings(this._mappings, this.sourceRoot); } return this.__originalMappings; } }); SourceMapConsumer.prototype._charIsMappingSeparator = function SourceMapConsumer_charIsMappingSeparator(aStr, index) { var c = aStr.charAt(index); return c === ";" || c === ","; }; /** * Parse the mappings in a string in to a data structure which we can easily * query (the ordered arrays in the `this.__generatedMappings` and * `this.__originalMappings` properties). */ SourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { throw new Error("Subclasses must implement _parseMappings"); }; SourceMapConsumer.GENERATED_ORDER = 1; SourceMapConsumer.ORIGINAL_ORDER = 2; SourceMapConsumer.GREATEST_LOWER_BOUND = 1; SourceMapConsumer.LEAST_UPPER_BOUND = 2; /** * Iterate over each mapping between an original source/line/column and a * generated line/column in this source map. * * @param Function aCallback * The function that is called with each mapping. * @param Object aContext * Optional. If specified, this object will be the value of `this` every * time that `aCallback` is called. * @param aOrder * Either `SourceMapConsumer.GENERATED_ORDER` or * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to * iterate over the mappings sorted by the generated file's line/column * order or the original's source/line/column order, respectively. Defaults to * `SourceMapConsumer.GENERATED_ORDER`. */ SourceMapConsumer.prototype.eachMapping = function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { var context = aContext || null; var order = aOrder || SourceMapConsumer.GENERATED_ORDER; var mappings; switch (order) { case SourceMapConsumer.GENERATED_ORDER: mappings = this._generatedMappings; break; case SourceMapConsumer.ORIGINAL_ORDER: mappings = this._originalMappings; break; default: throw new Error("Unknown order of iteration."); } var sourceRoot = this.sourceRoot; mappings.map(function (mapping) { var source = mapping.source === null ? null : this._sources.at(mapping.source); if (source != null && sourceRoot != null) { source = util.join(sourceRoot, source); } return { source: source, generatedLine: mapping.generatedLine, generatedColumn: mapping.generatedColumn, originalLine: mapping.originalLine, originalColumn: mapping.originalColumn, name: mapping.name === null ? null : this._names.at(mapping.name) }; }, this).forEach(aCallback, context); }; /** * Returns all generated line and column information for the original source, * line, and column provided. If no column is provided, returns all mappings * corresponding to a either the line we are searching for or the next * closest line that has any mappings. Otherwise, returns all mappings * corresponding to the given line and either the column we are searching for * or the next closest column that has any offsets. * * The only argument is an object with the following properties: * * - source: The filename of the original source. * - line: The line number in the original source. * - column: Optional. the column number in the original source. * * and an array of objects is returned, each with the following properties: * * - line: The line number in the generated source, or null. * - column: The column number in the generated source, or null. */ SourceMapConsumer.prototype.allGeneratedPositionsFor = function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { var line = util.getArg(aArgs, 'line'); // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping // returns the index of the closest mapping less than the needle. By // setting needle.originalColumn to 0, we thus find the last mapping for // the given line, provided such a mapping exists. var needle = { source: util.getArg(aArgs, 'source'), originalLine: line, originalColumn: util.getArg(aArgs, 'column', 0) }; if (this.sourceRoot != null) { needle.source = util.relative(this.sourceRoot, needle.source); } if (!this._sources.has(needle.source)) { return []; } needle.source = this._sources.indexOf(needle.source); var mappings = []; var index = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util.compareByOriginalPositions, binarySearch.LEAST_UPPER_BOUND); if (index >= 0) { var mapping = this._originalMappings[index]; if (aArgs.column === undefined) { var originalLine = mapping.originalLine; // Iterate until either we run out of mappings, or we run into // a mapping for a different line than the one we found. Since // mappings are sorted, this is guaranteed to find all mappings for // the line we found. while (mapping && mapping.originalLine === originalLine) { mappings.push({ line: util.getArg(mapping, 'generatedLine', null), column: util.getArg(mapping, 'generatedColumn', null), lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) }); mapping = this._originalMappings[++index]; } } else { var originalColumn = mapping.originalColumn; // Iterate until either we run out of mappings, or we run into // a mapping for a different line than the one we were searching for. // Since mappings are sorted, this is guaranteed to find all mappings for // the line we are searching for. while (mapping && mapping.originalLine === line && mapping.originalColumn == originalColumn) { mappings.push({ line: util.getArg(mapping, 'generatedLine', null), column: util.getArg(mapping, 'generatedColumn', null), lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) }); mapping = this._originalMappings[++index]; } } } return mappings; }; exports.SourceMapConsumer = SourceMapConsumer; /** * A BasicSourceMapConsumer instance represents a parsed source map which we can * query for information about the original file positions by giving it a file * position in the generated source. * * The only parameter is the raw source map (either as a JSON string, or * already parsed to an object). According to the spec, source maps have the * following attributes: * * - version: Which version of the source map spec this map is following. * - sources: An array of URLs to the original source files. * - names: An array of identifiers which can be referrenced by individual mappings. * - sourceRoot: Optional. The URL root from which all sources are relative. * - sourcesContent: Optional. An array of contents of the original source files. * - mappings: A string of base64 VLQs which contain the actual mappings. * - file: Optional. The generated file this source map is associated with. * * Here is an example source map, taken from the source map spec[0]: * * { * version : 3, * file: "out.js", * sourceRoot : "", * sources: ["foo.js", "bar.js"], * names: ["src", "maps", "are", "fun"], * mappings: "AA,AB;;ABCDE;" * } * * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# */ function BasicSourceMapConsumer(aSourceMap) { var sourceMap = aSourceMap; if (typeof aSourceMap === 'string') { sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); } var version = util.getArg(sourceMap, 'version'); var sources = util.getArg(sourceMap, 'sources'); // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which // requires the array) to play nice here. var names = util.getArg(sourceMap, 'names', []); var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); var mappings = util.getArg(sourceMap, 'mappings'); var file = util.getArg(sourceMap, 'file', null); // Once again, Sass deviates from the spec and supplies the version as a // string rather than a number, so we use loose equality checking here. if (version != this._version) { throw new Error('Unsupported version: ' + version); } sources = sources // Some source maps produce relative source paths like "./foo.js" instead of // "foo.js". Normalize these first so that future comparisons will succeed. // See bugzil.la/1090768. .map(util.normalize) // Always ensure that absolute sources are internally stored relative to // the source root, if the source root is absolute. Not doing this would // be particularly problematic when the source root is a prefix of the // source (valid, but why??). See github issue #199 and bugzil.la/1188982. .map(function (source) { return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) ? util.relative(sourceRoot, source) : source; }); // Pass `true` below to allow duplicate names and sources. While source maps // are intended to be compressed and deduplicated, the TypeScript compiler // sometimes generates source maps with duplicates in them. See Github issue // #72 and bugzil.la/889492. this._names = ArraySet.fromArray(names, true); this._sources = ArraySet.fromArray(sources, true); this.sourceRoot = sourceRoot; this.sourcesContent = sourcesContent; this._mappings = mappings; this.file = file; } BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; /** * Create a BasicSourceMapConsumer from a SourceMapGenerator. * * @param SourceMapGenerator aSourceMap * The source map that will be consumed. * @returns BasicSourceMapConsumer */ BasicSourceMapConsumer.fromSourceMap = function SourceMapConsumer_fromSourceMap(aSourceMap) { var smc = Object.create(BasicSourceMapConsumer.prototype); var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); smc.sourceRoot = aSourceMap._sourceRoot; smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), smc.sourceRoot); smc.file = aSourceMap._file; // Because we are modifying the entries (by converting string sources and // names to indices into the sources and names ArraySets), we have to make // a copy of the entry or else bad things happen. Shared mutable state // strikes again! See github issue #191. var generatedMappings = aSourceMap._mappings.toArray().slice(); var destGeneratedMappings = smc.__generatedMappings = []; var destOriginalMappings = smc.__originalMappings = []; for (var i = 0, length = generatedMappings.length; i < length; i++) { var srcMapping = generatedMappings[i]; var destMapping = new Mapping; destMapping.generatedLine = srcMapping.generatedLine; destMapping.generatedColumn = srcMapping.generatedColumn; if (srcMapping.source) { destMapping.source = sources.indexOf(srcMapping.source); destMapping.originalLine = srcMapping.originalLine; destMapping.originalColumn = srcMapping.originalColumn; if (srcMapping.name) { destMapping.name = names.indexOf(srcMapping.name); } destOriginalMappings.push(destMapping); } destGeneratedMappings.push(destMapping); } quickSort(smc.__originalMappings, util.compareByOriginalPositions); return smc; }; /** * The version of the source mapping spec that we are consuming. */ BasicSourceMapConsumer.prototype._version = 3; /** * The list of original sources. */ Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { get: function () { return this._sources.toArray().map(function (s) { return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s; }, this); } }); /** * Provide the JIT with a nice shape / hidden class. */ function Mapping() { this.generatedLine = 0; this.generatedColumn = 0; this.source = null; this.originalLine = null; this.originalColumn = null; this.name = null; } /** * Parse the mappings in a string in to a data structure which we can easily * query (the ordered arrays in the `this.__generatedMappings` and * `this.__originalMappings` properties). */ BasicSourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { var generatedLine = 1; var previousGeneratedColumn = 0; var previousOriginalLine = 0; var previousOriginalColumn = 0; var previousSource = 0; var previousName = 0; var length = aStr.length; var index = 0; var cachedSegments = {}; var temp = {}; var originalMappings = []; var generatedMappings = []; var mapping, str, segment, end, value; while (index < length) { if (aStr.charAt(index) === ';') { generatedLine++; index++; previousGeneratedColumn = 0; } else if (aStr.charAt(index) === ',') { index++; } else { mapping = new Mapping(); mapping.generatedLine = generatedLine; // Because each offset is encoded relative to the previous one, // many segments often have the same encoding. We can exploit this // fact by caching the parsed variable length fields of each segment, // allowing us to avoid a second parse if we encounter the same // segment again. for (end = index; end < length; end++) { if (this._charIsMappingSeparator(aStr, end)) { break; } } str = aStr.slice(index, end); segment = cachedSegments[str]; if (segment) { index += str.length; } else { segment = []; while (index < end) { base64VLQ.decode(aStr, index, temp); value = temp.value; index = temp.rest; segment.push(value); } if (segment.length === 2) { throw new Error('Found a source, but no line and column'); } if (segment.length === 3) { throw new Error('Found a source and line, but no column'); } cachedSegments[str] = segment; } // Generated column. mapping.generatedColumn = previousGeneratedColumn + segment[0]; previousGeneratedColumn = mapping.generatedColumn; if (segment.length > 1) { // Original source. mapping.source = previousSource + segment[1]; previousSource += segment[1]; // Original line. mapping.originalLine = previousOriginalLine + segment[2]; previousOriginalLine = mapping.originalLine; // Lines are stored 0-based mapping.originalLine += 1; // Original column. mapping.originalColumn = previousOriginalColumn + segment[3]; previousOriginalColumn = mapping.originalColumn; if (segment.length > 4) { // Original name. mapping.name = previousName + segment[4]; previousName += segment[4]; } } generatedMappings.push(mapping); if (typeof mapping.originalLine === 'number') { originalMappings.push(mapping); } } } quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); this.__generatedMappings = generatedMappings; quickSort(originalMappings, util.compareByOriginalPositions); this.__originalMappings = originalMappings; }; /** * Find the mapping that best matches the hypothetical "needle" mapping that * we are searching for in the given "haystack" of mappings. */ BasicSourceMapConsumer.prototype._findMapping = function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, aColumnName, aComparator, aBias) { // To return the position we are searching for, we must first find the // mapping for the given position and then return the opposite position it // points to. Because the mappings are sorted, we can use binary search to // find the best mapping. if (aNeedle[aLineName] <= 0) { throw new TypeError('Line must be greater than or equal to 1, got ' + aNeedle[aLineName]); } if (aNeedle[aColumnName] < 0) { throw new TypeError('Column must be greater than or equal to 0, got ' + aNeedle[aColumnName]); } return binarySearch.search(aNeedle, aMappings, aComparator, aBias); }; /** * Compute the last column for each generated mapping. The last column is * inclusive. */ BasicSourceMapConsumer.prototype.computeColumnSpans = function SourceMapConsumer_computeColumnSpans() { for (var index = 0; index < this._generatedMappings.length; ++index) { var mapping = this._generatedMappings[index]; // Mappings do not contain a field for the last generated columnt. We // can come up with an optimistic estimate, however, by assuming that // mappings are contiguous (i.e. given two consecutive mappings, the // first mapping ends where the second one starts). if (index + 1 < this._generatedMappings.length) { var nextMapping = this._generatedMappings[index + 1]; if (mapping.generatedLine === nextMapping.generatedLine) { mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; continue; } } // The last mapping for each line spans the entire line. mapping.lastGeneratedColumn = Infinity; } }; /** * Returns the original source, line, and column information for the generated * source's line and column positions provided. The only argument is an object * with the following properties: * * - line: The line number in the generated source. * - column: The column number in the generated source. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the * closest element that is smaller than or greater than the one we are * searching for, respectively, if the exact element cannot be found. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. * * and an object is returned with the following properties: * * - source: The original source file, or null. * - line: The line number in the original source, or null. * - column: The column number in the original source, or null. * - name: The original identifier, or null. */ BasicSourceMapConsumer.prototype.originalPositionFor = function SourceMapConsumer_originalPositionFor(aArgs) { var needle = { generatedLine: util.getArg(aArgs, 'line'), generatedColumn: util.getArg(aArgs, 'column') }; var index = this._findMapping( needle, this._generatedMappings, "generatedLine", "generatedColumn", util.compareByGeneratedPositionsDeflated, util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) ); if (index >= 0) { var mapping = this._generatedMappings[index]; if (mapping.generatedLine === needle.generatedLine) { var source = util.getArg(mapping, 'source', null); if (source !== null) { source = this._sources.at(source); if (this.sourceRoot != null) { source = util.join(this.sourceRoot, source); } } var name = util.getArg(mapping, 'name', null); if (name !== null) { name = this._names.at(name); } return { source: source, line: util.getArg(mapping, 'originalLine', null), column: util.getArg(mapping, 'originalColumn', null), name: name }; } } return { source: null, line: null, column: null, name: null }; }; /** * Return true if we have the source content for every source in the source * map, false otherwise. */ BasicSourceMapConsumer.prototype.hasContentsOfAllSources = function BasicSourceMapConsumer_hasContentsOfAllSources() { if (!this.sourcesContent) { return false; } return this.sourcesContent.length >= this._sources.size() && !this.sourcesContent.some(function (sc) { return sc == null; }); }; /** * Returns the original source content. The only argument is the url of the * original source file. Returns null if no original source content is * available. */ BasicSourceMapConsumer.prototype.sourceContentFor = function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { if (!this.sourcesContent) { return null; } if (this.sourceRoot != null) { aSource = util.relative(this.sourceRoot, aSource); } if (this._sources.has(aSource)) { return this.sourcesContent[this._sources.indexOf(aSource)]; } var url; if (this.sourceRoot != null && (url = util.urlParse(this.sourceRoot))) { // XXX: file:// URIs and absolute paths lead to unexpected behavior for // many users. We can help them out when they expect file:// URIs to // behave like it would if they were running a local HTTP server. See // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. var fileUriAbsPath = aSource.replace(/^file:\/\//, ""); if (url.scheme == "file" && this._sources.has(fileUriAbsPath)) { return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] } if ((!url.path || url.path == "/") && this._sources.has("/" + aSource)) { return this.sourcesContent[this._sources.indexOf("/" + aSource)]; } } // This function is used recursively from // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we // don't want to throw if we can't find the source - we just want to // return null, so we provide a flag to exit gracefully. if (nullOnMissing) { return null; } else { throw new Error('"' + aSource + '" is not in the SourceMap.'); } }; /** * Returns the generated line and column information for the original source, * line, and column positions provided. The only argument is an object with * the following properties: * * - source: The filename of the original source. * - line: The line number in the original source. * - column: The column number in the original source. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the * closest element that is smaller than or greater than the one we are * searching for, respectively, if the exact element cannot be found. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. * * and an object is returned with the following properties: * * - line: The line number in the generated source, or null. * - column: The column number in the generated source, or null. */ BasicSourceMapConsumer.prototype.generatedPositionFor = function SourceMapConsumer_generatedPositionFor(aArgs) { var source = util.getArg(aArgs, 'source'); if (this.sourceRoot != null) { source = util.relative(this.sourceRoot, source); } if (!this._sources.has(source)) { return { line: null, column: null, lastColumn: null }; } source = this._sources.indexOf(source); var needle = { source: source, originalLine: util.getArg(aArgs, 'line'), originalColumn: util.getArg(aArgs, 'column') }; var index = this._findMapping( needle, this._originalMappings, "originalLine", "originalColumn", util.compareByOriginalPositions, util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) ); if (index >= 0) { var mapping = this._originalMappings[index]; if (mapping.source === needle.source) { return { line: util.getArg(mapping, 'generatedLine', null), column: util.getArg(mapping, 'generatedColumn', null), lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) }; } } return { line: null, column: null, lastColumn: null }; }; exports.BasicSourceMapConsumer = BasicSourceMapConsumer; /** * An IndexedSourceMapConsumer instance represents a parsed source map which * we can query for information. It differs from BasicSourceMapConsumer in * that it takes "indexed" source maps (i.e. ones with a "sections" field) as * input. * * The only parameter is a raw source map (either as a JSON string, or already * parsed to an object). According to the spec for indexed source maps, they * have the following attributes: * * - version: Which version of the source map spec this map is following. * - file: Optional. The generated file this source map is associated with. * - sections: A list of section definitions. * * Each value under the "sections" field has two fields: * - offset: The offset into the original specified at which this section * begins to apply, defined as an object with a "line" and "column" * field. * - map: A source map definition. This source map could also be indexed, * but doesn't have to be. * * Instead of the "map" field, it's also possible to have a "url" field * specifying a URL to retrieve a source map from, but that's currently * unsupported. * * Here's an example source map, taken from the source map spec[0], but * modified to omit a section which uses the "url" field. * * { * version : 3, * file: "app.js", * sections: [{ * offset: {line:100, column:10}, * map: { * version : 3, * file: "section.js", * sources: ["foo.js", "bar.js"], * names: ["src", "maps", "are", "fun"], * mappings: "AAAA,E;;ABCDE;" * } * }], * } * * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt */ function IndexedSourceMapConsumer(aSourceMap) { var sourceMap = aSourceMap; if (typeof aSourceMap === 'string') { sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); } var version = util.getArg(sourceMap, 'version'); var sections = util.getArg(sourceMap, 'sections'); if (version != this._version) { throw new Error('Unsupported version: ' + version); } this._sources = new ArraySet(); this._names = new ArraySet(); var lastOffset = { line: -1, column: 0 }; this._sections = sections.map(function (s) { if (s.url) { // The url field will require support for asynchronicity. // See https://github.com/mozilla/source-map/issues/16 throw new Error('Support for url field in sections not implemented.'); } var offset = util.getArg(s, 'offset'); var offsetLine = util.getArg(offset, 'line'); var offsetColumn = util.getArg(offset, 'column'); if (offsetLine < lastOffset.line || (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { throw new Error('Section offsets must be ordered and non-overlapping.'); } lastOffset = offset; return { generatedOffset: { // The offset fields are 0-based, but we use 1-based indices when // encoding/decoding from VLQ. generatedLine: offsetLine + 1, generatedColumn: offsetColumn + 1 }, consumer: new SourceMapConsumer(util.getArg(s, 'map')) } }); } IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; /** * The version of the source mapping spec that we are consuming. */ IndexedSourceMapConsumer.prototype._version = 3; /** * The list of original sources. */ Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { get: function () { var sources = []; for (var i = 0; i < this._sections.length; i++) { for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { sources.push(this._sections[i].consumer.sources[j]); } } return sources; } }); /** * Returns the original source, line, and column information for the generated * source's line and column positions provided. The only argument is an object * with the following properties: * * - line: The line number in the generated source. * - column: The column number in the generated source. * * and an object is returned with the following properties: * * - source: The original source file, or null. * - line: The line number in the original source, or null. * - column: The column number in the original source, or null. * - name: The original identifier, or null. */ IndexedSourceMapConsumer.prototype.originalPositionFor = function IndexedSourceMapConsumer_originalPositionFor(aArgs) { var needle = { generatedLine: util.getArg(aArgs, 'line'), generatedColumn: util.getArg(aArgs, 'column') }; // Find the section containing the generated position we're trying to map // to an original position. var sectionIndex = binarySearch.search(needle, this._sections, function(needle, section) { var cmp = needle.generatedLine - section.generatedOffset.generatedLine; if (cmp) { return cmp; } return (needle.generatedColumn - section.generatedOffset.generatedColumn); }); var section = this._sections[sectionIndex]; if (!section) { return { source: null, line: null, column: null, name: null }; } return section.consumer.originalPositionFor({ line: needle.generatedLine - (section.generatedOffset.generatedLine - 1), column: needle.generatedColumn - (section.generatedOffset.generatedLine === needle.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0), bias: aArgs.bias }); }; /** * Return true if we have the source content for every source in the source * map, false otherwise. */ IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = function IndexedSourceMapConsumer_hasContentsOfAllSources() { return this._sections.every(function (s) { return s.consumer.hasContentsOfAllSources(); }); }; /** * Returns the original source content. The only argument is the url of the * original source file. Returns null if no original source content is * available. */ IndexedSourceMapConsumer.prototype.sourceContentFor = function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { for (var i = 0; i < this._sections.length; i++) { var section = this._sections[i]; var content = section.consumer.sourceContentFor(aSource, true); if (content) { return content; } } if (nullOnMissing) { return null; } else { throw new Error('"' + aSource + '" is not in the SourceMap.'); } }; /** * Returns the generated line and column information for the original source, * line, and column positions provided. The only argument is an object with * the following properties: * * - source: The filename of the original source. * - line: The line number in the original source. * - column: The column number in the original source. * * and an object is returned with the following properties: * * - line: The line number in the generated source, or null. * - column: The column number in the generated source, or null. */ IndexedSourceMapConsumer.prototype.generatedPositionFor = function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { for (var i = 0; i < this._sections.length; i++) { var section = this._sections[i]; // Only consider this section if the requested source is in the list of // sources of the consumer. if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source')) === -1) { continue; } var generatedPosition = section.consumer.generatedPositionFor(aArgs); if (generatedPosition) { var ret = { line: generatedPosition.line + (section.generatedOffset.generatedLine - 1), column: generatedPosition.column + (section.generatedOffset.generatedLine === generatedPosition.line ? section.generatedOffset.generatedColumn - 1 : 0) }; return ret; } } return { line: null, column: null }; }; /** * Parse the mappings in a string in to a data structure which we can easily * query (the ordered arrays in the `this.__generatedMappings` and * `this.__originalMappings` properties). */ IndexedSourceMapConsumer.prototype._parseMappings = function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { this.__generatedMappings = []; this.__originalMappings = []; for (var i = 0; i < this._sections.length; i++) { var section = this._sections[i]; var sectionMappings = section.consumer._generatedMappings; for (var j = 0; j < sectionMappings.length; j++) { var mapping = sectionMappings[j]; var source = section.consumer._sources.at(mapping.source); if (section.consumer.sourceRoot !== null) { source = util.join(section.consumer.sourceRoot, source); } this._sources.add(source); source = this._sources.indexOf(source); var name = section.consumer._names.at(mapping.name); this._names.add(name); name = this._names.indexOf(name); // The mappings coming from the consumer for the section have // generated positions relative to the start of the section, so we // need to offset them to be relative to the start of the concatenated // generated file. var adjustedMapping = { source: source, generatedLine: mapping.generatedLine + (section.generatedOffset.generatedLine - 1), generatedColumn: mapping.generatedColumn + (section.generatedOffset.generatedLine === mapping.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0), originalLine: mapping.originalLine, originalColumn: mapping.originalColumn, name: name }; this.__generatedMappings.push(adjustedMapping); if (typeof adjustedMapping.originalLine === 'number') { this.__originalMappings.push(adjustedMapping); } } } quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); quickSort(this.__originalMappings, util.compareByOriginalPositions); }; exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; } /***/ }, /* 8 */ /***/ function(module, exports) { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ { exports.GREATEST_LOWER_BOUND = 1; exports.LEAST_UPPER_BOUND = 2; /** * Recursive implementation of binary search. * * @param aLow Indices here and lower do not contain the needle. * @param aHigh Indices here and higher do not contain the needle. * @param aNeedle The element being searched for. * @param aHaystack The non-empty array being searched. * @param aCompare Function which takes two elements and returns -1, 0, or 1. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the * closest element that is smaller than or greater than the one we are * searching for, respectively, if the exact element cannot be found. */ function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { // This function terminates when one of the following is true: // // 1. We find the exact element we are looking for. // // 2. We did not find the exact element, but we can return the index of // the next-closest element. // // 3. We did not find the exact element, and there is no next-closest // element than the one we are searching for, so we return -1. var mid = Math.floor((aHigh - aLow) / 2) + aLow; var cmp = aCompare(aNeedle, aHaystack[mid], true); if (cmp === 0) { // Found the element we are looking for. return mid; } else if (cmp > 0) { // Our needle is greater than aHaystack[mid]. if (aHigh - mid > 1) { // The element is in the upper half. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); } // The exact needle element was not found in this haystack. Determine if // we are in termination case (3) or (2) and return the appropriate thing. if (aBias == exports.LEAST_UPPER_BOUND) { return aHigh < aHaystack.length ? aHigh : -1; } else { return mid; } } else { // Our needle is less than aHaystack[mid]. if (mid - aLow > 1) { // The element is in the lower half. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); } // we are in termination case (3) or (2) and return the appropriate thing. if (aBias == exports.LEAST_UPPER_BOUND) { return mid; } else { return aLow < 0 ? -1 : aLow; } } } /** * This is an implementation of binary search which will always try and return * the index of the closest element if there is no exact hit. This is because * mappings between original and generated line/col pairs are single points, * and there is an implicit region between each of them, so a miss just means * that you aren't on the very start of a region. * * @param aNeedle The element you are looking for. * @param aHaystack The array that is being searched. * @param aCompare A function which takes the needle and an element in the * array and returns -1, 0, or 1 depending on whether the needle is less * than, equal to, or greater than the element, respectively. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the * closest element that is smaller than or greater than the one we are * searching for, respectively, if the exact element cannot be found. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. */ exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { if (aHaystack.length === 0) { return -1; } var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare, aBias || exports.GREATEST_LOWER_BOUND); if (index < 0) { return -1; } // We have found either the exact element, or the next-closest element than // the one we are searching for. However, there may be more than one such // element. Make sure we always return the smallest of these. while (index - 1 >= 0) { if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { break; } --index; } return index; }; } /***/ }, /* 9 */ /***/ function(module, exports) { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ { // It turns out that some (most?) JavaScript engines don't self-host // `Array.prototype.sort`. This makes sense because C++ will likely remain // faster than JS when doing raw CPU-intensive sorting. However, when using a // custom comparator function, calling back and forth between the VM's C++ and // JIT'd JS is rather slow *and* loses JIT type information, resulting in // worse generated code for the comparator function than would be optimal. In // fact, when sorting with a comparator, these costs outweigh the benefits of // sorting in C++. By using our own JS-implemented Quick Sort (below), we get // a ~3500ms mean speed-up in `bench/bench.html`. /** * Swap the elements indexed by `x` and `y` in the array `ary`. * * @param {Array} ary * The array. * @param {Number} x * The index of the first item. * @param {Number} y * The index of the second item. */ function swap(ary, x, y) { var temp = ary[x]; ary[x] = ary[y]; ary[y] = temp; } /** * Returns a random integer within the range `low .. high` inclusive. * * @param {Number} low * The lower bound on the range. * @param {Number} high * The upper bound on the range. */ function randomIntInRange(low, high) { return Math.round(low + (Math.random() * (high - low))); } /** * The Quick Sort algorithm. * * @param {Array} ary * An array to sort. * @param {function} comparator * Function to use to compare two items. * @param {Number} p * Start index of the array * @param {Number} r * End index of the array */ function doQuickSort(ary, comparator, p, r) { // If our lower bound is less than our upper bound, we (1) partition the // array into two pieces and (2) recurse on each half. If it is not, this is // the empty array and our base case. if (p < r) { // (1) Partitioning. // // The partitioning chooses a pivot between `p` and `r` and moves all // elements that are less than or equal to the pivot to the before it, and // all the elements that are greater than it after it. The effect is that // once partition is done, the pivot is in the exact place it will be when // the array is put in sorted order, and it will not need to be moved // again. This runs in O(n) time. // Always choose a random pivot so that an input array which is reverse // sorted does not cause O(n^2) running time. var pivotIndex = randomIntInRange(p, r); var i = p - 1; swap(ary, pivotIndex, r); var pivot = ary[r]; // Immediately after `j` is incremented in this loop, the following hold // true: // // * Every element in `ary[p .. i]` is less than or equal to the pivot. // // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. for (var j = p; j < r; j++) { if (comparator(ary[j], pivot) <= 0) { i += 1; swap(ary, i, j); } } swap(ary, i + 1, j); var q = i + 1; // (2) Recurse on each half. doQuickSort(ary, comparator, p, q - 1); doQuickSort(ary, comparator, q + 1, r); } } /** * Sort the given array in-place with the given comparator function. * * @param {Array} ary * An array to sort. * @param {function} comparator * Function to use to compare two items. */ exports.quickSort = function (ary, comparator) { doQuickSort(ary, comparator, 0, ary.length - 1); }; } /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ { var SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; var util = __webpack_require__(4); // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other // operating systems these days (capturing the result). var REGEX_NEWLINE = /(\r?\n)/; // Newline character code for charCodeAt() comparisons var NEWLINE_CODE = 10; // Private symbol for identifying `SourceNode`s when multiple versions of // the source-map library are loaded. This MUST NOT CHANGE across // versions! var isSourceNode = "$$$isSourceNode$$$"; /** * SourceNodes provide a way to abstract over interpolating/concatenating * snippets of generated JavaScript source code while maintaining the line and * column information associated with the original source code. * * @param aLine The original line number. * @param aColumn The original column number. * @param aSource The original source's filename. * @param aChunks Optional. An array of strings which are snippets of * generated JS, or other SourceNodes. * @param aName The original identifier. */ function SourceNode(aLine, aColumn, aSource, aChunks, aName) { this.children = []; this.sourceContents = {}; this.line = aLine == null ? null : aLine; this.column = aColumn == null ? null : aColumn; this.source = aSource == null ? null : aSource; this.name = aName == null ? null : aName; this[isSourceNode] = true; if (aChunks != null) this.add(aChunks); } /** * Creates a SourceNode from generated code and a SourceMapConsumer. * * @param aGeneratedCode The generated code * @param aSourceMapConsumer The SourceMap for the generated code * @param aRelativePath Optional. The path that relative sources in the * SourceMapConsumer should be relative to. */ SourceNode.fromStringWithSourceMap = function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { // The SourceNode we want to fill with the generated code // and the SourceMap var node = new SourceNode(); // All even indices of this array are one line of the generated code, // while all odd indices are the newlines between two adjacent lines // (since `REGEX_NEWLINE` captures its match). // Processed fragments are removed from this array, by calling `shiftNextLine`. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); var shiftNextLine = function() { var lineContents = remainingLines.shift(); // The last line of a file might not have a newline. var newLine = remainingLines.shift() || ""; return lineContents + newLine; }; // We need to remember the position of "remainingLines" var lastGeneratedLine = 1, lastGeneratedColumn = 0; // The generate SourceNodes we need a code range. // To extract it current and last mapping is used. // Here we store the last mapping. var lastMapping = null; aSourceMapConsumer.eachMapping(function (mapping) { if (lastMapping !== null) { // We add the code from "lastMapping" to "mapping": // First check if there is a new line in between. if (lastGeneratedLine < mapping.generatedLine) { // Associate first line with "lastMapping" addMappingWithCode(lastMapping, shiftNextLine()); lastGeneratedLine++; lastGeneratedColumn = 0; // The remaining code is added without mapping } else { // There is no new line in between. // Associate the code between "lastGeneratedColumn" and // "mapping.generatedColumn" with "lastMapping" var nextLine = remainingLines[0]; var code = nextLine.substr(0, mapping.generatedColumn - lastGeneratedColumn); remainingLines[0] = nextLine.substr(mapping.generatedColumn - lastGeneratedColumn); lastGeneratedColumn = mapping.generatedColumn; addMappingWithCode(lastMapping, code); // No more remaining code, continue lastMapping = mapping; return; } } // We add the generated code until the first mapping // to the SourceNode without any mapping. // Each line is added as separate string. while (lastGeneratedLine < mapping.generatedLine) { node.add(shiftNextLine()); lastGeneratedLine++; } if (lastGeneratedColumn < mapping.generatedColumn) { var nextLine = remainingLines[0]; node.add(nextLine.substr(0, mapping.generatedColumn)); remainingLines[0] = nextLine.substr(mapping.generatedColumn); lastGeneratedColumn = mapping.generatedColumn; } lastMapping = mapping; }, this); // We have processed all mappings. if (remainingLines.length > 0) { if (lastMapping) { // Associate the remaining code in the current line with "lastMapping" addMappingWithCode(lastMapping, shiftNextLine()); } // and add the remaining lines without any mapping node.add(remainingLines.join("")); } // Copy sourcesContent into SourceNode aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content != null) { if (aRelativePath != null) { sourceFile = util.join(aRelativePath, sourceFile); } node.setSourceContent(sourceFile, content); } }); return node; function addMappingWithCode(mapping, code) { if (mapping === null || mapping.source === undefined) { node.add(code); } else { var source = aRelativePath ? util.join(aRelativePath, mapping.source) : mapping.source; node.add(new SourceNode(mapping.originalLine, mapping.originalColumn, source, code, mapping.name)); } } }; /** * Add a chunk of generated JS to this source node. * * @param aChunk A string snippet of generated JS code, another instance of * SourceNode, or an array where each member is one of those things. */ SourceNode.prototype.add = function SourceNode_add(aChunk) { if (Array.isArray(aChunk)) { aChunk.forEach(function (chunk) { this.add(chunk); }, this); } else if (aChunk[isSourceNode] || typeof aChunk === "string") { if (aChunk) { this.children.push(aChunk); } } else { throw new TypeError( "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk ); } return this; }; /** * Add a chunk of generated JS to the beginning of this source node. * * @param aChunk A string snippet of generated JS code, another instance of * SourceNode, or an array where each member is one of those things. */ SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { if (Array.isArray(aChunk)) { for (var i = aChunk.length-1; i >= 0; i--) { this.prepend(aChunk[i]); } } else if (aChunk[isSourceNode] || typeof aChunk === "string") { this.children.unshift(aChunk); } else { throw new TypeError( "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk ); } return this; }; /** * Walk over the tree of JS snippets in this node and its children. The * walking function is called once for each snippet of JS and is passed that * snippet and the its original associated source's line/column location. * * @param aFn The traversal function. */ SourceNode.prototype.walk = function SourceNode_walk(aFn) { var chunk; for (var i = 0, len = this.children.length; i < len; i++) { chunk = this.children[i]; if (chunk[isSourceNode]) { chunk.walk(aFn); } else { if (chunk !== '') { aFn(chunk, { source: this.source, line: this.line, column: this.column, name: this.name }); } } } }; /** * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between * each of `this.children`. * * @param aSep The separator. */ SourceNode.prototype.join = function SourceNode_join(aSep) { var newChildren; var i; var len = this.children.length; if (len > 0) { newChildren = []; for (i = 0; i < len-1; i++) { newChildren.push(this.children[i]); newChildren.push(aSep); } newChildren.push(this.children[i]); this.children = newChildren; } return this; }; /** * Call String.prototype.replace on the very right-most source snippet. Useful * for trimming whitespace from the end of a source node, etc. * * @param aPattern The pattern to replace. * @param aReplacement The thing to replace the pattern with. */ SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { var lastChild = this.children[this.children.length - 1]; if (lastChild[isSourceNode]) { lastChild.replaceRight(aPattern, aReplacement); } else if (typeof lastChild === 'string') { this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); } else { this.children.push(''.replace(aPattern, aReplacement)); } return this; }; /** * Set the source content for a source file. This will be added to the SourceMapGenerator * in the sourcesContent field. * * @param aSourceFile The filename of the source file * @param aSourceContent The content of the source file */ SourceNode.prototype.setSourceContent = function SourceNode_setSourceContent(aSourceFile, aSourceContent) { this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; }; /** * Walk over the tree of SourceNodes. The walking function is called for each * source file content and is passed the filename and source content. * * @param aFn The traversal function. */ SourceNode.prototype.walkSourceContents = function SourceNode_walkSourceContents(aFn) { for (var i = 0, len = this.children.length; i < len; i++) { if (this.children[i][isSourceNode]) { this.children[i].walkSourceContents(aFn); } } var sources = Object.keys(this.sourceContents); for (var i = 0, len = sources.length; i < len; i++) { aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); } }; /** * Return the string representation of this source node. Walks over the tree * and concatenates all the various snippets together to one string. */ SourceNode.prototype.toString = function SourceNode_toString() { var str = ""; this.walk(function (chunk) { str += chunk; }); return str; }; /** * Returns the string representation of this source node along with a source * map. */ SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { var generated = { code: "", line: 1, column: 0 }; var map = new SourceMapGenerator(aArgs); var sourceMappingActive = false; var lastOriginalSource = null; var lastOriginalLine = null; var lastOriginalColumn = null; var lastOriginalName = null; this.walk(function (chunk, original) { generated.code += chunk; if (original.source !== null && original.line !== null && original.column !== null) { if(lastOriginalSource !== original.source || lastOriginalLine !== original.line || lastOriginalColumn !== original.column || lastOriginalName !== original.name) { map.addMapping({ source: original.source, original: { line: original.line, column: original.column }, generated: { line: generated.line, column: generated.column }, name: original.name }); } lastOriginalSource = original.source; lastOriginalLine = original.line; lastOriginalColumn = original.column; lastOriginalName = original.name; sourceMappingActive = true; } else if (sourceMappingActive) { map.addMapping({ generated: { line: generated.line, column: generated.column } }); lastOriginalSource = null; sourceMappingActive = false; } for (var idx = 0, length = chunk.length; idx < length; idx++) { if (chunk.charCodeAt(idx) === NEWLINE_CODE) { generated.line++; generated.column = 0; // Mappings end at eol if (idx + 1 === length) { lastOriginalSource = null; sourceMappingActive = false; } else if (sourceMappingActive) { map.addMapping({ source: original.source, original: { line: original.line, column: original.column }, generated: { line: generated.line, column: generated.column }, name: original.name }); } } else { generated.column++; } } }); this.walkSourceContents(function (sourceFile, sourceContent) { map.setSourceContent(sourceFile, sourceContent); }); return { code: generated.code, map: map }; }; exports.SourceNode = SourceNode; } /***/ } /******/ ]) }); ;//Distributed under the BSD license: //Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com> define('uglifyjs', ['exports', 'source-map', 'logger', 'env!env/file'], function (exports, MOZ_SourceMap, logger, rjsFile) { /*********************************************************************** A JavaScript tokenizer / parser / beautifier / compressor. https://github.com/mishoo/UglifyJS2 -------------------------------- (C) --------------------------------- Author: Mihai Bazon <mihai.bazon@gmail.com> http://mihai.bazon.net/blog Distributed under the BSD license: Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************/ "use strict"; function array_to_hash(a) { var ret = Object.create(null); for (var i = 0; i < a.length; ++i) ret[a[i]] = true; return ret; }; function slice(a, start) { return Array.prototype.slice.call(a, start || 0); }; function characters(str) { return str.split(""); }; function member(name, array) { for (var i = array.length; --i >= 0;) if (array[i] == name) return true; return false; }; function find_if(func, array) { for (var i = 0, n = array.length; i < n; ++i) { if (func(array[i])) return array[i]; } }; function repeat_string(str, i) { if (i <= 0) return ""; if (i == 1) return str; var d = repeat_string(str, i >> 1); d += d; if (i & 1) d += str; return d; }; function DefaultsError(msg, defs) { Error.call(this, msg); this.msg = msg; this.defs = defs; }; DefaultsError.prototype = Object.create(Error.prototype); DefaultsError.prototype.constructor = DefaultsError; DefaultsError.croak = function(msg, defs) { throw new DefaultsError(msg, defs); }; function defaults(args, defs, croak) { if (args === true) args = {}; var ret = args || {}; if (croak) for (var i in ret) if (ret.hasOwnProperty(i) && !defs.hasOwnProperty(i)) DefaultsError.croak("`" + i + "` is not a supported option", defs); for (var i in defs) if (defs.hasOwnProperty(i)) { ret[i] = (args && args.hasOwnProperty(i)) ? args[i] : defs[i]; } return ret; }; function merge(obj, ext) { var count = 0; for (var i in ext) if (ext.hasOwnProperty(i)) { obj[i] = ext[i]; count++; } return count; }; function noop() {}; var MAP = (function(){ function MAP(a, f, backwards) { var ret = [], top = [], i; function doit() { var val = f(a[i], i); var is_last = val instanceof Last; if (is_last) val = val.v; if (val instanceof AtTop) { val = val.v; if (val instanceof Splice) { top.push.apply(top, backwards ? val.v.slice().reverse() : val.v); } else { top.push(val); } } else if (val !== skip) { if (val instanceof Splice) { ret.push.apply(ret, backwards ? val.v.slice().reverse() : val.v); } else { ret.push(val); } } return is_last; }; if (a instanceof Array) { if (backwards) { for (i = a.length; --i >= 0;) if (doit()) break; ret.reverse(); top.reverse(); } else { for (i = 0; i < a.length; ++i) if (doit()) break; } } else { for (i in a) if (a.hasOwnProperty(i)) if (doit()) break; } return top.concat(ret); }; MAP.at_top = function(val) { return new AtTop(val) }; MAP.splice = function(val) { return new Splice(val) }; MAP.last = function(val) { return new Last(val) }; var skip = MAP.skip = {}; function AtTop(val) { this.v = val }; function Splice(val) { this.v = val }; function Last(val) { this.v = val }; return MAP; })(); function push_uniq(array, el) { if (array.indexOf(el) < 0) array.push(el); }; function string_template(text, props) { return text.replace(/\{(.+?)\}/g, function(str, p){ return props[p]; }); }; function remove(array, el) { for (var i = array.length; --i >= 0;) { if (array[i] === el) array.splice(i, 1); } }; function mergeSort(array, cmp) { if (array.length < 2) return array.slice(); function merge(a, b) { var r = [], ai = 0, bi = 0, i = 0; while (ai < a.length && bi < b.length) { cmp(a[ai], b[bi]) <= 0 ? r[i++] = a[ai++] : r[i++] = b[bi++]; } if (ai < a.length) r.push.apply(r, a.slice(ai)); if (bi < b.length) r.push.apply(r, b.slice(bi)); return r; }; function _ms(a) { if (a.length <= 1) return a; var m = Math.floor(a.length / 2), left = a.slice(0, m), right = a.slice(m); left = _ms(left); right = _ms(right); return merge(left, right); }; return _ms(array); }; function set_difference(a, b) { return a.filter(function(el){ return b.indexOf(el) < 0; }); }; function set_intersection(a, b) { return a.filter(function(el){ return b.indexOf(el) >= 0; }); }; // this function is taken from Acorn [1], written by Marijn Haverbeke // [1] https://github.com/marijnh/acorn function makePredicate(words) { if (!(words instanceof Array)) words = words.split(" "); var f = "", cats = []; out: for (var i = 0; i < words.length; ++i) { for (var j = 0; j < cats.length; ++j) if (cats[j][0].length == words[i].length) { cats[j].push(words[i]); continue out; } cats.push([words[i]]); } function compareTo(arr) { if (arr.length == 1) return f += "return str === " + JSON.stringify(arr[0]) + ";"; f += "switch(str){"; for (var i = 0; i < arr.length; ++i) f += "case " + JSON.stringify(arr[i]) + ":"; f += "return true}return false;"; } // When there are more than three length categories, an outer // switch first dispatches on the lengths, to save on comparisons. if (cats.length > 3) { cats.sort(function(a, b) {return b.length - a.length;}); f += "switch(str.length){"; for (var i = 0; i < cats.length; ++i) { var cat = cats[i]; f += "case " + cat[0].length + ":"; compareTo(cat); } f += "}"; // Otherwise, simply generate a flat `switch` statement. } else { compareTo(words); } return new Function("str", f); }; function all(array, predicate) { for (var i = array.length; --i >= 0;) if (!predicate(array[i])) return false; return true; }; function Dictionary() { this._values = Object.create(null); this._size = 0; }; Dictionary.prototype = { set: function(key, val) { if (!this.has(key)) ++this._size; this._values["$" + key] = val; return this; }, add: function(key, val) { if (this.has(key)) { this.get(key).push(val); } else { this.set(key, [ val ]); } return this; }, get: function(key) { return this._values["$" + key] }, del: function(key) { if (this.has(key)) { --this._size; delete this._values["$" + key]; } return this; }, has: function(key) { return ("$" + key) in this._values }, each: function(f) { for (var i in this._values) f(this._values[i], i.substr(1)); }, size: function() { return this._size; }, map: function(f) { var ret = []; for (var i in this._values) ret.push(f(this._values[i], i.substr(1))); return ret; }, toObject: function() { return this._values } }; Dictionary.fromObject = function(obj) { var dict = new Dictionary(); dict._size = merge(dict._values, obj); return dict; }; /*********************************************************************** A JavaScript tokenizer / parser / beautifier / compressor. https://github.com/mishoo/UglifyJS2 -------------------------------- (C) --------------------------------- Author: Mihai Bazon <mihai.bazon@gmail.com> http://mihai.bazon.net/blog Distributed under the BSD license: Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************/ "use strict"; function DEFNODE(type, props, methods, base) { if (arguments.length < 4) base = AST_Node; if (!props) props = []; else props = props.split(/\s+/); var self_props = props; if (base && base.PROPS) props = props.concat(base.PROPS); var code = "return function AST_" + type + "(props){ if (props) { "; for (var i = props.length; --i >= 0;) { code += "this." + props[i] + " = props." + props[i] + ";"; } var proto = base && new base; if (proto && proto.initialize || (methods && methods.initialize)) code += "this.initialize();"; code += "}}"; var ctor = new Function(code)(); if (proto) { ctor.prototype = proto; ctor.BASE = base; } if (base) base.SUBCLASSES.push(ctor); ctor.prototype.CTOR = ctor; ctor.PROPS = props || null; ctor.SELF_PROPS = self_props; ctor.SUBCLASSES = []; if (type) { ctor.prototype.TYPE = ctor.TYPE = type; } if (methods) for (i in methods) if (methods.hasOwnProperty(i)) { if (/^\$/.test(i)) { ctor[i.substr(1)] = methods[i]; } else { ctor.prototype[i] = methods[i]; } } ctor.DEFMETHOD = function(name, method) { this.prototype[name] = method; }; exports["AST_" + type] = ctor; return ctor; }; var AST_Token = DEFNODE("Token", "type value line col pos endline endcol endpos nlb comments_before file raw", { }, null); var AST_Node = DEFNODE("Node", "start end", { clone: function() { return new this.CTOR(this); }, $documentation: "Base class of all AST nodes", $propdoc: { start: "[AST_Token] The first token of this node", end: "[AST_Token] The last token of this node" }, _walk: function(visitor) { return visitor._visit(this); }, walk: function(visitor) { return this._walk(visitor); // not sure the indirection will be any help } }, null); AST_Node.warn_function = null; AST_Node.warn = function(txt, props) { if (AST_Node.warn_function) AST_Node.warn_function(string_template(txt, props)); }; /* -----[ statements ]----- */ var AST_Statement = DEFNODE("Statement", null, { $documentation: "Base class of all statements", }); var AST_Debugger = DEFNODE("Debugger", null, { $documentation: "Represents a debugger statement", }, AST_Statement); var AST_Directive = DEFNODE("Directive", "value scope quote", { $documentation: "Represents a directive, like \"use strict\";", $propdoc: { value: "[string] The value of this directive as a plain string (it's not an AST_String!)", scope: "[AST_Scope/S] The scope that this directive affects", quote: "[string] the original quote character" }, }, AST_Statement); var AST_SimpleStatement = DEFNODE("SimpleStatement", "body", { $documentation: "A statement consisting of an expression, i.e. a = 1 + 2", $propdoc: { body: "[AST_Node] an expression node (should not be instanceof AST_Statement)" }, _walk: function(visitor) { return visitor._visit(this, function(){ this.body._walk(visitor); }); } }, AST_Statement); function walk_body(node, visitor) { if (node.body instanceof AST_Statement) { node.body._walk(visitor); } else node.body.forEach(function(stat){ stat._walk(visitor); }); }; var AST_Block = DEFNODE("Block", "body", { $documentation: "A body of statements (usually bracketed)", $propdoc: { body: "[AST_Statement*] an array of statements" }, _walk: function(visitor) { return visitor._visit(this, function(){ walk_body(this, visitor); }); } }, AST_Statement); var AST_BlockStatement = DEFNODE("BlockStatement", null, { $documentation: "A block statement", }, AST_Block); var AST_EmptyStatement = DEFNODE("EmptyStatement", null, { $documentation: "The empty statement (empty block or simply a semicolon)", _walk: function(visitor) { return visitor._visit(this); } }, AST_Statement); var AST_StatementWithBody = DEFNODE("StatementWithBody", "body", { $documentation: "Base class for all statements that contain one nested body: `For`, `ForIn`, `Do`, `While`, `With`", $propdoc: { body: "[AST_Statement] the body; this should always be present, even if it's an AST_EmptyStatement" }, _walk: function(visitor) { return visitor._visit(this, function(){ this.body._walk(visitor); }); } }, AST_Statement); var AST_LabeledStatement = DEFNODE("LabeledStatement", "label", { $documentation: "Statement with a label", $propdoc: { label: "[AST_Label] a label definition" }, _walk: function(visitor) { return visitor._visit(this, function(){ this.label._walk(visitor); this.body._walk(visitor); }); } }, AST_StatementWithBody); var AST_IterationStatement = DEFNODE("IterationStatement", null, { $documentation: "Internal class. All loops inherit from it." }, AST_StatementWithBody); var AST_DWLoop = DEFNODE("DWLoop", "condition", { $documentation: "Base class for do/while statements", $propdoc: { condition: "[AST_Node] the loop condition. Should not be instanceof AST_Statement" } }, AST_IterationStatement); var AST_Do = DEFNODE("Do", null, { $documentation: "A `do` statement", _walk: function(visitor) { return visitor._visit(this, function(){ this.body._walk(visitor); this.condition._walk(visitor); }); } }, AST_DWLoop); var AST_While = DEFNODE("While", null, { $documentation: "A `while` statement", _walk: function(visitor) { return visitor._visit(this, function(){ this.condition._walk(visitor); this.body._walk(visitor); }); } }, AST_DWLoop); var AST_For = DEFNODE("For", "init condition step", { $documentation: "A `for` statement", $propdoc: { init: "[AST_Node?] the `for` initialization code, or null if empty", condition: "[AST_Node?] the `for` termination clause, or null if empty", step: "[AST_Node?] the `for` update clause, or null if empty" }, _walk: function(visitor) { return visitor._visit(this, function(){ if (this.init) this.init._walk(visitor); if (this.condition) this.condition._walk(visitor); if (this.step) this.step._walk(visitor); this.body._walk(visitor); }); } }, AST_IterationStatement); var AST_ForIn = DEFNODE("ForIn", "init name object", { $documentation: "A `for ... in` statement", $propdoc: { init: "[AST_Node] the `for/in` initialization code", name: "[AST_SymbolRef?] the loop variable, only if `init` is AST_Var", object: "[AST_Node] the object that we're looping through" }, _walk: function(visitor) { return visitor._visit(this, function(){ this.init._walk(visitor); this.object._walk(visitor); this.body._walk(visitor); }); } }, AST_IterationStatement); var AST_With = DEFNODE("With", "expression", { $documentation: "A `with` statement", $propdoc: { expression: "[AST_Node] the `with` expression" }, _walk: function(visitor) { return visitor._visit(this, function(){ this.expression._walk(visitor); this.body._walk(visitor); }); } }, AST_StatementWithBody); /* -----[ scope and functions ]----- */ var AST_Scope = DEFNODE("Scope", "directives variables functions uses_with uses_eval parent_scope enclosed cname", { $documentation: "Base class for all statements introducing a lexical scope", $propdoc: { directives: "[string*/S] an array of directives declared in this scope", variables: "[Object/S] a map of name -> SymbolDef for all variables/functions defined in this scope", functions: "[Object/S] like `variables`, but only lists function declarations", uses_with: "[boolean/S] tells whether this scope uses the `with` statement", uses_eval: "[boolean/S] tells whether this scope contains a direct call to the global `eval`", parent_scope: "[AST_Scope?/S] link to the parent scope", enclosed: "[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes", cname: "[integer/S] current index for mangling variables (used internally by the mangler)", }, }, AST_Block); var AST_Toplevel = DEFNODE("Toplevel", "globals", { $documentation: "The toplevel scope", $propdoc: { globals: "[Object/S] a map of name -> SymbolDef for all undeclared names", }, wrap_enclose: function(arg_parameter_pairs) { var self = this; var args = []; var parameters = []; arg_parameter_pairs.forEach(function(pair) { var splitAt = pair.lastIndexOf(":"); args.push(pair.substr(0, splitAt)); parameters.push(pair.substr(splitAt + 1)); }); var wrapped_tl = "(function(" + parameters.join(",") + "){ '$ORIG'; })(" + args.join(",") + ")"; wrapped_tl = parse(wrapped_tl); wrapped_tl = wrapped_tl.transform(new TreeTransformer(function before(node){ if (node instanceof AST_Directive && node.value == "$ORIG") { return MAP.splice(self.body); } })); return wrapped_tl; }, wrap_commonjs: function(name, export_all) { var self = this; var to_export = []; if (export_all) { self.figure_out_scope(); self.walk(new TreeWalker(function(node){ if (node instanceof AST_SymbolDeclaration && node.definition().global) { if (!find_if(function(n){ return n.name == node.name }, to_export)) to_export.push(node); } })); } var wrapped_tl = "(function(exports, global){ '$ORIG'; '$EXPORTS'; global['" + name + "'] = exports; }({}, (function(){return this}())))"; wrapped_tl = parse(wrapped_tl); wrapped_tl = wrapped_tl.transform(new TreeTransformer(function before(node){ if (node instanceof AST_Directive) { switch (node.value) { case "$ORIG": return MAP.splice(self.body); case "$EXPORTS": var body = []; to_export.forEach(function(sym){ body.push(new AST_SimpleStatement({ body: new AST_Assign({ left: new AST_Sub({ expression: new AST_SymbolRef({ name: "exports" }), property: new AST_String({ value: sym.name }), }), operator: "=", right: new AST_SymbolRef(sym), }), })); }); return MAP.splice(body); } } })); return wrapped_tl; } }, AST_Scope); var AST_Lambda = DEFNODE("Lambda", "name argnames uses_arguments", { $documentation: "Base class for functions", $propdoc: { name: "[AST_SymbolDeclaration?] the name of this function", argnames: "[AST_SymbolFunarg*] array of function arguments", uses_arguments: "[boolean/S] tells whether this function accesses the arguments array" }, _walk: function(visitor) { return visitor._visit(this, function(){ if (this.name) this.name._walk(visitor); this.argnames.forEach(function(arg){ arg._walk(visitor); }); walk_body(this, visitor); }); } }, AST_Scope); var AST_Accessor = DEFNODE("Accessor", null, { $documentation: "A setter/getter function. The `name` property is always null." }, AST_Lambda); var AST_Function = DEFNODE("Function", null, { $documentation: "A function expression" }, AST_Lambda); var AST_Defun = DEFNODE("Defun", null, { $documentation: "A function definition" }, AST_Lambda); /* -----[ JUMPS ]----- */ var AST_Jump = DEFNODE("Jump", null, { $documentation: "Base class for “jumps” (for now that's `return`, `throw`, `break` and `continue`)" }, AST_Statement); var AST_Exit = DEFNODE("Exit", "value", { $documentation: "Base class for “exits” (`return` and `throw`)", $propdoc: { value: "[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return" }, _walk: function(visitor) { return visitor._visit(this, this.value && function(){ this.value._walk(visitor); }); } }, AST_Jump); var AST_Return = DEFNODE("Return", null, { $documentation: "A `return` statement" }, AST_Exit); var AST_Throw = DEFNODE("Throw", null, { $documentation: "A `throw` statement" }, AST_Exit); var AST_LoopControl = DEFNODE("LoopControl", "label", { $documentation: "Base class for loop control statements (`break` and `continue`)", $propdoc: { label: "[AST_LabelRef?] the label, or null if none", }, _walk: function(visitor) { return visitor._visit(this, this.label && function(){ this.label._walk(visitor); }); } }, AST_Jump); var AST_Break = DEFNODE("Break", null, { $documentation: "A `break` statement" }, AST_LoopControl); var AST_Continue = DEFNODE("Continue", null, { $documentation: "A `continue` statement" }, AST_LoopControl); /* -----[ IF ]----- */ var AST_If = DEFNODE("If", "condition alternative", { $documentation: "A `if` statement", $propdoc: { condition: "[AST_Node] the `if` condition", alternative: "[AST_Statement?] the `else` part, or null if not present" }, _walk: function(visitor) { return visitor._visit(this, function(){ this.condition._walk(visitor); this.body._walk(visitor); if (this.alternative) this.alternative._walk(visitor); }); } }, AST_StatementWithBody); /* -----[ SWITCH ]----- */ var AST_Switch = DEFNODE("Switch", "expression", { $documentation: "A `switch` statement", $propdoc: { expression: "[AST_Node] the `switch` “discriminant”" }, _walk: function(visitor) { return visitor._visit(this, function(){ this.expression._walk(visitor); walk_body(this, visitor); }); } }, AST_Block); var AST_SwitchBranch = DEFNODE("SwitchBranch", null, { $documentation: "Base class for `switch` branches", }, AST_Block); var AST_Default = DEFNODE("Default", null, { $documentation: "A `default` switch branch", }, AST_SwitchBranch); var AST_Case = DEFNODE("Case", "expression", { $documentation: "A `case` switch branch", $propdoc: { expression: "[AST_Node] the `case` expression" }, _walk: function(visitor) { return visitor._visit(this, function(){ this.expression._walk(visitor); walk_body(this, visitor); }); } }, AST_SwitchBranch); /* -----[ EXCEPTIONS ]----- */ var AST_Try = DEFNODE("Try", "bcatch bfinally", { $documentation: "A `try` statement", $propdoc: { bcatch: "[AST_Catch?] the catch block, or null if not present", bfinally: "[AST_Finally?] the finally block, or null if not present" }, _walk: function(visitor) { return visitor._visit(this, function(){ walk_body(this, visitor); if (this.bcatch) this.bcatch._walk(visitor); if (this.bfinally) this.bfinally._walk(visitor); }); } }, AST_Block); var AST_Catch = DEFNODE("Catch", "argname", { $documentation: "A `catch` node; only makes sense as part of a `try` statement", $propdoc: { argname: "[AST_SymbolCatch] symbol for the exception" }, _walk: function(visitor) { return visitor._visit(this, function(){ this.argname._walk(visitor); walk_body(this, visitor); }); } }, AST_Block); var AST_Finally = DEFNODE("Finally", null, { $documentation: "A `finally` node; only makes sense as part of a `try` statement" }, AST_Block); /* -----[ VAR/CONST ]----- */ var AST_Definitions = DEFNODE("Definitions", "definitions", { $documentation: "Base class for `var` or `const` nodes (variable declarations/initializations)", $propdoc: { definitions: "[AST_VarDef*] array of variable definitions" }, _walk: function(visitor) { return visitor._visit(this, function(){ this.definitions.forEach(function(def){ def._walk(visitor); }); }); } }, AST_Statement); var AST_Var = DEFNODE("Var", null, { $documentation: "A `var` statement" }, AST_Definitions); var AST_Const = DEFNODE("Const", null, { $documentation: "A `const` statement" }, AST_Definitions); var AST_VarDef = DEFNODE("VarDef", "name value", { $documentation: "A variable declaration; only appears in a AST_Definitions node", $propdoc: { name: "[AST_SymbolVar|AST_SymbolConst] name of the variable", value: "[AST_Node?] initializer, or null of there's no initializer" }, _walk: function(visitor) { return visitor._visit(this, function(){ this.name._walk(visitor); if (this.value) this.value._walk(visitor); }); } }); /* -----[ OTHER ]----- */ var AST_Call = DEFNODE("Call", "expression args", { $documentation: "A function call expression", $propdoc: { expression: "[AST_Node] expression to invoke as function", args: "[AST_Node*] array of arguments" }, _walk: function(visitor) { return visitor._visit(this, function(){ this.expression._walk(visitor); this.args.forEach(function(arg){ arg._walk(visitor); }); }); } }); var AST_New = DEFNODE("New", null, { $documentation: "An object instantiation. Derives from a function call since it has exactly the same properties" }, AST_Call); var AST_Seq = DEFNODE("Seq", "car cdr", { $documentation: "A sequence expression (two comma-separated expressions)", $propdoc: { car: "[AST_Node] first element in sequence", cdr: "[AST_Node] second element in sequence" }, $cons: function(x, y) { var seq = new AST_Seq(x); seq.car = x; seq.cdr = y; return seq; }, $from_array: function(array) { if (array.length == 0) return null; if (array.length == 1) return array[0].clone(); var list = null; for (var i = array.length; --i >= 0;) { list = AST_Seq.cons(array[i], list); } var p = list; while (p) { if (p.cdr && !p.cdr.cdr) { p.cdr = p.cdr.car; break; } p = p.cdr; } return list; }, to_array: function() { var p = this, a = []; while (p) { a.push(p.car); if (p.cdr && !(p.cdr instanceof AST_Seq)) { a.push(p.cdr); break; } p = p.cdr; } return a; }, add: function(node) { var p = this; while (p) { if (!(p.cdr instanceof AST_Seq)) { var cell = AST_Seq.cons(p.cdr, node); return p.cdr = cell; } p = p.cdr; } }, _walk: function(visitor) { return visitor._visit(this, function(){ this.car._walk(visitor); if (this.cdr) this.cdr._walk(visitor); }); } }); var AST_PropAccess = DEFNODE("PropAccess", "expression property", { $documentation: "Base class for property access expressions, i.e. `a.foo` or `a[\"foo\"]`", $propdoc: { expression: "[AST_Node] the “container” expression", property: "[AST_Node|string] the property to access. For AST_Dot this is always a plain string, while for AST_Sub it's an arbitrary AST_Node" } }); var AST_Dot = DEFNODE("Dot", null, { $documentation: "A dotted property access expression", _walk: function(visitor) { return visitor._visit(this, function(){ this.expression._walk(visitor); }); } }, AST_PropAccess); var AST_Sub = DEFNODE("Sub", null, { $documentation: "Index-style property access, i.e. `a[\"foo\"]`", _walk: function(visitor) { return visitor._visit(this, function(){ this.expression._walk(visitor); this.property._walk(visitor); }); } }, AST_PropAccess); var AST_Unary = DEFNODE("Unary", "operator expression", { $documentation: "Base class for unary expressions", $propdoc: { operator: "[string] the operator", expression: "[AST_Node] expression that this unary operator applies to" }, _walk: function(visitor) { return visitor._visit(this, function(){ this.expression._walk(visitor); }); } }); var AST_UnaryPrefix = DEFNODE("UnaryPrefix", null, { $documentation: "Unary prefix expression, i.e. `typeof i` or `++i`" }, AST_Unary); var AST_UnaryPostfix = DEFNODE("UnaryPostfix", null, { $documentation: "Unary postfix expression, i.e. `i++`" }, AST_Unary); var AST_Binary = DEFNODE("Binary", "left operator right", { $documentation: "Binary expression, i.e. `a + b`", $propdoc: { left: "[AST_Node] left-hand side expression", operator: "[string] the operator", right: "[AST_Node] right-hand side expression" }, _walk: function(visitor) { return visitor._visit(this, function(){ this.left._walk(visitor); this.right._walk(visitor); }); } }); var AST_Conditional = DEFNODE("Conditional", "condition consequent alternative", { $documentation: "Conditional expression using the ternary operator, i.e. `a ? b : c`", $propdoc: { condition: "[AST_Node]", consequent: "[AST_Node]", alternative: "[AST_Node]" }, _walk: function(visitor) { return visitor._visit(this, function(){ this.condition._walk(visitor); this.consequent._walk(visitor); this.alternative._walk(visitor); }); } }); var AST_Assign = DEFNODE("Assign", null, { $documentation: "An assignment expression — `a = b + 5`", }, AST_Binary); /* -----[ LITERALS ]----- */ var AST_Array = DEFNODE("Array", "elements", { $documentation: "An array literal", $propdoc: { elements: "[AST_Node*] array of elements" }, _walk: function(visitor) { return visitor._visit(this, function(){ this.elements.forEach(function(el){ el._walk(visitor); }); }); } }); var AST_Object = DEFNODE("Object", "properties", { $documentation: "An object literal", $propdoc: { properties: "[AST_ObjectProperty*] array of properties" }, _walk: function(visitor) { return visitor._visit(this, function(){ this.properties.forEach(function(prop){ prop._walk(visitor); }); }); } }); var AST_ObjectProperty = DEFNODE("ObjectProperty", "key value", { $documentation: "Base class for literal object properties", $propdoc: { key: "[string] the property name converted to a string for ObjectKeyVal. For setters and getters this is an arbitrary AST_Node.", value: "[AST_Node] property value. For setters and getters this is an AST_Function." }, _walk: function(visitor) { return visitor._visit(this, function(){ this.value._walk(visitor); }); } }); var AST_ObjectKeyVal = DEFNODE("ObjectKeyVal", "quote", { $documentation: "A key: value object property", $propdoc: { quote: "[string] the original quote character" } }, AST_ObjectProperty); var AST_ObjectSetter = DEFNODE("ObjectSetter", null, { $documentation: "An object setter property", }, AST_ObjectProperty); var AST_ObjectGetter = DEFNODE("ObjectGetter", null, { $documentation: "An object getter property", }, AST_ObjectProperty); var AST_Symbol = DEFNODE("Symbol", "scope name thedef", { $propdoc: { name: "[string] name of this symbol", scope: "[AST_Scope/S] the current scope (not necessarily the definition scope)", thedef: "[SymbolDef/S] the definition of this symbol" }, $documentation: "Base class for all symbols", }); var AST_SymbolAccessor = DEFNODE("SymbolAccessor", null, { $documentation: "The name of a property accessor (setter/getter function)" }, AST_Symbol); var AST_SymbolDeclaration = DEFNODE("SymbolDeclaration", "init", { $documentation: "A declaration symbol (symbol in var/const, function name or argument, symbol in catch)", $propdoc: { init: "[AST_Node*/S] array of initializers for this declaration." } }, AST_Symbol); var AST_SymbolVar = DEFNODE("SymbolVar", null, { $documentation: "Symbol defining a variable", }, AST_SymbolDeclaration); var AST_SymbolConst = DEFNODE("SymbolConst", null, { $documentation: "A constant declaration" }, AST_SymbolDeclaration); var AST_SymbolFunarg = DEFNODE("SymbolFunarg", null, { $documentation: "Symbol naming a function argument", }, AST_SymbolVar); var AST_SymbolDefun = DEFNODE("SymbolDefun", null, { $documentation: "Symbol defining a function", }, AST_SymbolDeclaration); var AST_SymbolLambda = DEFNODE("SymbolLambda", null, { $documentation: "Symbol naming a function expression", }, AST_SymbolDeclaration); var AST_SymbolCatch = DEFNODE("SymbolCatch", null, { $documentation: "Symbol naming the exception in catch", }, AST_SymbolDeclaration); var AST_Label = DEFNODE("Label", "references", { $documentation: "Symbol naming a label (declaration)", $propdoc: { references: "[AST_LoopControl*] a list of nodes referring to this label" }, initialize: function() { this.references = []; this.thedef = this; } }, AST_Symbol); var AST_SymbolRef = DEFNODE("SymbolRef", null, { $documentation: "Reference to some symbol (not definition/declaration)", }, AST_Symbol); var AST_LabelRef = DEFNODE("LabelRef", null, { $documentation: "Reference to a label symbol", }, AST_Symbol); var AST_This = DEFNODE("This", null, { $documentation: "The `this` symbol", }, AST_Symbol); var AST_Constant = DEFNODE("Constant", null, { $documentation: "Base class for all constants", getValue: function() { return this.value; } }); var AST_String = DEFNODE("String", "value quote", { $documentation: "A string literal", $propdoc: { value: "[string] the contents of this string", quote: "[string] the original quote character" } }, AST_Constant); var AST_Number = DEFNODE("Number", "value literal", { $documentation: "A number literal", $propdoc: { value: "[number] the numeric value", literal: "[string] numeric value as string (optional)" } }, AST_Constant); var AST_RegExp = DEFNODE("RegExp", "value", { $documentation: "A regexp literal", $propdoc: { value: "[RegExp] the actual regexp" } }, AST_Constant); var AST_Atom = DEFNODE("Atom", null, { $documentation: "Base class for atoms", }, AST_Constant); var AST_Null = DEFNODE("Null", null, { $documentation: "The `null` atom", value: null }, AST_Atom); var AST_NaN = DEFNODE("NaN", null, { $documentation: "The impossible value", value: 0/0 }, AST_Atom); var AST_Undefined = DEFNODE("Undefined", null, { $documentation: "The `undefined` value", value: (function(){}()) }, AST_Atom); var AST_Hole = DEFNODE("Hole", null, { $documentation: "A hole in an array", value: (function(){}()) }, AST_Atom); var AST_Infinity = DEFNODE("Infinity", null, { $documentation: "The `Infinity` value", value: 1/0 }, AST_Atom); var AST_Boolean = DEFNODE("Boolean", null, { $documentation: "Base class for booleans", }, AST_Atom); var AST_False = DEFNODE("False", null, { $documentation: "The `false` atom", value: false }, AST_Boolean); var AST_True = DEFNODE("True", null, { $documentation: "The `true` atom", value: true }, AST_Boolean); /* -----[ TreeWalker ]----- */ function TreeWalker(callback) { this.visit = callback; this.stack = []; this.directives = Object.create(null); }; TreeWalker.prototype = { _visit: function(node, descend) { this.push(node); var ret = this.visit(node, descend ? function(){ descend.call(node); } : noop); if (!ret && descend) { descend.call(node); } this.pop(node); return ret; }, parent: function(n) { return this.stack[this.stack.length - 2 - (n || 0)]; }, push: function (node) { if (node instanceof AST_Lambda) { this.directives = Object.create(this.directives); } else if (node instanceof AST_Directive) { this.directives[node.value] = this.directives[node.value] ? "up" : true; } this.stack.push(node); }, pop: function(node) { this.stack.pop(); if (node instanceof AST_Lambda) { this.directives = Object.getPrototypeOf(this.directives); } }, self: function() { return this.stack[this.stack.length - 1]; }, find_parent: function(type) { var stack = this.stack; for (var i = stack.length; --i >= 0;) { var x = stack[i]; if (x instanceof type) return x; } }, has_directive: function(type) { var dir = this.directives[type]; if (dir) return dir; var node = this.stack[this.stack.length - 1]; if (node instanceof AST_Scope) { for (var i = 0; i < node.body.length; ++i) { var st = node.body[i]; if (!(st instanceof AST_Directive)) break; if (st.value == type) return true; } } }, in_boolean_context: function() { var stack = this.stack; var i = stack.length, self = stack[--i]; while (i > 0) { var p = stack[--i]; if ((p instanceof AST_If && p.condition === self) || (p instanceof AST_Conditional && p.condition === self) || (p instanceof AST_DWLoop && p.condition === self) || (p instanceof AST_For && p.condition === self) || (p instanceof AST_UnaryPrefix && p.operator == "!" && p.expression === self)) { return true; } if (!(p instanceof AST_Binary && (p.operator == "&&" || p.operator == "||"))) return false; self = p; } }, loopcontrol_target: function(label) { var stack = this.stack; if (label) for (var i = stack.length; --i >= 0;) { var x = stack[i]; if (x instanceof AST_LabeledStatement && x.label.name == label.name) { return x.body; } } else for (var i = stack.length; --i >= 0;) { var x = stack[i]; if (x instanceof AST_Switch || x instanceof AST_IterationStatement) return x; } } }; /*********************************************************************** A JavaScript tokenizer / parser / beautifier / compressor. https://github.com/mishoo/UglifyJS2 -------------------------------- (C) --------------------------------- Author: Mihai Bazon <mihai.bazon@gmail.com> http://mihai.bazon.net/blog Distributed under the BSD license: Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com> Parser based on parse-js (http://marijn.haverbeke.nl/parse-js/). Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************/ "use strict"; var KEYWORDS = 'break case catch const continue debugger default delete do else finally for function if in instanceof new return switch throw try typeof var void while with'; var KEYWORDS_ATOM = 'false null true'; var RESERVED_WORDS = 'abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized this throws transient volatile yield' + " " + KEYWORDS_ATOM + " " + KEYWORDS; var KEYWORDS_BEFORE_EXPRESSION = 'return new delete throw else case'; KEYWORDS = makePredicate(KEYWORDS); RESERVED_WORDS = makePredicate(RESERVED_WORDS); KEYWORDS_BEFORE_EXPRESSION = makePredicate(KEYWORDS_BEFORE_EXPRESSION); KEYWORDS_ATOM = makePredicate(KEYWORDS_ATOM); var OPERATOR_CHARS = makePredicate(characters("+-*&%=<>!?|~^")); var RE_HEX_NUMBER = /^0x[0-9a-f]+$/i; var RE_OCT_NUMBER = /^0[0-7]+$/; var OPERATORS = makePredicate([ "in", "instanceof", "typeof", "new", "void", "delete", "++", "--", "+", "-", "!", "~", "&", "|", "^", "*", "/", "%", ">>", "<<", ">>>", "<", ">", "<=", ">=", "==", "===", "!=", "!==", "?", "=", "+=", "-=", "/=", "*=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&=", "&&", "||" ]); var WHITESPACE_CHARS = makePredicate(characters(" \u00a0\n\r\t\f\u000b\u200b\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\uFEFF")); var PUNC_BEFORE_EXPRESSION = makePredicate(characters("[{(,.;:")); var PUNC_CHARS = makePredicate(characters("[]{}(),;:")); var REGEXP_MODIFIERS = makePredicate(characters("gmsiy")); /* -----[ Tokenizer ]----- */ // regexps adapted from http://xregexp.com/plugins/#unicode var UNICODE = { letter: new RegExp("[\\u0041-\\u005A\\u0061-\\u007A\\u00AA\\u00B5\\u00BA\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u08A0-\\u08B2\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C39\\u0C3D\\u0C58\\u0C59\\u0C60\\u0C61\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D60\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19C1-\\u19C7\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FCC\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA69D\\uA6A0-\\uA6EF\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA78E\\uA790-\\uA7AD\\uA7B0\\uA7B1\\uA7F7-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uA9E0-\\uA9E4\\uA9E6-\\uA9EF\\uA9FA-\\uA9FE\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA7E-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB5F\\uAB64\\uAB65\\uABC0-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]"), digit: new RegExp("[\\u0030-\\u0039\\u0660-\\u0669\\u06F0-\\u06F9\\u07C0-\\u07C9\\u0966-\\u096F\\u09E6-\\u09EF\\u0A66-\\u0A6F\\u0AE6-\\u0AEF\\u0B66-\\u0B6F\\u0BE6-\\u0BEF\\u0C66-\\u0C6F\\u0CE6-\\u0CEF\\u0D66-\\u0D6F\\u0DE6-\\u0DEF\\u0E50-\\u0E59\\u0ED0-\\u0ED9\\u0F20-\\u0F29\\u1040-\\u1049\\u1090-\\u1099\\u17E0-\\u17E9\\u1810-\\u1819\\u1946-\\u194F\\u19D0-\\u19D9\\u1A80-\\u1A89\\u1A90-\\u1A99\\u1B50-\\u1B59\\u1BB0-\\u1BB9\\u1C40-\\u1C49\\u1C50-\\u1C59\\uA620-\\uA629\\uA8D0-\\uA8D9\\uA900-\\uA909\\uA9D0-\\uA9D9\\uA9F0-\\uA9F9\\uAA50-\\uAA59\\uABF0-\\uABF9\\uFF10-\\uFF19]"), non_spacing_mark: new RegExp("[\\u0300-\\u036F\\u0483-\\u0487\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u0610-\\u061A\\u064B-\\u065E\\u0670\\u06D6-\\u06DC\\u06DF-\\u06E4\\u06E7\\u06E8\\u06EA-\\u06ED\\u0711\\u0730-\\u074A\\u07A6-\\u07B0\\u07EB-\\u07F3\\u0816-\\u0819\\u081B-\\u0823\\u0825-\\u0827\\u0829-\\u082D\\u0900-\\u0902\\u093C\\u0941-\\u0948\\u094D\\u0951-\\u0955\\u0962\\u0963\\u0981\\u09BC\\u09C1-\\u09C4\\u09CD\\u09E2\\u09E3\\u0A01\\u0A02\\u0A3C\\u0A41\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A70\\u0A71\\u0A75\\u0A81\\u0A82\\u0ABC\\u0AC1-\\u0AC5\\u0AC7\\u0AC8\\u0ACD\\u0AE2\\u0AE3\\u0B01\\u0B3C\\u0B3F\\u0B41-\\u0B44\\u0B4D\\u0B56\\u0B62\\u0B63\\u0B82\\u0BC0\\u0BCD\\u0C3E-\\u0C40\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C62\\u0C63\\u0CBC\\u0CBF\\u0CC6\\u0CCC\\u0CCD\\u0CE2\\u0CE3\\u0D41-\\u0D44\\u0D4D\\u0D62\\u0D63\\u0DCA\\u0DD2-\\u0DD4\\u0DD6\\u0E31\\u0E34-\\u0E3A\\u0E47-\\u0E4E\\u0EB1\\u0EB4-\\u0EB9\\u0EBB\\u0EBC\\u0EC8-\\u0ECD\\u0F18\\u0F19\\u0F35\\u0F37\\u0F39\\u0F71-\\u0F7E\\u0F80-\\u0F84\\u0F86\\u0F87\\u0F90-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u102D-\\u1030\\u1032-\\u1037\\u1039\\u103A\\u103D\\u103E\\u1058\\u1059\\u105E-\\u1060\\u1071-\\u1074\\u1082\\u1085\\u1086\\u108D\\u109D\\u135F\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17B7-\\u17BD\\u17C6\\u17C9-\\u17D3\\u17DD\\u180B-\\u180D\\u18A9\\u1920-\\u1922\\u1927\\u1928\\u1932\\u1939-\\u193B\\u1A17\\u1A18\\u1A56\\u1A58-\\u1A5E\\u1A60\\u1A62\\u1A65-\\u1A6C\\u1A73-\\u1A7C\\u1A7F\\u1B00-\\u1B03\\u1B34\\u1B36-\\u1B3A\\u1B3C\\u1B42\\u1B6B-\\u1B73\\u1B80\\u1B81\\u1BA2-\\u1BA5\\u1BA8\\u1BA9\\u1C2C-\\u1C33\\u1C36\\u1C37\\u1CD0-\\u1CD2\\u1CD4-\\u1CE0\\u1CE2-\\u1CE8\\u1CED\\u1DC0-\\u1DE6\\u1DFD-\\u1DFF\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2CEF-\\u2CF1\\u2DE0-\\u2DFF\\u302A-\\u302F\\u3099\\u309A\\uA66F\\uA67C\\uA67D\\uA6F0\\uA6F1\\uA802\\uA806\\uA80B\\uA825\\uA826\\uA8C4\\uA8E0-\\uA8F1\\uA926-\\uA92D\\uA947-\\uA951\\uA980-\\uA982\\uA9B3\\uA9B6-\\uA9B9\\uA9BC\\uAA29-\\uAA2E\\uAA31\\uAA32\\uAA35\\uAA36\\uAA43\\uAA4C\\uAAB0\\uAAB2-\\uAAB4\\uAAB7\\uAAB8\\uAABE\\uAABF\\uAAC1\\uABE5\\uABE8\\uABED\\uFB1E\\uFE00-\\uFE0F\\uFE20-\\uFE26]"), space_combining_mark: new RegExp("[\\u0903\\u093E-\\u0940\\u0949-\\u094C\\u094E\\u0982\\u0983\\u09BE-\\u09C0\\u09C7\\u09C8\\u09CB\\u09CC\\u09D7\\u0A03\\u0A3E-\\u0A40\\u0A83\\u0ABE-\\u0AC0\\u0AC9\\u0ACB\\u0ACC\\u0B02\\u0B03\\u0B3E\\u0B40\\u0B47\\u0B48\\u0B4B\\u0B4C\\u0B57\\u0BBE\\u0BBF\\u0BC1\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCC\\u0BD7\\u0C01-\\u0C03\\u0C41-\\u0C44\\u0C82\\u0C83\\u0CBE\\u0CC0-\\u0CC4\\u0CC7\\u0CC8\\u0CCA\\u0CCB\\u0CD5\\u0CD6\\u0D02\\u0D03\\u0D3E-\\u0D40\\u0D46-\\u0D48\\u0D4A-\\u0D4C\\u0D57\\u0D82\\u0D83\\u0DCF-\\u0DD1\\u0DD8-\\u0DDF\\u0DF2\\u0DF3\\u0F3E\\u0F3F\\u0F7F\\u102B\\u102C\\u1031\\u1038\\u103B\\u103C\\u1056\\u1057\\u1062-\\u1064\\u1067-\\u106D\\u1083\\u1084\\u1087-\\u108C\\u108F\\u109A-\\u109C\\u17B6\\u17BE-\\u17C5\\u17C7\\u17C8\\u1923-\\u1926\\u1929-\\u192B\\u1930\\u1931\\u1933-\\u1938\\u19B0-\\u19C0\\u19C8\\u19C9\\u1A19-\\u1A1B\\u1A55\\u1A57\\u1A61\\u1A63\\u1A64\\u1A6D-\\u1A72\\u1B04\\u1B35\\u1B3B\\u1B3D-\\u1B41\\u1B43\\u1B44\\u1B82\\u1BA1\\u1BA6\\u1BA7\\u1BAA\\u1C24-\\u1C2B\\u1C34\\u1C35\\u1CE1\\u1CF2\\uA823\\uA824\\uA827\\uA880\\uA881\\uA8B4-\\uA8C3\\uA952\\uA953\\uA983\\uA9B4\\uA9B5\\uA9BA\\uA9BB\\uA9BD-\\uA9C0\\uAA2F\\uAA30\\uAA33\\uAA34\\uAA4D\\uAA7B\\uABE3\\uABE4\\uABE6\\uABE7\\uABE9\\uABEA\\uABEC]"), connector_punctuation: new RegExp("[\\u005F\\u203F\\u2040\\u2054\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFF3F]") }; function is_letter(code) { return (code >= 97 && code <= 122) || (code >= 65 && code <= 90) || (code >= 0xaa && UNICODE.letter.test(String.fromCharCode(code))); }; function is_digit(code) { return code >= 48 && code <= 57; }; function is_alphanumeric_char(code) { return is_digit(code) || is_letter(code); }; function is_unicode_digit(code) { return UNICODE.digit.test(String.fromCharCode(code)); } function is_unicode_combining_mark(ch) { return UNICODE.non_spacing_mark.test(ch) || UNICODE.space_combining_mark.test(ch); }; function is_unicode_connector_punctuation(ch) { return UNICODE.connector_punctuation.test(ch); }; function is_identifier(name) { return !RESERVED_WORDS(name) && /^[a-z_$][a-z0-9_$]*$/i.test(name); }; function is_identifier_start(code) { return code == 36 || code == 95 || is_letter(code); }; function is_identifier_char(ch) { var code = ch.charCodeAt(0); return is_identifier_start(code) || is_digit(code) || code == 8204 // \u200c: zero-width non-joiner <ZWNJ> || code == 8205 // \u200d: zero-width joiner <ZWJ> (in my ECMA-262 PDF, this is also 200c) || is_unicode_combining_mark(ch) || is_unicode_connector_punctuation(ch) || is_unicode_digit(code) ; }; function is_identifier_string(str){ return /^[a-z_$][a-z0-9_$]*$/i.test(str); }; function parse_js_number(num) { if (RE_HEX_NUMBER.test(num)) { return parseInt(num.substr(2), 16); } else if (RE_OCT_NUMBER.test(num)) { return parseInt(num.substr(1), 8); } else { var val = parseFloat(num); if (val == num) return val; } }; function JS_Parse_Error(message, filename, line, col, pos) { this.message = message; this.filename = filename; this.line = line; this.col = col; this.pos = pos; this.stack = new Error().stack; }; JS_Parse_Error.prototype.toString = function() { return this.message + " (line: " + this.line + ", col: " + this.col + ", pos: " + this.pos + ")" + "\n\n" + this.stack; }; function js_error(message, filename, line, col, pos) { throw new JS_Parse_Error(message, filename, line, col, pos); }; function is_token(token, type, val) { return token.type == type && (val == null || token.value == val); }; var EX_EOF = {}; function tokenizer($TEXT, filename, html5_comments, shebang) { var S = { text : $TEXT, filename : filename, pos : 0, tokpos : 0, line : 1, tokline : 0, col : 0, tokcol : 0, newline_before : false, regex_allowed : false, comments_before : [] }; function peek() { return S.text.charAt(S.pos); }; function next(signal_eof, in_string) { var ch = S.text.charAt(S.pos++); if (signal_eof && !ch) throw EX_EOF; if ("\r\n\u2028\u2029".indexOf(ch) >= 0) { S.newline_before = S.newline_before || !in_string; ++S.line; S.col = 0; if (!in_string && ch == "\r" && peek() == "\n") { // treat a \r\n sequence as a single \n ++S.pos; ch = "\n"; } } else { ++S.col; } return ch; }; function forward(i) { while (i-- > 0) next(); }; function looking_at(str) { return S.text.substr(S.pos, str.length) == str; }; function find(what, signal_eof) { var pos = S.text.indexOf(what, S.pos); if (signal_eof && pos == -1) throw EX_EOF; return pos; }; function start_token() { S.tokline = S.line; S.tokcol = S.col; S.tokpos = S.pos; }; var prev_was_dot = false; function token(type, value, is_comment) { S.regex_allowed = ((type == "operator" && !UNARY_POSTFIX(value)) || (type == "keyword" && KEYWORDS_BEFORE_EXPRESSION(value)) || (type == "punc" && PUNC_BEFORE_EXPRESSION(value))); prev_was_dot = (type == "punc" && value == "."); var ret = { type : type, value : value, line : S.tokline, col : S.tokcol, pos : S.tokpos, endline : S.line, endcol : S.col, endpos : S.pos, nlb : S.newline_before, file : filename }; if (/^(?:num|string|regexp)$/i.test(type)) { ret.raw = $TEXT.substring(ret.pos, ret.endpos); } if (!is_comment) { ret.comments_before = S.comments_before; S.comments_before = []; // make note of any newlines in the comments that came before for (var i = 0, len = ret.comments_before.length; i < len; i++) { ret.nlb = ret.nlb || ret.comments_before[i].nlb; } } S.newline_before = false; return new AST_Token(ret); }; function skip_whitespace() { var ch; while (WHITESPACE_CHARS(ch = peek()) || ch == "\u2028" || ch == "\u2029") next(); }; function read_while(pred) { var ret = "", ch, i = 0; while ((ch = peek()) && pred(ch, i++)) ret += next(); return ret; }; function parse_error(err) { js_error(err, filename, S.tokline, S.tokcol, S.tokpos); }; function read_num(prefix) { var has_e = false, after_e = false, has_x = false, has_dot = prefix == "."; var num = read_while(function(ch, i){ var code = ch.charCodeAt(0); switch (code) { case 120: case 88: // xX return has_x ? false : (has_x = true); case 101: case 69: // eE return has_x ? true : has_e ? false : (has_e = after_e = true); case 45: // - return after_e || (i == 0 && !prefix); case 43: // + return after_e; case (after_e = false, 46): // . return (!has_dot && !has_x && !has_e) ? (has_dot = true) : false; } return is_alphanumeric_char(code); }); if (prefix) num = prefix + num; var valid = parse_js_number(num); if (!isNaN(valid)) { return token("num", valid); } else { parse_error("Invalid syntax: " + num); } }; function read_escaped_char(in_string) { var ch = next(true, in_string); switch (ch.charCodeAt(0)) { case 110 : return "\n"; case 114 : return "\r"; case 116 : return "\t"; case 98 : return "\b"; case 118 : return "\u000b"; // \v case 102 : return "\f"; case 48 : return "\0"; case 120 : return String.fromCharCode(hex_bytes(2)); // \x case 117 : return String.fromCharCode(hex_bytes(4)); // \u case 10 : return ""; // newline case 13 : // \r if (peek() == "\n") { // DOS newline next(true, in_string); return ""; } } return ch; }; function hex_bytes(n) { var num = 0; for (; n > 0; --n) { var digit = parseInt(next(true), 16); if (isNaN(digit)) parse_error("Invalid hex-character pattern in string"); num = (num << 4) | digit; } return num; }; var read_string = with_eof_error("Unterminated string constant", function(quote_char){ var quote = next(), ret = ""; for (;;) { var ch = next(true, true); if (ch == "\\") { // read OctalEscapeSequence (XXX: deprecated if "strict mode") // https://github.com/mishoo/UglifyJS/issues/178 var octal_len = 0, first = null; ch = read_while(function(ch){ if (ch >= "0" && ch <= "7") { if (!first) { first = ch; return ++octal_len; } else if (first <= "3" && octal_len <= 2) return ++octal_len; else if (first >= "4" && octal_len <= 1) return ++octal_len; } return false; }); if (octal_len > 0) ch = String.fromCharCode(parseInt(ch, 8)); else ch = read_escaped_char(true); } else if (ch == quote) break; ret += ch; } var tok = token("string", ret); tok.quote = quote_char; return tok; }); function skip_line_comment(type) { var regex_allowed = S.regex_allowed; var i = find("\n"), ret; if (i == -1) { ret = S.text.substr(S.pos); S.pos = S.text.length; } else { ret = S.text.substring(S.pos, i); S.pos = i; } S.col = S.tokcol + (S.pos - S.tokpos); S.comments_before.push(token(type, ret, true)); S.regex_allowed = regex_allowed; return next_token(); }; var skip_multiline_comment = with_eof_error("Unterminated multiline comment", function(){ var regex_allowed = S.regex_allowed; var i = find("*/", true); var text = S.text.substring(S.pos, i); var a = text.split("\n"), n = a.length; // update stream position S.pos = i + 2; S.line += n - 1; if (n > 1) S.col = a[n - 1].length; else S.col += a[n - 1].length; S.col += 2; var nlb = S.newline_before = S.newline_before || text.indexOf("\n") >= 0; S.comments_before.push(token("comment2", text, true)); S.regex_allowed = regex_allowed; S.newline_before = nlb; return next_token(); }); function read_name() { var backslash = false, name = "", ch, escaped = false, hex; while ((ch = peek()) != null) { if (!backslash) { if (ch == "\\") escaped = backslash = true, next(); else if (is_identifier_char(ch)) name += next(); else break; } else { if (ch != "u") parse_error("Expecting UnicodeEscapeSequence -- uXXXX"); ch = read_escaped_char(); if (!is_identifier_char(ch)) parse_error("Unicode char: " + ch.charCodeAt(0) + " is not valid in identifier"); name += ch; backslash = false; } } if (KEYWORDS(name) && escaped) { hex = name.charCodeAt(0).toString(16).toUpperCase(); name = "\\u" + "0000".substr(hex.length) + hex + name.slice(1); } return name; }; var read_regexp = with_eof_error("Unterminated regular expression", function(regexp){ var prev_backslash = false, ch, in_class = false; while ((ch = next(true))) if (prev_backslash) { regexp += "\\" + ch; prev_backslash = false; } else if (ch == "[") { in_class = true; regexp += ch; } else if (ch == "]" && in_class) { in_class = false; regexp += ch; } else if (ch == "/" && !in_class) { break; } else if (ch == "\\") { prev_backslash = true; } else { regexp += ch; } var mods = read_name(); try { return token("regexp", new RegExp(regexp, mods)); } catch(e) { parse_error(e.message); } }); function read_operator(prefix) { function grow(op) { if (!peek()) return op; var bigger = op + peek(); if (OPERATORS(bigger)) { next(); return grow(bigger); } else { return op; } }; return token("operator", grow(prefix || next())); }; function handle_slash() { next(); switch (peek()) { case "/": next(); return skip_line_comment("comment1"); case "*": next(); return skip_multiline_comment(); } return S.regex_allowed ? read_regexp("") : read_operator("/"); }; function handle_dot() { next(); return is_digit(peek().charCodeAt(0)) ? read_num(".") : token("punc", "."); }; function read_word() { var word = read_name(); if (prev_was_dot) return token("name", word); return KEYWORDS_ATOM(word) ? token("atom", word) : !KEYWORDS(word) ? token("name", word) : OPERATORS(word) ? token("operator", word) : token("keyword", word); }; function with_eof_error(eof_error, cont) { return function(x) { try { return cont(x); } catch(ex) { if (ex === EX_EOF) parse_error(eof_error); else throw ex; } }; }; function next_token(force_regexp) { if (force_regexp != null) return read_regexp(force_regexp); skip_whitespace(); start_token(); if (html5_comments) { if (looking_at("<!--")) { forward(4); return skip_line_comment("comment3"); } if (looking_at("-->") && S.newline_before) { forward(3); return skip_line_comment("comment4"); } } var ch = peek(); if (!ch) return token("eof"); var code = ch.charCodeAt(0); switch (code) { case 34: case 39: return read_string(ch); case 46: return handle_dot(); case 47: return handle_slash(); } if (is_digit(code)) return read_num(); if (PUNC_CHARS(ch)) return token("punc", next()); if (OPERATOR_CHARS(ch)) return read_operator(); if (code == 92 || is_identifier_start(code)) return read_word(); if (shebang) { if (S.pos == 0 && looking_at("#!")) { forward(2); return skip_line_comment("comment5"); } } parse_error("Unexpected character '" + ch + "'"); }; next_token.context = function(nc) { if (nc) S = nc; return S; }; return next_token; }; /* -----[ Parser (constants) ]----- */ var UNARY_PREFIX = makePredicate([ "typeof", "void", "delete", "--", "++", "!", "~", "-", "+" ]); var UNARY_POSTFIX = makePredicate([ "--", "++" ]); var ASSIGNMENT = makePredicate([ "=", "+=", "-=", "/=", "*=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&=" ]); var PRECEDENCE = (function(a, ret){ for (var i = 0; i < a.length; ++i) { var b = a[i]; for (var j = 0; j < b.length; ++j) { ret[b[j]] = i + 1; } } return ret; })( [ ["||"], ["&&"], ["|"], ["^"], ["&"], ["==", "===", "!=", "!=="], ["<", ">", "<=", ">=", "in", "instanceof"], [">>", "<<", ">>>"], ["+", "-"], ["*", "/", "%"] ], {} ); var STATEMENTS_WITH_LABELS = array_to_hash([ "for", "do", "while", "switch" ]); var ATOMIC_START_TOKEN = array_to_hash([ "atom", "num", "string", "regexp", "name" ]); /* -----[ Parser ]----- */ function parse($TEXT, options) { options = defaults(options, { strict : false, filename : null, toplevel : null, expression : false, html5_comments : true, bare_returns : false, shebang : true, }); var S = { input : (typeof $TEXT == "string" ? tokenizer($TEXT, options.filename, options.html5_comments, options.shebang) : $TEXT), token : null, prev : null, peeked : null, in_function : 0, in_directives : true, in_loop : 0, labels : [] }; S.token = next(); function is(type, value) { return is_token(S.token, type, value); }; function peek() { return S.peeked || (S.peeked = S.input()); }; function next() { S.prev = S.token; if (S.peeked) { S.token = S.peeked; S.peeked = null; } else { S.token = S.input(); } S.in_directives = S.in_directives && ( S.token.type == "string" || is("punc", ";") ); return S.token; }; function prev() { return S.prev; }; function croak(msg, line, col, pos) { var ctx = S.input.context(); js_error(msg, ctx.filename, line != null ? line : ctx.tokline, col != null ? col : ctx.tokcol, pos != null ? pos : ctx.tokpos); }; function token_error(token, msg) { croak(msg, token.line, token.col); }; function unexpected(token) { if (token == null) token = S.token; token_error(token, "Unexpected token: " + token.type + " (" + token.value + ")"); }; function expect_token(type, val) { if (is(type, val)) { return next(); } token_error(S.token, "Unexpected token " + S.token.type + " «" + S.token.value + "»" + ", expected " + type + " «" + val + "»"); }; function expect(punc) { return expect_token("punc", punc); }; function can_insert_semicolon() { return !options.strict && ( S.token.nlb || is("eof") || is("punc", "}") ); }; function semicolon() { if (is("punc", ";")) next(); else if (!can_insert_semicolon()) unexpected(); }; function parenthesised() { expect("("); var exp = expression(true); expect(")"); return exp; }; function embed_tokens(parser) { return function() { var start = S.token; var expr = parser(); var end = prev(); expr.start = start; expr.end = end; return expr; }; }; function handle_regexp() { if (is("operator", "/") || is("operator", "/=")) { S.peeked = null; S.token = S.input(S.token.value.substr(1)); // force regexp } }; var statement = embed_tokens(function() { var tmp; handle_regexp(); switch (S.token.type) { case "string": var dir = S.in_directives, stat = simple_statement(); // XXXv2: decide how to fix directives if (dir && stat.body instanceof AST_String && !is("punc", ",")) { return new AST_Directive({ start : stat.body.start, end : stat.body.end, quote : stat.body.quote, value : stat.body.value, }); } return stat; case "num": case "regexp": case "operator": case "atom": return simple_statement(); case "name": return is_token(peek(), "punc", ":") ? labeled_statement() : simple_statement(); case "punc": switch (S.token.value) { case "{": return new AST_BlockStatement({ start : S.token, body : block_(), end : prev() }); case "[": case "(": return simple_statement(); case ";": next(); return new AST_EmptyStatement(); default: unexpected(); } case "keyword": switch (tmp = S.token.value, next(), tmp) { case "break": return break_cont(AST_Break); case "continue": return break_cont(AST_Continue); case "debugger": semicolon(); return new AST_Debugger(); case "do": return new AST_Do({ body : in_loop(statement), condition : (expect_token("keyword", "while"), tmp = parenthesised(), semicolon(), tmp) }); case "while": return new AST_While({ condition : parenthesised(), body : in_loop(statement) }); case "for": return for_(); case "function": return function_(AST_Defun); case "if": return if_(); case "return": if (S.in_function == 0 && !options.bare_returns) croak("'return' outside of function"); return new AST_Return({ value: ( is("punc", ";") ? (next(), null) : can_insert_semicolon() ? null : (tmp = expression(true), semicolon(), tmp) ) }); case "switch": return new AST_Switch({ expression : parenthesised(), body : in_loop(switch_body_) }); case "throw": if (S.token.nlb) croak("Illegal newline after 'throw'"); return new AST_Throw({ value: (tmp = expression(true), semicolon(), tmp) }); case "try": return try_(); case "var": return tmp = var_(), semicolon(), tmp; case "const": return tmp = const_(), semicolon(), tmp; case "with": return new AST_With({ expression : parenthesised(), body : statement() }); default: unexpected(); } } }); function labeled_statement() { var label = as_symbol(AST_Label); if (find_if(function(l){ return l.name == label.name }, S.labels)) { // ECMA-262, 12.12: An ECMAScript program is considered // syntactically incorrect if it contains a // LabelledStatement that is enclosed by a // LabelledStatement with the same Identifier as label. croak("Label " + label.name + " defined twice"); } expect(":"); S.labels.push(label); var stat = statement(); S.labels.pop(); if (!(stat instanceof AST_IterationStatement)) { // check for `continue` that refers to this label. // those should be reported as syntax errors. // https://github.com/mishoo/UglifyJS2/issues/287 label.references.forEach(function(ref){ if (ref instanceof AST_Continue) { ref = ref.label.start; croak("Continue label `" + label.name + "` refers to non-IterationStatement.", ref.line, ref.col, ref.pos); } }); } return new AST_LabeledStatement({ body: stat, label: label }); }; function simple_statement(tmp) { return new AST_SimpleStatement({ body: (tmp = expression(true), semicolon(), tmp) }); }; function break_cont(type) { var label = null, ldef; if (!can_insert_semicolon()) { label = as_symbol(AST_LabelRef, true); } if (label != null) { ldef = find_if(function(l){ return l.name == label.name }, S.labels); if (!ldef) croak("Undefined label " + label.name); label.thedef = ldef; } else if (S.in_loop == 0) croak(type.TYPE + " not inside a loop or switch"); semicolon(); var stat = new type({ label: label }); if (ldef) ldef.references.push(stat); return stat; }; function for_() { expect("("); var init = null; if (!is("punc", ";")) { init = is("keyword", "var") ? (next(), var_(true)) : expression(true, true); if (is("operator", "in")) { if (init instanceof AST_Var && init.definitions.length > 1) croak("Only one variable declaration allowed in for..in loop"); next(); return for_in(init); } } return regular_for(init); }; function regular_for(init) { expect(";"); var test = is("punc", ";") ? null : expression(true); expect(";"); var step = is("punc", ")") ? null : expression(true); expect(")"); return new AST_For({ init : init, condition : test, step : step, body : in_loop(statement) }); }; function for_in(init) { var lhs = init instanceof AST_Var ? init.definitions[0].name : null; var obj = expression(true); expect(")"); return new AST_ForIn({ init : init, name : lhs, object : obj, body : in_loop(statement) }); }; var function_ = function(ctor) { var in_statement = ctor === AST_Defun; var name = is("name") ? as_symbol(in_statement ? AST_SymbolDefun : AST_SymbolLambda) : null; if (in_statement && !name) unexpected(); expect("("); return new ctor({ name: name, argnames: (function(first, a){ while (!is("punc", ")")) { if (first) first = false; else expect(","); a.push(as_symbol(AST_SymbolFunarg)); } next(); return a; })(true, []), body: (function(loop, labels){ ++S.in_function; S.in_directives = true; S.in_loop = 0; S.labels = []; var a = block_(); --S.in_function; S.in_loop = loop; S.labels = labels; return a; })(S.in_loop, S.labels) }); }; function if_() { var cond = parenthesised(), body = statement(), belse = null; if (is("keyword", "else")) { next(); belse = statement(); } return new AST_If({ condition : cond, body : body, alternative : belse }); }; function block_() { expect("{"); var a = []; while (!is("punc", "}")) { if (is("eof")) unexpected(); a.push(statement()); } next(); return a; }; function switch_body_() { expect("{"); var a = [], cur = null, branch = null, tmp; while (!is("punc", "}")) { if (is("eof")) unexpected(); if (is("keyword", "case")) { if (branch) branch.end = prev(); cur = []; branch = new AST_Case({ start : (tmp = S.token, next(), tmp), expression : expression(true), body : cur }); a.push(branch); expect(":"); } else if (is("keyword", "default")) { if (branch) branch.end = prev(); cur = []; branch = new AST_Default({ start : (tmp = S.token, next(), expect(":"), tmp), body : cur }); a.push(branch); } else { if (!cur) unexpected(); cur.push(statement()); } } if (branch) branch.end = prev(); next(); return a; }; function try_() { var body = block_(), bcatch = null, bfinally = null; if (is("keyword", "catch")) { var start = S.token; next(); expect("("); var name = as_symbol(AST_SymbolCatch); expect(")"); bcatch = new AST_Catch({ start : start, argname : name, body : block_(), end : prev() }); } if (is("keyword", "finally")) { var start = S.token; next(); bfinally = new AST_Finally({ start : start, body : block_(), end : prev() }); } if (!bcatch && !bfinally) croak("Missing catch/finally blocks"); return new AST_Try({ body : body, bcatch : bcatch, bfinally : bfinally }); }; function vardefs(no_in, in_const) { var a = []; for (;;) { a.push(new AST_VarDef({ start : S.token, name : as_symbol(in_const ? AST_SymbolConst : AST_SymbolVar), value : is("operator", "=") ? (next(), expression(false, no_in)) : null, end : prev() })); if (!is("punc", ",")) break; next(); } return a; }; var var_ = function(no_in) { return new AST_Var({ start : prev(), definitions : vardefs(no_in, false), end : prev() }); }; var const_ = function() { return new AST_Const({ start : prev(), definitions : vardefs(false, true), end : prev() }); }; var new_ = function(allow_calls) { var start = S.token; expect_token("operator", "new"); var newexp = expr_atom(false), args; if (is("punc", "(")) { next(); args = expr_list(")"); } else { args = []; } return subscripts(new AST_New({ start : start, expression : newexp, args : args, end : prev() }), allow_calls); }; function as_atom_node() { var tok = S.token, ret; switch (tok.type) { case "name": case "keyword": ret = _make_symbol(AST_SymbolRef); break; case "num": ret = new AST_Number({ start: tok, end: tok, value: tok.value }); break; case "string": ret = new AST_String({ start : tok, end : tok, value : tok.value, quote : tok.quote }); break; case "regexp": ret = new AST_RegExp({ start: tok, end: tok, value: tok.value }); break; case "atom": switch (tok.value) { case "false": ret = new AST_False({ start: tok, end: tok }); break; case "true": ret = new AST_True({ start: tok, end: tok }); break; case "null": ret = new AST_Null({ start: tok, end: tok }); break; } break; } next(); return ret; }; var expr_atom = function(allow_calls) { if (is("operator", "new")) { return new_(allow_calls); } var start = S.token; if (is("punc")) { switch (start.value) { case "(": next(); var ex = expression(true); ex.start = start; ex.end = S.token; expect(")"); return subscripts(ex, allow_calls); case "[": return subscripts(array_(), allow_calls); case "{": return subscripts(object_(), allow_calls); } unexpected(); } if (is("keyword", "function")) { next(); var func = function_(AST_Function); func.start = start; func.end = prev(); return subscripts(func, allow_calls); } if (ATOMIC_START_TOKEN[S.token.type]) { return subscripts(as_atom_node(), allow_calls); } unexpected(); }; function expr_list(closing, allow_trailing_comma, allow_empty) { var first = true, a = []; while (!is("punc", closing)) { if (first) first = false; else expect(","); if (allow_trailing_comma && is("punc", closing)) break; if (is("punc", ",") && allow_empty) { a.push(new AST_Hole({ start: S.token, end: S.token })); } else { a.push(expression(false)); } } next(); return a; }; var array_ = embed_tokens(function() { expect("["); return new AST_Array({ elements: expr_list("]", !options.strict, true) }); }); var object_ = embed_tokens(function() { expect("{"); var first = true, a = []; while (!is("punc", "}")) { if (first) first = false; else expect(","); if (!options.strict && is("punc", "}")) // allow trailing comma break; var start = S.token; var type = start.type; var name = as_property_name(); if (type == "name" && !is("punc", ":")) { if (name == "get") { a.push(new AST_ObjectGetter({ start : start, key : as_atom_node(), value : function_(AST_Accessor), end : prev() })); continue; } if (name == "set") { a.push(new AST_ObjectSetter({ start : start, key : as_atom_node(), value : function_(AST_Accessor), end : prev() })); continue; } } expect(":"); a.push(new AST_ObjectKeyVal({ start : start, quote : start.quote, key : name, value : expression(false), end : prev() })); } next(); return new AST_Object({ properties: a }); }); function as_property_name() { var tmp = S.token; next(); switch (tmp.type) { case "num": case "string": case "name": case "operator": case "keyword": case "atom": return tmp.value; default: unexpected(); } }; function as_name() { var tmp = S.token; next(); switch (tmp.type) { case "name": case "operator": case "keyword": case "atom": return tmp.value; default: unexpected(); } }; function _make_symbol(type) { var name = S.token.value; return new (name == "this" ? AST_This : type)({ name : String(name), start : S.token, end : S.token }); }; function as_symbol(type, noerror) { if (!is("name")) { if (!noerror) croak("Name expected"); return null; } var sym = _make_symbol(type); next(); return sym; }; var subscripts = function(expr, allow_calls) { var start = expr.start; if (is("punc", ".")) { next(); return subscripts(new AST_Dot({ start : start, expression : expr, property : as_name(), end : prev() }), allow_calls); } if (is("punc", "[")) { next(); var prop = expression(true); expect("]"); return subscripts(new AST_Sub({ start : start, expression : expr, property : prop, end : prev() }), allow_calls); } if (allow_calls && is("punc", "(")) { next(); return subscripts(new AST_Call({ start : start, expression : expr, args : expr_list(")"), end : prev() }), true); } return expr; }; var maybe_unary = function(allow_calls) { var start = S.token; if (is("operator") && UNARY_PREFIX(start.value)) { next(); handle_regexp(); var ex = make_unary(AST_UnaryPrefix, start.value, maybe_unary(allow_calls)); ex.start = start; ex.end = prev(); return ex; } var val = expr_atom(allow_calls); while (is("operator") && UNARY_POSTFIX(S.token.value) && !S.token.nlb) { val = make_unary(AST_UnaryPostfix, S.token.value, val); val.start = start; val.end = S.token; next(); } return val; }; function make_unary(ctor, op, expr) { if ((op == "++" || op == "--") && !is_assignable(expr)) croak("Invalid use of " + op + " operator"); return new ctor({ operator: op, expression: expr }); }; var expr_op = function(left, min_prec, no_in) { var op = is("operator") ? S.token.value : null; if (op == "in" && no_in) op = null; var prec = op != null ? PRECEDENCE[op] : null; if (prec != null && prec > min_prec) { next(); var right = expr_op(maybe_unary(true), prec, no_in); return expr_op(new AST_Binary({ start : left.start, left : left, operator : op, right : right, end : right.end }), min_prec, no_in); } return left; }; function expr_ops(no_in) { return expr_op(maybe_unary(true), 0, no_in); }; var maybe_conditional = function(no_in) { var start = S.token; var expr = expr_ops(no_in); if (is("operator", "?")) { next(); var yes = expression(false); expect(":"); return new AST_Conditional({ start : start, condition : expr, consequent : yes, alternative : expression(false, no_in), end : prev() }); } return expr; }; function is_assignable(expr) { if (!options.strict) return true; if (expr instanceof AST_This) return false; return (expr instanceof AST_PropAccess || expr instanceof AST_Symbol); }; var maybe_assign = function(no_in) { var start = S.token; var left = maybe_conditional(no_in), val = S.token.value; if (is("operator") && ASSIGNMENT(val)) { if (is_assignable(left)) { next(); return new AST_Assign({ start : start, left : left, operator : val, right : maybe_assign(no_in), end : prev() }); } croak("Invalid assignment"); } return left; }; var expression = function(commas, no_in) { var start = S.token; var expr = maybe_assign(no_in); if (commas && is("punc", ",")) { next(); return new AST_Seq({ start : start, car : expr, cdr : expression(true, no_in), end : peek() }); } return expr; }; function in_loop(cont) { ++S.in_loop; var ret = cont(); --S.in_loop; return ret; }; if (options.expression) { return expression(true); } return (function(){ var start = S.token; var body = []; while (!is("eof")) body.push(statement()); var end = prev(); var toplevel = options.toplevel; if (toplevel) { toplevel.body = toplevel.body.concat(body); toplevel.end = end; } else { toplevel = new AST_Toplevel({ start: start, body: body, end: end }); } return toplevel; })(); }; /*********************************************************************** A JavaScript tokenizer / parser / beautifier / compressor. https://github.com/mishoo/UglifyJS2 -------------------------------- (C) --------------------------------- Author: Mihai Bazon <mihai.bazon@gmail.com> http://mihai.bazon.net/blog Distributed under the BSD license: Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************/ "use strict"; // Tree transformer helpers. function TreeTransformer(before, after) { TreeWalker.call(this); this.before = before; this.after = after; } TreeTransformer.prototype = new TreeWalker; (function(undefined){ function _(node, descend) { node.DEFMETHOD("transform", function(tw, in_list){ var x, y; tw.push(this); if (tw.before) x = tw.before(this, descend, in_list); if (x === undefined) { if (!tw.after) { x = this; descend(x, tw); } else { tw.stack[tw.stack.length - 1] = x = this.clone(); descend(x, tw); y = tw.after(x, in_list); if (y !== undefined) x = y; } } tw.pop(this); return x; }); }; function do_list(list, tw) { return MAP(list, function(node){ return node.transform(tw, true); }); }; _(AST_Node, noop); _(AST_LabeledStatement, function(self, tw){ self.label = self.label.transform(tw); self.body = self.body.transform(tw); }); _(AST_SimpleStatement, function(self, tw){ self.body = self.body.transform(tw); }); _(AST_Block, function(self, tw){ self.body = do_list(self.body, tw); }); _(AST_DWLoop, function(self, tw){ self.condition = self.condition.transform(tw); self.body = self.body.transform(tw); }); _(AST_For, function(self, tw){ if (self.init) self.init = self.init.transform(tw); if (self.condition) self.condition = self.condition.transform(tw); if (self.step) self.step = self.step.transform(tw); self.body = self.body.transform(tw); }); _(AST_ForIn, function(self, tw){ self.init = self.init.transform(tw); self.object = self.object.transform(tw); self.body = self.body.transform(tw); }); _(AST_With, function(self, tw){ self.expression = self.expression.transform(tw); self.body = self.body.transform(tw); }); _(AST_Exit, function(self, tw){ if (self.value) self.value = self.value.transform(tw); }); _(AST_LoopControl, function(self, tw){ if (self.label) self.label = self.label.transform(tw); }); _(AST_If, function(self, tw){ self.condition = self.condition.transform(tw); self.body = self.body.transform(tw); if (self.alternative) self.alternative = self.alternative.transform(tw); }); _(AST_Switch, function(self, tw){ self.expression = self.expression.transform(tw); self.body = do_list(self.body, tw); }); _(AST_Case, function(self, tw){ self.expression = self.expression.transform(tw); self.body = do_list(self.body, tw); }); _(AST_Try, function(self, tw){ self.body = do_list(self.body, tw); if (self.bcatch) self.bcatch = self.bcatch.transform(tw); if (self.bfinally) self.bfinally = self.bfinally.transform(tw); }); _(AST_Catch, function(self, tw){ self.argname = self.argname.transform(tw); self.body = do_list(self.body, tw); }); _(AST_Definitions, function(self, tw){ self.definitions = do_list(self.definitions, tw); }); _(AST_VarDef, function(self, tw){ self.name = self.name.transform(tw); if (self.value) self.value = self.value.transform(tw); }); _(AST_Lambda, function(self, tw){ if (self.name) self.name = self.name.transform(tw); self.argnames = do_list(self.argnames, tw); self.body = do_list(self.body, tw); }); _(AST_Call, function(self, tw){ self.expression = self.expression.transform(tw); self.args = do_list(self.args, tw); }); _(AST_Seq, function(self, tw){ self.car = self.car.transform(tw); self.cdr = self.cdr.transform(tw); }); _(AST_Dot, function(self, tw){ self.expression = self.expression.transform(tw); }); _(AST_Sub, function(self, tw){ self.expression = self.expression.transform(tw); self.property = self.property.transform(tw); }); _(AST_Unary, function(self, tw){ self.expression = self.expression.transform(tw); }); _(AST_Binary, function(self, tw){ self.left = self.left.transform(tw); self.right = self.right.transform(tw); }); _(AST_Conditional, function(self, tw){ self.condition = self.condition.transform(tw); self.consequent = self.consequent.transform(tw); self.alternative = self.alternative.transform(tw); }); _(AST_Array, function(self, tw){ self.elements = do_list(self.elements, tw); }); _(AST_Object, function(self, tw){ self.properties = do_list(self.properties, tw); }); _(AST_ObjectProperty, function(self, tw){ self.value = self.value.transform(tw); }); })(); /*********************************************************************** A JavaScript tokenizer / parser / beautifier / compressor. https://github.com/mishoo/UglifyJS2 -------------------------------- (C) --------------------------------- Author: Mihai Bazon <mihai.bazon@gmail.com> http://mihai.bazon.net/blog Distributed under the BSD license: Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************/ "use strict"; function SymbolDef(scope, index, orig) { this.name = orig.name; this.orig = [ orig ]; this.scope = scope; this.references = []; this.global = false; this.mangled_name = null; this.undeclared = false; this.constant = false; this.index = index; }; SymbolDef.prototype = { unmangleable: function(options) { if (!options) options = {}; return (this.global && !options.toplevel) || this.undeclared || (!options.eval && (this.scope.uses_eval || this.scope.uses_with)) || (options.keep_fnames && (this.orig[0] instanceof AST_SymbolLambda || this.orig[0] instanceof AST_SymbolDefun)); }, mangle: function(options) { var cache = options.cache && options.cache.props; if (this.global && cache && cache.has(this.name)) { this.mangled_name = cache.get(this.name); } else if (!this.mangled_name && !this.unmangleable(options)) { var s = this.scope; if (!options.screw_ie8 && this.orig[0] instanceof AST_SymbolLambda) s = s.parent_scope; this.mangled_name = s.next_mangled(options, this); if (this.global && cache) { cache.set(this.name, this.mangled_name); } } } }; AST_Toplevel.DEFMETHOD("figure_out_scope", function(options){ options = defaults(options, { screw_ie8: false, cache: null }); // pass 1: setup scope chaining and handle definitions var self = this; var scope = self.parent_scope = null; var labels = new Dictionary(); var defun = null; var nesting = 0; var tw = new TreeWalker(function(node, descend){ if (options.screw_ie8 && node instanceof AST_Catch) { var save_scope = scope; scope = new AST_Scope(node); scope.init_scope_vars(nesting); scope.parent_scope = save_scope; descend(); scope = save_scope; return true; } if (node instanceof AST_Scope) { node.init_scope_vars(nesting); var save_scope = node.parent_scope = scope; var save_defun = defun; var save_labels = labels; defun = scope = node; labels = new Dictionary(); ++nesting; descend(); --nesting; scope = save_scope; defun = save_defun; labels = save_labels; return true; // don't descend again in TreeWalker } if (node instanceof AST_LabeledStatement) { var l = node.label; if (labels.has(l.name)) { throw new Error(string_template("Label {name} defined twice", l)); } labels.set(l.name, l); descend(); labels.del(l.name); return true; // no descend again } if (node instanceof AST_With) { for (var s = scope; s; s = s.parent_scope) s.uses_with = true; return; } if (node instanceof AST_Symbol) { node.scope = scope; } if (node instanceof AST_Label) { node.thedef = node; node.references = []; } if (node instanceof AST_SymbolLambda) { defun.def_function(node); } else if (node instanceof AST_SymbolDefun) { // Careful here, the scope where this should be defined is // the parent scope. The reason is that we enter a new // scope when we encounter the AST_Defun node (which is // instanceof AST_Scope) but we get to the symbol a bit // later. (node.scope = defun.parent_scope).def_function(node); } else if (node instanceof AST_SymbolVar || node instanceof AST_SymbolConst) { var def = defun.def_variable(node); def.constant = node instanceof AST_SymbolConst; def.init = tw.parent().value; } else if (node instanceof AST_SymbolCatch) { (options.screw_ie8 ? scope : defun) .def_variable(node); } else if (node instanceof AST_LabelRef) { var sym = labels.get(node.name); if (!sym) throw new Error(string_template("Undefined label {name} [{line},{col}]", { name: node.name, line: node.start.line, col: node.start.col })); node.thedef = sym; } }); self.walk(tw); // pass 2: find back references and eval var func = null; var globals = self.globals = new Dictionary(); var tw = new TreeWalker(function(node, descend){ if (node instanceof AST_Lambda) { var prev_func = func; func = node; descend(); func = prev_func; return true; } if (node instanceof AST_LoopControl && node.label) { node.label.thedef.references.push(node); return true; } if (node instanceof AST_SymbolRef) { var name = node.name; var sym = node.scope.find_variable(name); if (!sym) { var g; if (globals.has(name)) { g = globals.get(name); } else { g = new SymbolDef(self, globals.size(), node); g.undeclared = true; g.global = true; globals.set(name, g); } node.thedef = g; if (name == "eval" && tw.parent() instanceof AST_Call) { for (var s = node.scope; s && !s.uses_eval; s = s.parent_scope) s.uses_eval = true; } if (func && name == "arguments") { func.uses_arguments = true; } } else { node.thedef = sym; } node.reference(); return true; } }); self.walk(tw); if (options.cache) { this.cname = options.cache.cname; } }); AST_Scope.DEFMETHOD("init_scope_vars", function(nesting){ this.variables = new Dictionary(); // map name to AST_SymbolVar (variables defined in this scope; includes functions) this.functions = new Dictionary(); // map name to AST_SymbolDefun (functions defined in this scope) this.uses_with = false; // will be set to true if this or some nested scope uses the `with` statement this.uses_eval = false; // will be set to true if this or nested scope uses the global `eval` this.parent_scope = null; // the parent scope this.enclosed = []; // a list of variables from this or outer scope(s) that are referenced from this or inner scopes this.cname = -1; // the current index for mangling functions/variables this.nesting = nesting; // the nesting level of this scope (0 means toplevel) }); AST_Lambda.DEFMETHOD("init_scope_vars", function(){ AST_Scope.prototype.init_scope_vars.apply(this, arguments); this.uses_arguments = false; }); AST_SymbolRef.DEFMETHOD("reference", function() { var def = this.definition(); def.references.push(this); var s = this.scope; while (s) { push_uniq(s.enclosed, def); if (s === def.scope) break; s = s.parent_scope; } this.frame = this.scope.nesting - def.scope.nesting; }); AST_Scope.DEFMETHOD("find_variable", function(name){ if (name instanceof AST_Symbol) name = name.name; return this.variables.get(name) || (this.parent_scope && this.parent_scope.find_variable(name)); }); AST_Scope.DEFMETHOD("def_function", function(symbol){ this.functions.set(symbol.name, this.def_variable(symbol)); }); AST_Scope.DEFMETHOD("def_variable", function(symbol){ var def; if (!this.variables.has(symbol.name)) { def = new SymbolDef(this, this.variables.size(), symbol); this.variables.set(symbol.name, def); def.global = !this.parent_scope; } else { def = this.variables.get(symbol.name); def.orig.push(symbol); } return symbol.thedef = def; }); AST_Scope.DEFMETHOD("next_mangled", function(options){ var ext = this.enclosed; out: while (true) { var m = base54(++this.cname); if (!is_identifier(m)) continue; // skip over "do" // https://github.com/mishoo/UglifyJS2/issues/242 -- do not // shadow a name excepted from mangling. if (options.except.indexOf(m) >= 0) continue; // we must ensure that the mangled name does not shadow a name // from some parent scope that is referenced in this or in // inner scopes. for (var i = ext.length; --i >= 0;) { var sym = ext[i]; var name = sym.mangled_name || (sym.unmangleable(options) && sym.name); if (m == name) continue out; } return m; } }); AST_Function.DEFMETHOD("next_mangled", function(options, def){ // #179, #326 // in Safari strict mode, something like (function x(x){...}) is a syntax error; // a function expression's argument cannot shadow the function expression's name var tricky_def = def.orig[0] instanceof AST_SymbolFunarg && this.name && this.name.definition(); while (true) { var name = AST_Lambda.prototype.next_mangled.call(this, options, def); if (!(tricky_def && tricky_def.mangled_name == name)) return name; } }); AST_Scope.DEFMETHOD("references", function(sym){ if (sym instanceof AST_Symbol) sym = sym.definition(); return this.enclosed.indexOf(sym) < 0 ? null : sym; }); AST_Symbol.DEFMETHOD("unmangleable", function(options){ return this.definition().unmangleable(options); }); // property accessors are not mangleable AST_SymbolAccessor.DEFMETHOD("unmangleable", function(){ return true; }); // labels are always mangleable AST_Label.DEFMETHOD("unmangleable", function(){ return false; }); AST_Symbol.DEFMETHOD("unreferenced", function(){ return this.definition().references.length == 0 && !(this.scope.uses_eval || this.scope.uses_with); }); AST_Symbol.DEFMETHOD("undeclared", function(){ return this.definition().undeclared; }); AST_LabelRef.DEFMETHOD("undeclared", function(){ return false; }); AST_Label.DEFMETHOD("undeclared", function(){ return false; }); AST_Symbol.DEFMETHOD("definition", function(){ return this.thedef; }); AST_Symbol.DEFMETHOD("global", function(){ return this.definition().global; }); AST_Toplevel.DEFMETHOD("_default_mangler_options", function(options){ return defaults(options, { except : [], eval : false, sort : false, toplevel : false, screw_ie8 : false, keep_fnames : false }); }); AST_Toplevel.DEFMETHOD("mangle_names", function(options){ options = this._default_mangler_options(options); // We only need to mangle declaration nodes. Special logic wired // into the code generator will display the mangled name if it's // present (and for AST_SymbolRef-s it'll use the mangled name of // the AST_SymbolDeclaration that it points to). var lname = -1; var to_mangle = []; if (options.cache) { this.globals.each(function(symbol){ if (options.except.indexOf(symbol.name) < 0) { to_mangle.push(symbol); } }); } var tw = new TreeWalker(function(node, descend){ if (node instanceof AST_LabeledStatement) { // lname is incremented when we get to the AST_Label var save_nesting = lname; descend(); lname = save_nesting; return true; // don't descend again in TreeWalker } if (node instanceof AST_Scope) { var p = tw.parent(), a = []; node.variables.each(function(symbol){ if (options.except.indexOf(symbol.name) < 0) { a.push(symbol); } }); if (options.sort) a.sort(function(a, b){ return b.references.length - a.references.length; }); to_mangle.push.apply(to_mangle, a); return; } if (node instanceof AST_Label) { var name; do name = base54(++lname); while (!is_identifier(name)); node.mangled_name = name; return true; } if (options.screw_ie8 && node instanceof AST_SymbolCatch) { to_mangle.push(node.definition()); return; } }); this.walk(tw); to_mangle.forEach(function(def){ def.mangle(options) }); if (options.cache) { options.cache.cname = this.cname; } }); AST_Toplevel.DEFMETHOD("compute_char_frequency", function(options){ options = this._default_mangler_options(options); var tw = new TreeWalker(function(node){ if (node instanceof AST_Constant) base54.consider(node.print_to_string()); else if (node instanceof AST_Return) base54.consider("return"); else if (node instanceof AST_Throw) base54.consider("throw"); else if (node instanceof AST_Continue) base54.consider("continue"); else if (node instanceof AST_Break) base54.consider("break"); else if (node instanceof AST_Debugger) base54.consider("debugger"); else if (node instanceof AST_Directive) base54.consider(node.value); else if (node instanceof AST_While) base54.consider("while"); else if (node instanceof AST_Do) base54.consider("do while"); else if (node instanceof AST_If) { base54.consider("if"); if (node.alternative) base54.consider("else"); } else if (node instanceof AST_Var) base54.consider("var"); else if (node instanceof AST_Const) base54.consider("const"); else if (node instanceof AST_Lambda) base54.consider("function"); else if (node instanceof AST_For) base54.consider("for"); else if (node instanceof AST_ForIn) base54.consider("for in"); else if (node instanceof AST_Switch) base54.consider("switch"); else if (node instanceof AST_Case) base54.consider("case"); else if (node instanceof AST_Default) base54.consider("default"); else if (node instanceof AST_With) base54.consider("with"); else if (node instanceof AST_ObjectSetter) base54.consider("set" + node.key); else if (node instanceof AST_ObjectGetter) base54.consider("get" + node.key); else if (node instanceof AST_ObjectKeyVal) base54.consider(node.key); else if (node instanceof AST_New) base54.consider("new"); else if (node instanceof AST_This) base54.consider("this"); else if (node instanceof AST_Try) base54.consider("try"); else if (node instanceof AST_Catch) base54.consider("catch"); else if (node instanceof AST_Finally) base54.consider("finally"); else if (node instanceof AST_Symbol && node.unmangleable(options)) base54.consider(node.name); else if (node instanceof AST_Unary || node instanceof AST_Binary) base54.consider(node.operator); else if (node instanceof AST_Dot) base54.consider(node.property); }); this.walk(tw); base54.sort(); }); var base54 = (function() { var string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789"; var chars, frequency; function reset() { frequency = Object.create(null); chars = string.split("").map(function(ch){ return ch.charCodeAt(0) }); chars.forEach(function(ch){ frequency[ch] = 0 }); } base54.consider = function(str){ for (var i = str.length; --i >= 0;) { var code = str.charCodeAt(i); if (code in frequency) ++frequency[code]; } }; base54.sort = function() { chars = mergeSort(chars, function(a, b){ if (is_digit(a) && !is_digit(b)) return 1; if (is_digit(b) && !is_digit(a)) return -1; return frequency[b] - frequency[a]; }); }; base54.reset = reset; reset(); base54.get = function(){ return chars }; base54.freq = function(){ return frequency }; function base54(num) { var ret = "", base = 54; num++; do { num--; ret += String.fromCharCode(chars[num % base]); num = Math.floor(num / base); base = 64; } while (num > 0); return ret; }; return base54; })(); AST_Toplevel.DEFMETHOD("scope_warnings", function(options){ options = defaults(options, { undeclared : false, // this makes a lot of noise unreferenced : true, assign_to_global : true, func_arguments : true, nested_defuns : true, eval : true }); var tw = new TreeWalker(function(node){ if (options.undeclared && node instanceof AST_SymbolRef && node.undeclared()) { // XXX: this also warns about JS standard names, // i.e. Object, Array, parseInt etc. Should add a list of // exceptions. AST_Node.warn("Undeclared symbol: {name} [{file}:{line},{col}]", { name: node.name, file: node.start.file, line: node.start.line, col: node.start.col }); } if (options.assign_to_global) { var sym = null; if (node instanceof AST_Assign && node.left instanceof AST_SymbolRef) sym = node.left; else if (node instanceof AST_ForIn && node.init instanceof AST_SymbolRef) sym = node.init; if (sym && (sym.undeclared() || (sym.global() && sym.scope !== sym.definition().scope))) { AST_Node.warn("{msg}: {name} [{file}:{line},{col}]", { msg: sym.undeclared() ? "Accidental global?" : "Assignment to global", name: sym.name, file: sym.start.file, line: sym.start.line, col: sym.start.col }); } } if (options.eval && node instanceof AST_SymbolRef && node.undeclared() && node.name == "eval") { AST_Node.warn("Eval is used [{file}:{line},{col}]", node.start); } if (options.unreferenced && (node instanceof AST_SymbolDeclaration || node instanceof AST_Label) && !(node instanceof AST_SymbolCatch) && node.unreferenced()) { AST_Node.warn("{type} {name} is declared but not referenced [{file}:{line},{col}]", { type: node instanceof AST_Label ? "Label" : "Symbol", name: node.name, file: node.start.file, line: node.start.line, col: node.start.col }); } if (options.func_arguments && node instanceof AST_Lambda && node.uses_arguments) { AST_Node.warn("arguments used in function {name} [{file}:{line},{col}]", { name: node.name ? node.name.name : "anonymous", file: node.start.file, line: node.start.line, col: node.start.col }); } if (options.nested_defuns && node instanceof AST_Defun && !(tw.parent() instanceof AST_Scope)) { AST_Node.warn("Function {name} declared in nested statement \"{type}\" [{file}:{line},{col}]", { name: node.name.name, type: tw.parent().TYPE, file: node.start.file, line: node.start.line, col: node.start.col }); } }); this.walk(tw); }); /*********************************************************************** A JavaScript tokenizer / parser / beautifier / compressor. https://github.com/mishoo/UglifyJS2 -------------------------------- (C) --------------------------------- Author: Mihai Bazon <mihai.bazon@gmail.com> http://mihai.bazon.net/blog Distributed under the BSD license: Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************/ "use strict"; function OutputStream(options) { options = defaults(options, { indent_start : 0, indent_level : 4, quote_keys : false, space_colon : true, ascii_only : false, unescape_regexps : false, inline_script : false, width : 80, max_line_len : 32000, beautify : false, source_map : null, bracketize : false, semicolons : true, comments : false, shebang : true, preserve_line : false, screw_ie8 : false, preamble : null, quote_style : 0 }, true); var indentation = 0; var current_col = 0; var current_line = 1; var current_pos = 0; var OUTPUT = ""; function to_ascii(str, identifier) { return str.replace(/[\u0080-\uffff]/g, function(ch) { var code = ch.charCodeAt(0).toString(16); if (code.length <= 2 && !identifier) { while (code.length < 2) code = "0" + code; return "\\x" + code; } else { while (code.length < 4) code = "0" + code; return "\\u" + code; } }); }; function make_string(str, quote) { var dq = 0, sq = 0; str = str.replace(/[\\\b\f\n\r\v\t\x22\x27\u2028\u2029\0\ufeff]/g, function(s){ switch (s) { case "\\": return "\\\\"; case "\b": return "\\b"; case "\f": return "\\f"; case "\n": return "\\n"; case "\r": return "\\r"; case "\x0B": return options.screw_ie8 ? "\\v" : "\\x0B"; case "\u2028": return "\\u2028"; case "\u2029": return "\\u2029"; case '"': ++dq; return '"'; case "'": ++sq; return "'"; case "\0": return "\\x00"; case "\ufeff": return "\\ufeff"; } return s; }); function quote_single() { return "'" + str.replace(/\x27/g, "\\'") + "'"; } function quote_double() { return '"' + str.replace(/\x22/g, '\\"') + '"'; } if (options.ascii_only) str = to_ascii(str); switch (options.quote_style) { case 1: return quote_single(); case 2: return quote_double(); case 3: return quote == "'" ? quote_single() : quote_double(); default: return dq > sq ? quote_single() : quote_double(); } }; function encode_string(str, quote) { var ret = make_string(str, quote); if (options.inline_script) { ret = ret.replace(/<\x2fscript([>\/\t\n\f\r ])/gi, "<\\/script$1"); ret = ret.replace(/\x3c!--/g, "\\x3c!--"); ret = ret.replace(/--\x3e/g, "--\\x3e"); } return ret; }; function make_name(name) { name = name.toString(); if (options.ascii_only) name = to_ascii(name, true); return name; }; function make_indent(back) { return repeat_string(" ", options.indent_start + indentation - back * options.indent_level); }; /* -----[ beautification/minification ]----- */ var might_need_space = false; var might_need_semicolon = false; var last = null; function last_char() { return last.charAt(last.length - 1); }; function maybe_newline() { if (options.max_line_len && current_col > options.max_line_len) print("\n"); }; var requireSemicolonChars = makePredicate("( [ + * / - , ."); function print(str) { str = String(str); var ch = str.charAt(0); if (might_need_semicolon) { might_need_semicolon = false; if ((!ch || ";}".indexOf(ch) < 0) && !/[;]$/.test(last)) { if (options.semicolons || requireSemicolonChars(ch)) { OUTPUT += ";"; current_col++; current_pos++; } else { OUTPUT += "\n"; current_pos++; current_line++; current_col = 0; if (/^\s+$/.test(str)) { // reset the semicolon flag, since we didn't print one // now and might still have to later might_need_semicolon = true; } } if (!options.beautify) might_need_space = false; } } if (!options.beautify && options.preserve_line && stack[stack.length - 1]) { var target_line = stack[stack.length - 1].start.line; while (current_line < target_line) { OUTPUT += "\n"; current_pos++; current_line++; current_col = 0; might_need_space = false; } } if (might_need_space) { var prev = last_char(); if ((is_identifier_char(prev) && (is_identifier_char(ch) || ch == "\\")) || (/^[\+\-\/]$/.test(ch) && ch == prev)) { OUTPUT += " "; current_col++; current_pos++; } might_need_space = false; } var a = str.split(/\r?\n/), n = a.length - 1; current_line += n; if (n == 0) { current_col += a[n].length; } else { current_col = a[n].length; } current_pos += str.length; last = str; OUTPUT += str; }; var space = options.beautify ? function() { print(" "); } : function() { might_need_space = true; }; var indent = options.beautify ? function(half) { if (options.beautify) { print(make_indent(half ? 0.5 : 0)); } } : noop; var with_indent = options.beautify ? function(col, cont) { if (col === true) col = next_indent(); var save_indentation = indentation; indentation = col; var ret = cont(); indentation = save_indentation; return ret; } : function(col, cont) { return cont() }; var newline = options.beautify ? function() { print("\n"); } : maybe_newline; var semicolon = options.beautify ? function() { print(";"); } : function() { might_need_semicolon = true; }; function force_semicolon() { might_need_semicolon = false; print(";"); }; function next_indent() { return indentation + options.indent_level; }; function with_block(cont) { var ret; print("{"); newline(); with_indent(next_indent(), function(){ ret = cont(); }); indent(); print("}"); return ret; }; function with_parens(cont) { print("("); //XXX: still nice to have that for argument lists //var ret = with_indent(current_col, cont); var ret = cont(); print(")"); return ret; }; function with_square(cont) { print("["); //var ret = with_indent(current_col, cont); var ret = cont(); print("]"); return ret; }; function comma() { print(","); space(); }; function colon() { print(":"); if (options.space_colon) space(); }; var add_mapping = options.source_map ? function(token, name) { try { if (token) options.source_map.add( token.file || "?", current_line, current_col, token.line, token.col, (!name && token.type == "name") ? token.value : name ); } catch(ex) { AST_Node.warn("Couldn't figure out mapping for {file}:{line},{col} → {cline},{ccol} [{name}]", { file: token.file, line: token.line, col: token.col, cline: current_line, ccol: current_col, name: name || "" }) } } : noop; function get() { return OUTPUT; }; if (options.preamble) { print(options.preamble.replace(/\r\n?|[\n\u2028\u2029]|\s*$/g, "\n")); } var stack = []; return { get : get, toString : get, indent : indent, indentation : function() { return indentation }, current_width : function() { return current_col - indentation }, should_break : function() { return options.width && this.current_width() >= options.width }, newline : newline, print : print, space : space, comma : comma, colon : colon, last : function() { return last }, semicolon : semicolon, force_semicolon : force_semicolon, to_ascii : to_ascii, print_name : function(name) { print(make_name(name)) }, print_string : function(str, quote) { print(encode_string(str, quote)) }, next_indent : next_indent, with_indent : with_indent, with_block : with_block, with_parens : with_parens, with_square : with_square, add_mapping : add_mapping, option : function(opt) { return options[opt] }, line : function() { return current_line }, col : function() { return current_col }, pos : function() { return current_pos }, push_node : function(node) { stack.push(node) }, pop_node : function() { return stack.pop() }, stack : function() { return stack }, parent : function(n) { return stack[stack.length - 2 - (n || 0)]; } }; }; /* -----[ code generators ]----- */ (function(){ /* -----[ utils ]----- */ function DEFPRINT(nodetype, generator) { nodetype.DEFMETHOD("_codegen", generator); }; var use_asm = false; AST_Node.DEFMETHOD("print", function(stream, force_parens){ var self = this, generator = self._codegen, prev_use_asm = use_asm; if (self instanceof AST_Directive && self.value == "use asm") { use_asm = true; } function doit() { self.add_comments(stream); self.add_source_map(stream); generator(self, stream); } stream.push_node(self); if (force_parens || self.needs_parens(stream)) { stream.with_parens(doit); } else { doit(); } stream.pop_node(); if (self instanceof AST_Lambda) { use_asm = prev_use_asm; } }); AST_Node.DEFMETHOD("print_to_string", function(options){ var s = OutputStream(options); this.print(s); return s.get(); }); /* -----[ comments ]----- */ AST_Node.DEFMETHOD("add_comments", function(output){ var c = output.option("comments"), self = this; var start = self.start; if (start && !start._comments_dumped) { start._comments_dumped = true; var comments = start.comments_before || []; // XXX: ugly fix for https://github.com/mishoo/UglifyJS2/issues/112 // and https://github.com/mishoo/UglifyJS2/issues/372 if (self instanceof AST_Exit && self.value) { self.value.walk(new TreeWalker(function(node){ if (node.start && node.start.comments_before) { comments = comments.concat(node.start.comments_before); node.start.comments_before = []; } if (node instanceof AST_Function || node instanceof AST_Array || node instanceof AST_Object) { return true; // don't go inside. } })); } if (!c) { comments = comments.filter(function(comment) { return comment.type == "comment5"; }); } else if (c.test) { comments = comments.filter(function(comment){ return c.test(comment.value) || comment.type == "comment5"; }); } else if (typeof c == "function") { comments = comments.filter(function(comment){ return c(self, comment) || comment.type == "comment5"; }); } // Keep single line comments after nlb, after nlb if (!output.option("beautify") && comments.length > 0 && /comment[134]/.test(comments[0].type) && output.col() !== 0 && comments[0].nlb) { output.print("\n"); } comments.forEach(function(c){ if (/comment[134]/.test(c.type)) { output.print("//" + c.value + "\n"); output.indent(); } else if (c.type == "comment2") { output.print("/*" + c.value + "*/"); if (start.nlb) { output.print("\n"); output.indent(); } else { output.space(); } } else if (output.pos() === 0 && c.type == "comment5" && output.option("shebang")) { output.print("#!" + c.value + "\n"); output.indent(); } }); } }); /* -----[ PARENTHESES ]----- */ function PARENS(nodetype, func) { if (Array.isArray(nodetype)) { nodetype.forEach(function(nodetype){ PARENS(nodetype, func); }); } else { nodetype.DEFMETHOD("needs_parens", func); } }; PARENS(AST_Node, function(){ return false; }); // a function expression needs parens around it when it's provably // the first token to appear in a statement. PARENS(AST_Function, function(output){ return first_in_statement(output); }); // same goes for an object literal, because otherwise it would be // interpreted as a block of code. PARENS(AST_Object, function(output){ return first_in_statement(output); }); PARENS([ AST_Unary, AST_Undefined ], function(output){ var p = output.parent(); return p instanceof AST_PropAccess && p.expression === this; }); PARENS(AST_Seq, function(output){ var p = output.parent(); return p instanceof AST_Call // (foo, bar)() or foo(1, (2, 3), 4) || p instanceof AST_Unary // !(foo, bar, baz) || p instanceof AST_Binary // 1 + (2, 3) + 4 ==> 8 || p instanceof AST_VarDef // var a = (1, 2), b = a + a; ==> b == 4 || p instanceof AST_PropAccess // (1, {foo:2}).foo or (1, {foo:2})["foo"] ==> 2 || p instanceof AST_Array // [ 1, (2, 3), 4 ] ==> [ 1, 3, 4 ] || p instanceof AST_ObjectProperty // { foo: (1, 2) }.foo ==> 2 || p instanceof AST_Conditional /* (false, true) ? (a = 10, b = 20) : (c = 30) * ==> 20 (side effect, set a := 10 and b := 20) */ ; }); PARENS(AST_Binary, function(output){ var p = output.parent(); // (foo && bar)() if (p instanceof AST_Call && p.expression === this) return true; // typeof (foo && bar) if (p instanceof AST_Unary) return true; // (foo && bar)["prop"], (foo && bar).prop if (p instanceof AST_PropAccess && p.expression === this) return true; // this deals with precedence: 3 * (2 + 1) if (p instanceof AST_Binary) { var po = p.operator, pp = PRECEDENCE[po]; var so = this.operator, sp = PRECEDENCE[so]; if (pp > sp || (pp == sp && this === p.right)) { return true; } } }); PARENS(AST_PropAccess, function(output){ var p = output.parent(); if (p instanceof AST_New && p.expression === this) { // i.e. new (foo.bar().baz) // // if there's one call into this subtree, then we need // parens around it too, otherwise the call will be // interpreted as passing the arguments to the upper New // expression. try { this.walk(new TreeWalker(function(node){ if (node instanceof AST_Call) throw p; })); } catch(ex) { if (ex !== p) throw ex; return true; } } }); PARENS(AST_Call, function(output){ var p = output.parent(), p1; if (p instanceof AST_New && p.expression === this) return true; // workaround for Safari bug. // https://bugs.webkit.org/show_bug.cgi?id=123506 return this.expression instanceof AST_Function && p instanceof AST_PropAccess && p.expression === this && (p1 = output.parent(1)) instanceof AST_Assign && p1.left === p; }); PARENS(AST_New, function(output){ var p = output.parent(); if (no_constructor_parens(this, output) && (p instanceof AST_PropAccess // (new Date).getTime(), (new Date)["getTime"]() || p instanceof AST_Call && p.expression === this)) // (new foo)(bar) return true; }); PARENS(AST_Number, function(output){ var p = output.parent(); if (this.getValue() < 0 && p instanceof AST_PropAccess && p.expression === this) return true; }); PARENS([ AST_Assign, AST_Conditional ], function (output){ var p = output.parent(); // !(a = false) → true if (p instanceof AST_Unary) return true; // 1 + (a = 2) + 3 → 6, side effect setting a = 2 if (p instanceof AST_Binary && !(p instanceof AST_Assign)) return true; // (a = func)() —or— new (a = Object)() if (p instanceof AST_Call && p.expression === this) return true; // (a = foo) ? bar : baz if (p instanceof AST_Conditional && p.condition === this) return true; // (a = foo)["prop"] —or— (a = foo).prop if (p instanceof AST_PropAccess && p.expression === this) return true; }); /* -----[ PRINTERS ]----- */ DEFPRINT(AST_Directive, function(self, output){ output.print_string(self.value, self.quote); output.semicolon(); }); DEFPRINT(AST_Debugger, function(self, output){ output.print("debugger"); output.semicolon(); }); /* -----[ statements ]----- */ function display_body(body, is_toplevel, output) { var last = body.length - 1; body.forEach(function(stmt, i){ if (!(stmt instanceof AST_EmptyStatement)) { output.indent(); stmt.print(output); if (!(i == last && is_toplevel)) { output.newline(); if (is_toplevel) output.newline(); } } }); }; AST_StatementWithBody.DEFMETHOD("_do_print_body", function(output){ force_statement(this.body, output); }); DEFPRINT(AST_Statement, function(self, output){ self.body.print(output); output.semicolon(); }); DEFPRINT(AST_Toplevel, function(self, output){ display_body(self.body, true, output); output.print(""); }); DEFPRINT(AST_LabeledStatement, function(self, output){ self.label.print(output); output.colon(); self.body.print(output); }); DEFPRINT(AST_SimpleStatement, function(self, output){ self.body.print(output); output.semicolon(); }); function print_bracketed(body, output) { if (body.length > 0) output.with_block(function(){ display_body(body, false, output); }); else output.print("{}"); }; DEFPRINT(AST_BlockStatement, function(self, output){ print_bracketed(self.body, output); }); DEFPRINT(AST_EmptyStatement, function(self, output){ output.semicolon(); }); DEFPRINT(AST_Do, function(self, output){ output.print("do"); output.space(); self._do_print_body(output); output.space(); output.print("while"); output.space(); output.with_parens(function(){ self.condition.print(output); }); output.semicolon(); }); DEFPRINT(AST_While, function(self, output){ output.print("while"); output.space(); output.with_parens(function(){ self.condition.print(output); }); output.space(); self._do_print_body(output); }); DEFPRINT(AST_For, function(self, output){ output.print("for"); output.space(); output.with_parens(function(){ if (self.init && !(self.init instanceof AST_EmptyStatement)) { if (self.init instanceof AST_Definitions) { self.init.print(output); } else { parenthesize_for_noin(self.init, output, true); } output.print(";"); output.space(); } else { output.print(";"); } if (self.condition) { self.condition.print(output); output.print(";"); output.space(); } else { output.print(";"); } if (self.step) { self.step.print(output); } }); output.space(); self._do_print_body(output); }); DEFPRINT(AST_ForIn, function(self, output){ output.print("for"); output.space(); output.with_parens(function(){ self.init.print(output); output.space(); output.print("in"); output.space(); self.object.print(output); }); output.space(); self._do_print_body(output); }); DEFPRINT(AST_With, function(self, output){ output.print("with"); output.space(); output.with_parens(function(){ self.expression.print(output); }); output.space(); self._do_print_body(output); }); /* -----[ functions ]----- */ AST_Lambda.DEFMETHOD("_do_print", function(output, nokeyword){ var self = this; if (!nokeyword) { output.print("function"); } if (self.name) { output.space(); self.name.print(output); } output.with_parens(function(){ self.argnames.forEach(function(arg, i){ if (i) output.comma(); arg.print(output); }); }); output.space(); print_bracketed(self.body, output); }); DEFPRINT(AST_Lambda, function(self, output){ self._do_print(output); }); /* -----[ exits ]----- */ AST_Exit.DEFMETHOD("_do_print", function(output, kind){ output.print(kind); if (this.value) { output.space(); this.value.print(output); } output.semicolon(); }); DEFPRINT(AST_Return, function(self, output){ self._do_print(output, "return"); }); DEFPRINT(AST_Throw, function(self, output){ self._do_print(output, "throw"); }); /* -----[ loop control ]----- */ AST_LoopControl.DEFMETHOD("_do_print", function(output, kind){ output.print(kind); if (this.label) { output.space(); this.label.print(output); } output.semicolon(); }); DEFPRINT(AST_Break, function(self, output){ self._do_print(output, "break"); }); DEFPRINT(AST_Continue, function(self, output){ self._do_print(output, "continue"); }); /* -----[ if ]----- */ function make_then(self, output) { if (output.option("bracketize")) { make_block(self.body, output); return; } // The squeezer replaces "block"-s that contain only a single // statement with the statement itself; technically, the AST // is correct, but this can create problems when we output an // IF having an ELSE clause where the THEN clause ends in an // IF *without* an ELSE block (then the outer ELSE would refer // to the inner IF). This function checks for this case and // adds the block brackets if needed. if (!self.body) return output.force_semicolon(); if (self.body instanceof AST_Do && !output.option("screw_ie8")) { // https://github.com/mishoo/UglifyJS/issues/#issue/57 IE // croaks with "syntax error" on code like this: if (foo) // do ... while(cond); else ... we need block brackets // around do/while make_block(self.body, output); return; } var b = self.body; while (true) { if (b instanceof AST_If) { if (!b.alternative) { make_block(self.body, output); return; } b = b.alternative; } else if (b instanceof AST_StatementWithBody) { b = b.body; } else break; } force_statement(self.body, output); }; DEFPRINT(AST_If, function(self, output){ output.print("if"); output.space(); output.with_parens(function(){ self.condition.print(output); }); output.space(); if (self.alternative) { make_then(self, output); output.space(); output.print("else"); output.space(); force_statement(self.alternative, output); } else { self._do_print_body(output); } }); /* -----[ switch ]----- */ DEFPRINT(AST_Switch, function(self, output){ output.print("switch"); output.space(); output.with_parens(function(){ self.expression.print(output); }); output.space(); if (self.body.length > 0) output.with_block(function(){ self.body.forEach(function(stmt, i){ if (i) output.newline(); output.indent(true); stmt.print(output); }); }); else output.print("{}"); }); AST_SwitchBranch.DEFMETHOD("_do_print_body", function(output){ if (this.body.length > 0) { output.newline(); this.body.forEach(function(stmt){ output.indent(); stmt.print(output); output.newline(); }); } }); DEFPRINT(AST_Default, function(self, output){ output.print("default:"); self._do_print_body(output); }); DEFPRINT(AST_Case, function(self, output){ output.print("case"); output.space(); self.expression.print(output); output.print(":"); self._do_print_body(output); }); /* -----[ exceptions ]----- */ DEFPRINT(AST_Try, function(self, output){ output.print("try"); output.space(); print_bracketed(self.body, output); if (self.bcatch) { output.space(); self.bcatch.print(output); } if (self.bfinally) { output.space(); self.bfinally.print(output); } }); DEFPRINT(AST_Catch, function(self, output){ output.print("catch"); output.space(); output.with_parens(function(){ self.argname.print(output); }); output.space(); print_bracketed(self.body, output); }); DEFPRINT(AST_Finally, function(self, output){ output.print("finally"); output.space(); print_bracketed(self.body, output); }); /* -----[ var/const ]----- */ AST_Definitions.DEFMETHOD("_do_print", function(output, kind){ output.print(kind); output.space(); this.definitions.forEach(function(def, i){ if (i) output.comma(); def.print(output); }); var p = output.parent(); var in_for = p instanceof AST_For || p instanceof AST_ForIn; var avoid_semicolon = in_for && p.init === this; if (!avoid_semicolon) output.semicolon(); }); DEFPRINT(AST_Var, function(self, output){ self._do_print(output, "var"); }); DEFPRINT(AST_Const, function(self, output){ self._do_print(output, "const"); }); function parenthesize_for_noin(node, output, noin) { if (!noin) node.print(output); else try { // need to take some precautions here: // https://github.com/mishoo/UglifyJS2/issues/60 node.walk(new TreeWalker(function(node){ if (node instanceof AST_Binary && node.operator == "in") throw output; })); node.print(output); } catch(ex) { if (ex !== output) throw ex; node.print(output, true); } }; DEFPRINT(AST_VarDef, function(self, output){ self.name.print(output); if (self.value) { output.space(); output.print("="); output.space(); var p = output.parent(1); var noin = p instanceof AST_For || p instanceof AST_ForIn; parenthesize_for_noin(self.value, output, noin); } }); /* -----[ other expressions ]----- */ DEFPRINT(AST_Call, function(self, output){ self.expression.print(output); if (self instanceof AST_New && no_constructor_parens(self, output)) return; output.with_parens(function(){ self.args.forEach(function(expr, i){ if (i) output.comma(); expr.print(output); }); }); }); DEFPRINT(AST_New, function(self, output){ output.print("new"); output.space(); AST_Call.prototype._codegen(self, output); }); AST_Seq.DEFMETHOD("_do_print", function(output){ this.car.print(output); if (this.cdr) { output.comma(); if (output.should_break()) { output.newline(); output.indent(); } this.cdr.print(output); } }); DEFPRINT(AST_Seq, function(self, output){ self._do_print(output); // var p = output.parent(); // if (p instanceof AST_Statement) { // output.with_indent(output.next_indent(), function(){ // self._do_print(output); // }); // } else { // self._do_print(output); // } }); DEFPRINT(AST_Dot, function(self, output){ var expr = self.expression; expr.print(output); if (expr instanceof AST_Number && expr.getValue() >= 0) { if (!/[xa-f.]/i.test(output.last())) { output.print("."); } } output.print("."); // the name after dot would be mapped about here. output.add_mapping(self.end); output.print_name(self.property); }); DEFPRINT(AST_Sub, function(self, output){ self.expression.print(output); output.print("["); self.property.print(output); output.print("]"); }); DEFPRINT(AST_UnaryPrefix, function(self, output){ var op = self.operator; output.print(op); if (/^[a-z]/i.test(op) || (/[+-]$/.test(op) && self.expression instanceof AST_UnaryPrefix && /^[+-]/.test(self.expression.operator))) { output.space(); } self.expression.print(output); }); DEFPRINT(AST_UnaryPostfix, function(self, output){ self.expression.print(output); output.print(self.operator); }); DEFPRINT(AST_Binary, function(self, output){ var op = self.operator; self.left.print(output); if (op[0] == ">" /* ">>" ">>>" ">" ">=" */ && self.left instanceof AST_UnaryPostfix && self.left.operator == "--") { // space is mandatory to avoid outputting --> output.print(" "); } else { // the space is optional depending on "beautify" output.space(); } output.print(op); if ((op == "<" || op == "<<") && self.right instanceof AST_UnaryPrefix && self.right.operator == "!" && self.right.expression instanceof AST_UnaryPrefix && self.right.expression.operator == "--") { // space is mandatory to avoid outputting <!-- output.print(" "); } else { // the space is optional depending on "beautify" output.space(); } self.right.print(output); }); DEFPRINT(AST_Conditional, function(self, output){ self.condition.print(output); output.space(); output.print("?"); output.space(); self.consequent.print(output); output.space(); output.colon(); self.alternative.print(output); }); /* -----[ literals ]----- */ DEFPRINT(AST_Array, function(self, output){ output.with_square(function(){ var a = self.elements, len = a.length; if (len > 0) output.space(); a.forEach(function(exp, i){ if (i) output.comma(); exp.print(output); // If the final element is a hole, we need to make sure it // doesn't look like a trailing comma, by inserting an actual // trailing comma. if (i === len - 1 && exp instanceof AST_Hole) output.comma(); }); if (len > 0) output.space(); }); }); DEFPRINT(AST_Object, function(self, output){ if (self.properties.length > 0) output.with_block(function(){ self.properties.forEach(function(prop, i){ if (i) { output.print(","); output.newline(); } output.indent(); prop.print(output); }); output.newline(); }); else output.print("{}"); }); DEFPRINT(AST_ObjectKeyVal, function(self, output){ var key = self.key; var quote = self.quote; if (output.option("quote_keys")) { output.print_string(key + ""); } else if ((typeof key == "number" || !output.option("beautify") && +key + "" == key) && parseFloat(key) >= 0) { output.print(make_num(key)); } else if (RESERVED_WORDS(key) ? output.option("screw_ie8") : is_identifier_string(key)) { output.print_name(key); } else { output.print_string(key, quote); } output.colon(); self.value.print(output); }); DEFPRINT(AST_ObjectSetter, function(self, output){ output.print("set"); output.space(); self.key.print(output); self.value._do_print(output, true); }); DEFPRINT(AST_ObjectGetter, function(self, output){ output.print("get"); output.space(); self.key.print(output); self.value._do_print(output, true); }); DEFPRINT(AST_Symbol, function(self, output){ var def = self.definition(); output.print_name(def ? def.mangled_name || def.name : self.name); }); DEFPRINT(AST_Undefined, function(self, output){ output.print("void 0"); }); DEFPRINT(AST_Hole, noop); DEFPRINT(AST_Infinity, function(self, output){ output.print("Infinity"); }); DEFPRINT(AST_NaN, function(self, output){ output.print("NaN"); }); DEFPRINT(AST_This, function(self, output){ output.print("this"); }); DEFPRINT(AST_Constant, function(self, output){ output.print(self.getValue()); }); DEFPRINT(AST_String, function(self, output){ output.print_string(self.getValue(), self.quote); }); DEFPRINT(AST_Number, function(self, output){ if (use_asm && self.start.raw != null) { output.print(self.start.raw); } else { output.print(make_num(self.getValue())); } }); function regexp_safe_literal(code) { return [ 0x5c , // \ 0x2f , // / 0x2e , // . 0x2b , // + 0x2a , // * 0x3f , // ? 0x28 , // ( 0x29 , // ) 0x5b , // [ 0x5d , // ] 0x7b , // { 0x7d , // } 0x24 , // $ 0x5e , // ^ 0x3a , // : 0x7c , // | 0x21 , // ! 0x0a , // \n 0x0d , // \r 0x00 , // \0 0xfeff , // Unicode BOM 0x2028 , // unicode "line separator" 0x2029 , // unicode "paragraph separator" ].indexOf(code) < 0; }; DEFPRINT(AST_RegExp, function(self, output){ var str = self.getValue().toString(); if (output.option("ascii_only")) { str = output.to_ascii(str); } else if (output.option("unescape_regexps")) { str = str.split("\\\\").map(function(str){ return str.replace(/\\u[0-9a-fA-F]{4}|\\x[0-9a-fA-F]{2}/g, function(s){ var code = parseInt(s.substr(2), 16); return regexp_safe_literal(code) ? String.fromCharCode(code) : s; }); }).join("\\\\"); } output.print(str); var p = output.parent(); if (p instanceof AST_Binary && /^in/.test(p.operator) && p.left === self) output.print(" "); }); function force_statement(stat, output) { if (output.option("bracketize")) { if (!stat || stat instanceof AST_EmptyStatement) output.print("{}"); else if (stat instanceof AST_BlockStatement) stat.print(output); else output.with_block(function(){ output.indent(); stat.print(output); output.newline(); }); } else { if (!stat || stat instanceof AST_EmptyStatement) output.force_semicolon(); else stat.print(output); } }; // return true if the node at the top of the stack (that means the // innermost node in the current output) is lexically the first in // a statement. function first_in_statement(output) { var a = output.stack(), i = a.length, node = a[--i], p = a[--i]; while (i > 0) { if (p instanceof AST_Statement && p.body === node) return true; if ((p instanceof AST_Seq && p.car === node ) || (p instanceof AST_Call && p.expression === node && !(p instanceof AST_New) ) || (p instanceof AST_Dot && p.expression === node ) || (p instanceof AST_Sub && p.expression === node ) || (p instanceof AST_Conditional && p.condition === node ) || (p instanceof AST_Binary && p.left === node ) || (p instanceof AST_UnaryPostfix && p.expression === node )) { node = p; p = a[--i]; } else { return false; } } }; // self should be AST_New. decide if we want to show parens or not. function no_constructor_parens(self, output) { return self.args.length == 0 && !output.option("beautify"); }; function best_of(a) { var best = a[0], len = best.length; for (var i = 1; i < a.length; ++i) { if (a[i].length < len) { best = a[i]; len = best.length; } } return best; }; function make_num(num) { var str = num.toString(10), a = [ str.replace(/^0\./, ".").replace('e+', 'e') ], m; if (Math.floor(num) === num) { if (num >= 0) { a.push("0x" + num.toString(16).toLowerCase(), // probably pointless "0" + num.toString(8)); // same. } else { a.push("-0x" + (-num).toString(16).toLowerCase(), // probably pointless "-0" + (-num).toString(8)); // same. } if ((m = /^(.*?)(0+)$/.exec(num))) { a.push(m[1] + "e" + m[2].length); } } else if ((m = /^0?\.(0+)(.*)$/.exec(num))) { a.push(m[2] + "e-" + (m[1].length + m[2].length), str.substr(str.indexOf("."))); } return best_of(a); }; function make_block(stmt, output) { if (stmt instanceof AST_BlockStatement) { stmt.print(output); return; } output.with_block(function(){ output.indent(); stmt.print(output); output.newline(); }); }; /* -----[ source map generators ]----- */ function DEFMAP(nodetype, generator) { nodetype.DEFMETHOD("add_source_map", function(stream){ generator(this, stream); }); }; // We could easily add info for ALL nodes, but it seems to me that // would be quite wasteful, hence this noop in the base class. DEFMAP(AST_Node, noop); function basic_sourcemap_gen(self, output) { output.add_mapping(self.start); }; // XXX: I'm not exactly sure if we need it for all of these nodes, // or if we should add even more. DEFMAP(AST_Directive, basic_sourcemap_gen); DEFMAP(AST_Debugger, basic_sourcemap_gen); DEFMAP(AST_Symbol, basic_sourcemap_gen); DEFMAP(AST_Jump, basic_sourcemap_gen); DEFMAP(AST_StatementWithBody, basic_sourcemap_gen); DEFMAP(AST_LabeledStatement, noop); // since the label symbol will mark it DEFMAP(AST_Lambda, basic_sourcemap_gen); DEFMAP(AST_Switch, basic_sourcemap_gen); DEFMAP(AST_SwitchBranch, basic_sourcemap_gen); DEFMAP(AST_BlockStatement, basic_sourcemap_gen); DEFMAP(AST_Toplevel, noop); DEFMAP(AST_New, basic_sourcemap_gen); DEFMAP(AST_Try, basic_sourcemap_gen); DEFMAP(AST_Catch, basic_sourcemap_gen); DEFMAP(AST_Finally, basic_sourcemap_gen); DEFMAP(AST_Definitions, basic_sourcemap_gen); DEFMAP(AST_Constant, basic_sourcemap_gen); DEFMAP(AST_ObjectSetter, function(self, output){ output.add_mapping(self.start, self.key.name); }); DEFMAP(AST_ObjectGetter, function(self, output){ output.add_mapping(self.start, self.key.name); }); DEFMAP(AST_ObjectProperty, function(self, output){ output.add_mapping(self.start, self.key); }); })(); /*********************************************************************** A JavaScript tokenizer / parser / beautifier / compressor. https://github.com/mishoo/UglifyJS2 -------------------------------- (C) --------------------------------- Author: Mihai Bazon <mihai.bazon@gmail.com> http://mihai.bazon.net/blog Distributed under the BSD license: Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************/ "use strict"; function Compressor(options, false_by_default) { if (!(this instanceof Compressor)) return new Compressor(options, false_by_default); TreeTransformer.call(this, this.before, this.after); this.options = defaults(options, { sequences : !false_by_default, properties : !false_by_default, dead_code : !false_by_default, drop_debugger : !false_by_default, unsafe : false, unsafe_comps : false, conditionals : !false_by_default, comparisons : !false_by_default, evaluate : !false_by_default, booleans : !false_by_default, loops : !false_by_default, unused : !false_by_default, hoist_funs : !false_by_default, keep_fargs : true, keep_fnames : false, hoist_vars : false, if_return : !false_by_default, join_vars : !false_by_default, cascade : !false_by_default, side_effects : !false_by_default, pure_getters : false, pure_funcs : null, negate_iife : !false_by_default, screw_ie8 : false, drop_console : false, angular : false, warnings : true, global_defs : {} }, true); }; Compressor.prototype = new TreeTransformer; merge(Compressor.prototype, { option: function(key) { return this.options[key] }, warn: function() { if (this.options.warnings) AST_Node.warn.apply(AST_Node, arguments); }, before: function(node, descend, in_list) { if (node._squeezed) return node; var was_scope = false; if (node instanceof AST_Scope) { node = node.hoist_declarations(this); was_scope = true; } descend(node, this); node = node.optimize(this); if (was_scope && node instanceof AST_Scope) { node.drop_unused(this); descend(node, this); } node._squeezed = true; return node; } }); (function(){ function OPT(node, optimizer) { node.DEFMETHOD("optimize", function(compressor){ var self = this; if (self._optimized) return self; if (compressor.has_directive("use asm")) return self; var opt = optimizer(self, compressor); opt._optimized = true; if (opt === self) return opt; return opt.transform(compressor); }); }; OPT(AST_Node, function(self, compressor){ return self; }); AST_Node.DEFMETHOD("equivalent_to", function(node){ // XXX: this is a rather expensive way to test two node's equivalence: return this.print_to_string() == node.print_to_string(); }); function make_node(ctor, orig, props) { if (!props) props = {}; if (orig) { if (!props.start) props.start = orig.start; if (!props.end) props.end = orig.end; } return new ctor(props); }; function make_node_from_constant(compressor, val, orig) { // XXX: WIP. // if (val instanceof AST_Node) return val.transform(new TreeTransformer(null, function(node){ // if (node instanceof AST_SymbolRef) { // var scope = compressor.find_parent(AST_Scope); // var def = scope.find_variable(node); // node.thedef = def; // return node; // } // })).transform(compressor); if (val instanceof AST_Node) return val.transform(compressor); switch (typeof val) { case "string": return make_node(AST_String, orig, { value: val }).optimize(compressor); case "number": return make_node(isNaN(val) ? AST_NaN : AST_Number, orig, { value: val }).optimize(compressor); case "boolean": return make_node(val ? AST_True : AST_False, orig).optimize(compressor); case "undefined": return make_node(AST_Undefined, orig).optimize(compressor); default: if (val === null) { return make_node(AST_Null, orig, { value: null }).optimize(compressor); } if (val instanceof RegExp) { return make_node(AST_RegExp, orig, { value: val }).optimize(compressor); } throw new Error(string_template("Can't handle constant of type: {type}", { type: typeof val })); } }; function as_statement_array(thing) { if (thing === null) return []; if (thing instanceof AST_BlockStatement) return thing.body; if (thing instanceof AST_EmptyStatement) return []; if (thing instanceof AST_Statement) return [ thing ]; throw new Error("Can't convert thing to statement array"); }; function is_empty(thing) { if (thing === null) return true; if (thing instanceof AST_EmptyStatement) return true; if (thing instanceof AST_BlockStatement) return thing.body.length == 0; return false; }; function loop_body(x) { if (x instanceof AST_Switch) return x; if (x instanceof AST_For || x instanceof AST_ForIn || x instanceof AST_DWLoop) { return (x.body instanceof AST_BlockStatement ? x.body : x); } return x; }; function tighten_body(statements, compressor) { var CHANGED, max_iter = 10; do { CHANGED = false; if (compressor.option("angular")) { statements = process_for_angular(statements); } statements = eliminate_spurious_blocks(statements); if (compressor.option("dead_code")) { statements = eliminate_dead_code(statements, compressor); } if (compressor.option("if_return")) { statements = handle_if_return(statements, compressor); } if (compressor.option("sequences")) { statements = sequencesize(statements, compressor); } if (compressor.option("join_vars")) { statements = join_consecutive_vars(statements, compressor); } } while (CHANGED && max_iter-- > 0); if (compressor.option("negate_iife")) { negate_iifes(statements, compressor); } return statements; function process_for_angular(statements) { function has_inject(comment) { return /@ngInject/.test(comment.value); } function make_arguments_names_list(func) { return func.argnames.map(function(sym){ return make_node(AST_String, sym, { value: sym.name }); }); } function make_array(orig, elements) { return make_node(AST_Array, orig, { elements: elements }); } function make_injector(func, name) { return make_node(AST_SimpleStatement, func, { body: make_node(AST_Assign, func, { operator: "=", left: make_node(AST_Dot, name, { expression: make_node(AST_SymbolRef, name, name), property: "$inject" }), right: make_array(func, make_arguments_names_list(func)) }) }); } function check_expression(body) { if (body && body.args) { // if this is a function call check all of arguments passed body.args.forEach(function(argument, index, array) { var comments = argument.start.comments_before; // if the argument is function preceded by @ngInject if (argument instanceof AST_Lambda && comments.length && has_inject(comments[0])) { // replace the function with an array of names of its parameters and function at the end array[index] = make_array(argument, make_arguments_names_list(argument).concat(argument)); } }); // if this is chained call check previous one recursively if (body.expression && body.expression.expression) { check_expression(body.expression.expression); } } } return statements.reduce(function(a, stat){ a.push(stat); if (stat.body && stat.body.args) { check_expression(stat.body); } else { var token = stat.start; var comments = token.comments_before; if (comments && comments.length > 0) { var last = comments.pop(); if (has_inject(last)) { // case 1: defun if (stat instanceof AST_Defun) { a.push(make_injector(stat, stat.name)); } else if (stat instanceof AST_Definitions) { stat.definitions.forEach(function(def) { if (def.value && def.value instanceof AST_Lambda) { a.push(make_injector(def.value, def.name)); } }); } else { compressor.warn("Unknown statement marked with @ngInject [{file}:{line},{col}]", token); } } } } return a; }, []); } function eliminate_spurious_blocks(statements) { var seen_dirs = []; return statements.reduce(function(a, stat){ if (stat instanceof AST_BlockStatement) { CHANGED = true; a.push.apply(a, eliminate_spurious_blocks(stat.body)); } else if (stat instanceof AST_EmptyStatement) { CHANGED = true; } else if (stat instanceof AST_Directive) { if (seen_dirs.indexOf(stat.value) < 0) { a.push(stat); seen_dirs.push(stat.value); } else { CHANGED = true; } } else { a.push(stat); } return a; }, []); }; function handle_if_return(statements, compressor) { var self = compressor.self(); var in_lambda = self instanceof AST_Lambda; var ret = []; loop: for (var i = statements.length; --i >= 0;) { var stat = statements[i]; switch (true) { case (in_lambda && stat instanceof AST_Return && !stat.value && ret.length == 0): CHANGED = true; // note, ret.length is probably always zero // because we drop unreachable code before this // step. nevertheless, it's good to check. continue loop; case stat instanceof AST_If: if (stat.body instanceof AST_Return) { //--- // pretty silly case, but: // if (foo()) return; return; ==> foo(); return; if (((in_lambda && ret.length == 0) || (ret[0] instanceof AST_Return && !ret[0].value)) && !stat.body.value && !stat.alternative) { CHANGED = true; var cond = make_node(AST_SimpleStatement, stat.condition, { body: stat.condition }); ret.unshift(cond); continue loop; } //--- // if (foo()) return x; return y; ==> return foo() ? x : y; if (ret[0] instanceof AST_Return && stat.body.value && ret[0].value && !stat.alternative) { CHANGED = true; stat = stat.clone(); stat.alternative = ret[0]; ret[0] = stat.transform(compressor); continue loop; } //--- // if (foo()) return x; [ return ; ] ==> return foo() ? x : undefined; if ((ret.length == 0 || ret[0] instanceof AST_Return) && stat.body.value && !stat.alternative && in_lambda) { CHANGED = true; stat = stat.clone(); stat.alternative = ret[0] || make_node(AST_Return, stat, { value: make_node(AST_Undefined, stat) }); ret[0] = stat.transform(compressor); continue loop; } //--- // if (foo()) return; [ else x... ]; y... ==> if (!foo()) { x...; y... } if (!stat.body.value && in_lambda) { CHANGED = true; stat = stat.clone(); stat.condition = stat.condition.negate(compressor); stat.body = make_node(AST_BlockStatement, stat, { body: as_statement_array(stat.alternative).concat(ret) }); stat.alternative = null; ret = [ stat.transform(compressor) ]; continue loop; } //--- // XXX: what was the intention of this case? // if sequences is not enabled, this can lead to an endless loop (issue #866). // however, with sequences on this helps producing slightly better output for // the example code. if (compressor.option("sequences") && ret.length == 1 && in_lambda && ret[0] instanceof AST_SimpleStatement && (!stat.alternative || stat.alternative instanceof AST_SimpleStatement)) { CHANGED = true; ret.push(make_node(AST_Return, ret[0], { value: make_node(AST_Undefined, ret[0]) }).transform(compressor)); ret = as_statement_array(stat.alternative).concat(ret); ret.unshift(stat); continue loop; } } var ab = aborts(stat.body); var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab.label) : null; if (ab && ((ab instanceof AST_Return && !ab.value && in_lambda) || (ab instanceof AST_Continue && self === loop_body(lct)) || (ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct))) { if (ab.label) { remove(ab.label.thedef.references, ab); } CHANGED = true; var body = as_statement_array(stat.body).slice(0, -1); stat = stat.clone(); stat.condition = stat.condition.negate(compressor); stat.body = make_node(AST_BlockStatement, stat, { body: as_statement_array(stat.alternative).concat(ret) }); stat.alternative = make_node(AST_BlockStatement, stat, { body: body }); ret = [ stat.transform(compressor) ]; continue loop; } var ab = aborts(stat.alternative); var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab.label) : null; if (ab && ((ab instanceof AST_Return && !ab.value && in_lambda) || (ab instanceof AST_Continue && self === loop_body(lct)) || (ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct))) { if (ab.label) { remove(ab.label.thedef.references, ab); } CHANGED = true; stat = stat.clone(); stat.body = make_node(AST_BlockStatement, stat.body, { body: as_statement_array(stat.body).concat(ret) }); stat.alternative = make_node(AST_BlockStatement, stat.alternative, { body: as_statement_array(stat.alternative).slice(0, -1) }); ret = [ stat.transform(compressor) ]; continue loop; } ret.unshift(stat); break; default: ret.unshift(stat); break; } } return ret; }; function eliminate_dead_code(statements, compressor) { var has_quit = false; var orig = statements.length; var self = compressor.self(); statements = statements.reduce(function(a, stat){ if (has_quit) { extract_declarations_from_unreachable_code(compressor, stat, a); } else { if (stat instanceof AST_LoopControl) { var lct = compressor.loopcontrol_target(stat.label); if ((stat instanceof AST_Break && lct instanceof AST_BlockStatement && loop_body(lct) === self) || (stat instanceof AST_Continue && loop_body(lct) === self)) { if (stat.label) { remove(stat.label.thedef.references, stat); } } else { a.push(stat); } } else { a.push(stat); } if (aborts(stat)) has_quit = true; } return a; }, []); CHANGED = statements.length != orig; return statements; }; function sequencesize(statements, compressor) { if (statements.length < 2) return statements; var seq = [], ret = []; function push_seq() { seq = AST_Seq.from_array(seq); if (seq) ret.push(make_node(AST_SimpleStatement, seq, { body: seq })); seq = []; }; statements.forEach(function(stat){ if (stat instanceof AST_SimpleStatement && seq.length < 2000) seq.push(stat.body); else push_seq(), ret.push(stat); }); push_seq(); ret = sequencesize_2(ret, compressor); CHANGED = ret.length != statements.length; return ret; }; function sequencesize_2(statements, compressor) { function cons_seq(right) { ret.pop(); var left = prev.body; if (left instanceof AST_Seq) { left.add(right); } else { left = AST_Seq.cons(left, right); } return left.transform(compressor); }; var ret = [], prev = null; statements.forEach(function(stat){ if (prev) { if (stat instanceof AST_For) { var opera = {}; try { prev.body.walk(new TreeWalker(function(node){ if (node instanceof AST_Binary && node.operator == "in") throw opera; })); if (stat.init && !(stat.init instanceof AST_Definitions)) { stat.init = cons_seq(stat.init); } else if (!stat.init) { stat.init = prev.body; ret.pop(); } } catch(ex) { if (ex !== opera) throw ex; } } else if (stat instanceof AST_If) { stat.condition = cons_seq(stat.condition); } else if (stat instanceof AST_With) { stat.expression = cons_seq(stat.expression); } else if (stat instanceof AST_Exit && stat.value) { stat.value = cons_seq(stat.value); } else if (stat instanceof AST_Exit) { stat.value = cons_seq(make_node(AST_Undefined, stat)); } else if (stat instanceof AST_Switch) { stat.expression = cons_seq(stat.expression); } } ret.push(stat); prev = stat instanceof AST_SimpleStatement ? stat : null; }); return ret; }; function join_consecutive_vars(statements, compressor) { var prev = null; return statements.reduce(function(a, stat){ if (stat instanceof AST_Definitions && prev && prev.TYPE == stat.TYPE) { prev.definitions = prev.definitions.concat(stat.definitions); CHANGED = true; } else if (stat instanceof AST_For && prev instanceof AST_Definitions && (!stat.init || stat.init.TYPE == prev.TYPE)) { CHANGED = true; a.pop(); if (stat.init) { stat.init.definitions = prev.definitions.concat(stat.init.definitions); } else { stat.init = prev; } a.push(stat); prev = stat; } else { prev = stat; a.push(stat); } return a; }, []); }; function negate_iifes(statements, compressor) { statements.forEach(function(stat){ if (stat instanceof AST_SimpleStatement) { stat.body = (function transform(thing) { return thing.transform(new TreeTransformer(function(node){ if (node instanceof AST_Call && node.expression instanceof AST_Function) { return make_node(AST_UnaryPrefix, node, { operator: "!", expression: node }); } else if (node instanceof AST_Call) { node.expression = transform(node.expression); } else if (node instanceof AST_Seq) { node.car = transform(node.car); } else if (node instanceof AST_Conditional) { var expr = transform(node.condition); if (expr !== node.condition) { // it has been negated, reverse node.condition = expr; var tmp = node.consequent; node.consequent = node.alternative; node.alternative = tmp; } } return node; })); })(stat.body); } }); }; }; function extract_declarations_from_unreachable_code(compressor, stat, target) { compressor.warn("Dropping unreachable code [{file}:{line},{col}]", stat.start); stat.walk(new TreeWalker(function(node){ if (node instanceof AST_Definitions) { compressor.warn("Declarations in unreachable code! [{file}:{line},{col}]", node.start); node.remove_initializers(); target.push(node); return true; } if (node instanceof AST_Defun) { target.push(node); return true; } if (node instanceof AST_Scope) { return true; } })); }; /* -----[ boolean/negation helpers ]----- */ // methods to determine whether an expression has a boolean result type (function (def){ var unary_bool = [ "!", "delete" ]; var binary_bool = [ "in", "instanceof", "==", "!=", "===", "!==", "<", "<=", ">=", ">" ]; def(AST_Node, function(){ return false }); def(AST_UnaryPrefix, function(){ return member(this.operator, unary_bool); }); def(AST_Binary, function(){ return member(this.operator, binary_bool) || ( (this.operator == "&&" || this.operator == "||") && this.left.is_boolean() && this.right.is_boolean() ); }); def(AST_Conditional, function(){ return this.consequent.is_boolean() && this.alternative.is_boolean(); }); def(AST_Assign, function(){ return this.operator == "=" && this.right.is_boolean(); }); def(AST_Seq, function(){ return this.cdr.is_boolean(); }); def(AST_True, function(){ return true }); def(AST_False, function(){ return true }); })(function(node, func){ node.DEFMETHOD("is_boolean", func); }); // methods to determine if an expression has a string result type (function (def){ def(AST_Node, function(){ return false }); def(AST_String, function(){ return true }); def(AST_UnaryPrefix, function(){ return this.operator == "typeof"; }); def(AST_Binary, function(compressor){ return this.operator == "+" && (this.left.is_string(compressor) || this.right.is_string(compressor)); }); def(AST_Assign, function(compressor){ return (this.operator == "=" || this.operator == "+=") && this.right.is_string(compressor); }); def(AST_Seq, function(compressor){ return this.cdr.is_string(compressor); }); def(AST_Conditional, function(compressor){ return this.consequent.is_string(compressor) && this.alternative.is_string(compressor); }); def(AST_Call, function(compressor){ return compressor.option("unsafe") && this.expression instanceof AST_SymbolRef && this.expression.name == "String" && this.expression.undeclared(); }); })(function(node, func){ node.DEFMETHOD("is_string", func); }); function best_of(ast1, ast2) { return ast1.print_to_string().length > ast2.print_to_string().length ? ast2 : ast1; }; // methods to evaluate a constant expression (function (def){ // The evaluate method returns an array with one or two // elements. If the node has been successfully reduced to a // constant, then the second element tells us the value; // otherwise the second element is missing. The first element // of the array is always an AST_Node descendant; if // evaluation was successful it's a node that represents the // constant; otherwise it's the original or a replacement node. AST_Node.DEFMETHOD("evaluate", function(compressor){ if (!compressor.option("evaluate")) return [ this ]; try { var val = this._eval(compressor); return [ best_of(make_node_from_constant(compressor, val, this), this), val ]; } catch(ex) { if (ex !== def) throw ex; return [ this ]; } }); def(AST_Statement, function(){ throw new Error(string_template("Cannot evaluate a statement [{file}:{line},{col}]", this.start)); }); def(AST_Function, function(){ // XXX: AST_Function inherits from AST_Scope, which itself // inherits from AST_Statement; however, an AST_Function // isn't really a statement. This could byte in other // places too. :-( Wish JS had multiple inheritance. throw def; }); function ev(node, compressor) { if (!compressor) throw new Error("Compressor must be passed"); return node._eval(compressor); }; def(AST_Node, function(){ throw def; // not constant }); def(AST_Constant, function(){ return this.getValue(); }); def(AST_UnaryPrefix, function(compressor){ var e = this.expression; switch (this.operator) { case "!": return !ev(e, compressor); case "typeof": // Function would be evaluated to an array and so typeof would // incorrectly return 'object'. Hence making is a special case. if (e instanceof AST_Function) return typeof function(){}; e = ev(e, compressor); // typeof <RegExp> returns "object" or "function" on different platforms // so cannot evaluate reliably if (e instanceof RegExp) throw def; return typeof e; case "void": return void ev(e, compressor); case "~": return ~ev(e, compressor); case "-": e = ev(e, compressor); if (e === 0) throw def; return -e; case "+": return +ev(e, compressor); } throw def; }); def(AST_Binary, function(c){ var left = this.left, right = this.right; switch (this.operator) { case "&&" : return ev(left, c) && ev(right, c); case "||" : return ev(left, c) || ev(right, c); case "|" : return ev(left, c) | ev(right, c); case "&" : return ev(left, c) & ev(right, c); case "^" : return ev(left, c) ^ ev(right, c); case "+" : return ev(left, c) + ev(right, c); case "*" : return ev(left, c) * ev(right, c); case "/" : return ev(left, c) / ev(right, c); case "%" : return ev(left, c) % ev(right, c); case "-" : return ev(left, c) - ev(right, c); case "<<" : return ev(left, c) << ev(right, c); case ">>" : return ev(left, c) >> ev(right, c); case ">>>" : return ev(left, c) >>> ev(right, c); case "==" : return ev(left, c) == ev(right, c); case "===" : return ev(left, c) === ev(right, c); case "!=" : return ev(left, c) != ev(right, c); case "!==" : return ev(left, c) !== ev(right, c); case "<" : return ev(left, c) < ev(right, c); case "<=" : return ev(left, c) <= ev(right, c); case ">" : return ev(left, c) > ev(right, c); case ">=" : return ev(left, c) >= ev(right, c); case "in" : return ev(left, c) in ev(right, c); case "instanceof" : return ev(left, c) instanceof ev(right, c); } throw def; }); def(AST_Conditional, function(compressor){ return ev(this.condition, compressor) ? ev(this.consequent, compressor) : ev(this.alternative, compressor); }); def(AST_SymbolRef, function(compressor){ var d = this.definition(); if (d && d.constant && d.init) return ev(d.init, compressor); throw def; }); def(AST_Dot, function(compressor){ if (compressor.option("unsafe") && this.property == "length") { var str = ev(this.expression, compressor); if (typeof str == "string") return str.length; } throw def; }); })(function(node, func){ node.DEFMETHOD("_eval", func); }); // method to negate an expression (function(def){ function basic_negation(exp) { return make_node(AST_UnaryPrefix, exp, { operator: "!", expression: exp }); }; def(AST_Node, function(){ return basic_negation(this); }); def(AST_Statement, function(){ throw new Error("Cannot negate a statement"); }); def(AST_Function, function(){ return basic_negation(this); }); def(AST_UnaryPrefix, function(){ if (this.operator == "!") return this.expression; return basic_negation(this); }); def(AST_Seq, function(compressor){ var self = this.clone(); self.cdr = self.cdr.negate(compressor); return self; }); def(AST_Conditional, function(compressor){ var self = this.clone(); self.consequent = self.consequent.negate(compressor); self.alternative = self.alternative.negate(compressor); return best_of(basic_negation(this), self); }); def(AST_Binary, function(compressor){ var self = this.clone(), op = this.operator; if (compressor.option("unsafe_comps")) { switch (op) { case "<=" : self.operator = ">" ; return self; case "<" : self.operator = ">=" ; return self; case ">=" : self.operator = "<" ; return self; case ">" : self.operator = "<=" ; return self; } } switch (op) { case "==" : self.operator = "!="; return self; case "!=" : self.operator = "=="; return self; case "===": self.operator = "!=="; return self; case "!==": self.operator = "==="; return self; case "&&": self.operator = "||"; self.left = self.left.negate(compressor); self.right = self.right.negate(compressor); return best_of(basic_negation(this), self); case "||": self.operator = "&&"; self.left = self.left.negate(compressor); self.right = self.right.negate(compressor); return best_of(basic_negation(this), self); } return basic_negation(this); }); })(function(node, func){ node.DEFMETHOD("negate", function(compressor){ return func.call(this, compressor); }); }); // determine if expression has side effects (function(def){ def(AST_Node, function(compressor){ return true }); def(AST_EmptyStatement, function(compressor){ return false }); def(AST_Constant, function(compressor){ return false }); def(AST_This, function(compressor){ return false }); def(AST_Call, function(compressor){ var pure = compressor.option("pure_funcs"); if (!pure) return true; if (typeof pure == "function") return pure(this); return pure.indexOf(this.expression.print_to_string()) < 0; }); def(AST_Block, function(compressor){ for (var i = this.body.length; --i >= 0;) { if (this.body[i].has_side_effects(compressor)) return true; } return false; }); def(AST_SimpleStatement, function(compressor){ return this.body.has_side_effects(compressor); }); def(AST_Defun, function(compressor){ return true }); def(AST_Function, function(compressor){ return false }); def(AST_Binary, function(compressor){ return this.left.has_side_effects(compressor) || this.right.has_side_effects(compressor); }); def(AST_Assign, function(compressor){ return true }); def(AST_Conditional, function(compressor){ return this.condition.has_side_effects(compressor) || this.consequent.has_side_effects(compressor) || this.alternative.has_side_effects(compressor); }); def(AST_Unary, function(compressor){ return this.operator == "delete" || this.operator == "++" || this.operator == "--" || this.expression.has_side_effects(compressor); }); def(AST_SymbolRef, function(compressor){ return this.global() && this.undeclared(); }); def(AST_Object, function(compressor){ for (var i = this.properties.length; --i >= 0;) if (this.properties[i].has_side_effects(compressor)) return true; return false; }); def(AST_ObjectProperty, function(compressor){ return this.value.has_side_effects(compressor); }); def(AST_Array, function(compressor){ for (var i = this.elements.length; --i >= 0;) if (this.elements[i].has_side_effects(compressor)) return true; return false; }); def(AST_Dot, function(compressor){ if (!compressor.option("pure_getters")) return true; return this.expression.has_side_effects(compressor); }); def(AST_Sub, function(compressor){ if (!compressor.option("pure_getters")) return true; return this.expression.has_side_effects(compressor) || this.property.has_side_effects(compressor); }); def(AST_PropAccess, function(compressor){ return !compressor.option("pure_getters"); }); def(AST_Seq, function(compressor){ return this.car.has_side_effects(compressor) || this.cdr.has_side_effects(compressor); }); })(function(node, func){ node.DEFMETHOD("has_side_effects", func); }); // tell me if a statement aborts function aborts(thing) { return thing && thing.aborts(); }; (function(def){ def(AST_Statement, function(){ return null }); def(AST_Jump, function(){ return this }); function block_aborts(){ var n = this.body.length; return n > 0 && aborts(this.body[n - 1]); }; def(AST_BlockStatement, block_aborts); def(AST_SwitchBranch, block_aborts); def(AST_If, function(){ return this.alternative && aborts(this.body) && aborts(this.alternative) && this; }); })(function(node, func){ node.DEFMETHOD("aborts", func); }); /* -----[ optimizers ]----- */ OPT(AST_Directive, function(self, compressor){ if (compressor.has_directive(self.value) === "up") { return make_node(AST_EmptyStatement, self); } return self; }); OPT(AST_Debugger, function(self, compressor){ if (compressor.option("drop_debugger")) return make_node(AST_EmptyStatement, self); return self; }); OPT(AST_LabeledStatement, function(self, compressor){ if (self.body instanceof AST_Break && compressor.loopcontrol_target(self.body.label) === self.body) { return make_node(AST_EmptyStatement, self); } return self.label.references.length == 0 ? self.body : self; }); OPT(AST_Block, function(self, compressor){ self.body = tighten_body(self.body, compressor); return self; }); OPT(AST_BlockStatement, function(self, compressor){ self.body = tighten_body(self.body, compressor); switch (self.body.length) { case 1: return self.body[0]; case 0: return make_node(AST_EmptyStatement, self); } return self; }); AST_Scope.DEFMETHOD("drop_unused", function(compressor){ var self = this; if (compressor.has_directive("use asm")) return self; if (compressor.option("unused") && !(self instanceof AST_Toplevel) && !self.uses_eval ) { var in_use = []; var initializations = new Dictionary(); // pass 1: find out which symbols are directly used in // this scope (not in nested scopes). var scope = this; var tw = new TreeWalker(function(node, descend){ if (node !== self) { if (node instanceof AST_Defun) { initializations.add(node.name.name, node); return true; // don't go in nested scopes } if (node instanceof AST_Definitions && scope === self) { node.definitions.forEach(function(def){ if (def.value) { initializations.add(def.name.name, def.value); if (def.value.has_side_effects(compressor)) { def.value.walk(tw); } } }); return true; } if (node instanceof AST_SymbolRef) { push_uniq(in_use, node.definition()); return true; } if (node instanceof AST_Scope) { var save_scope = scope; scope = node; descend(); scope = save_scope; return true; } } }); self.walk(tw); // pass 2: for every used symbol we need to walk its // initialization code to figure out if it uses other // symbols (that may not be in_use). for (var i = 0; i < in_use.length; ++i) { in_use[i].orig.forEach(function(decl){ // undeclared globals will be instanceof AST_SymbolRef var init = initializations.get(decl.name); if (init) init.forEach(function(init){ var tw = new TreeWalker(function(node){ if (node instanceof AST_SymbolRef) { push_uniq(in_use, node.definition()); } }); init.walk(tw); }); }); } // pass 3: we should drop declarations not in_use var tt = new TreeTransformer( function before(node, descend, in_list) { if (node instanceof AST_Lambda && !(node instanceof AST_Accessor)) { if (!compressor.option("keep_fargs")) { for (var a = node.argnames, i = a.length; --i >= 0;) { var sym = a[i]; if (sym.unreferenced()) { a.pop(); compressor.warn("Dropping unused function argument {name} [{file}:{line},{col}]", { name : sym.name, file : sym.start.file, line : sym.start.line, col : sym.start.col }); } else break; } } } if (node instanceof AST_Defun && node !== self) { if (!member(node.name.definition(), in_use)) { compressor.warn("Dropping unused function {name} [{file}:{line},{col}]", { name : node.name.name, file : node.name.start.file, line : node.name.start.line, col : node.name.start.col }); return make_node(AST_EmptyStatement, node); } return node; } if (node instanceof AST_Definitions && !(tt.parent() instanceof AST_ForIn)) { var def = node.definitions.filter(function(def){ if (member(def.name.definition(), in_use)) return true; var w = { name : def.name.name, file : def.name.start.file, line : def.name.start.line, col : def.name.start.col }; if (def.value && def.value.has_side_effects(compressor)) { def._unused_side_effects = true; compressor.warn("Side effects in initialization of unused variable {name} [{file}:{line},{col}]", w); return true; } compressor.warn("Dropping unused variable {name} [{file}:{line},{col}]", w); return false; }); // place uninitialized names at the start def = mergeSort(def, function(a, b){ if (!a.value && b.value) return -1; if (!b.value && a.value) return 1; return 0; }); // for unused names whose initialization has // side effects, we can cascade the init. code // into the next one, or next statement. var side_effects = []; for (var i = 0; i < def.length;) { var x = def[i]; if (x._unused_side_effects) { side_effects.push(x.value); def.splice(i, 1); } else { if (side_effects.length > 0) { side_effects.push(x.value); x.value = AST_Seq.from_array(side_effects); side_effects = []; } ++i; } } if (side_effects.length > 0) { side_effects = make_node(AST_BlockStatement, node, { body: [ make_node(AST_SimpleStatement, node, { body: AST_Seq.from_array(side_effects) }) ] }); } else { side_effects = null; } if (def.length == 0 && !side_effects) { return make_node(AST_EmptyStatement, node); } if (def.length == 0) { return in_list ? MAP.splice(side_effects.body) : side_effects; } node.definitions = def; if (side_effects) { side_effects.body.unshift(node); return in_list ? MAP.splice(side_effects.body) : side_effects; } return node; } if (node instanceof AST_For) { descend(node, this); if (node.init instanceof AST_BlockStatement) { // certain combination of unused name + side effect leads to: // https://github.com/mishoo/UglifyJS2/issues/44 // that's an invalid AST. // We fix it at this stage by moving the `var` outside the `for`. var body = node.init.body.slice(0, -1); node.init = node.init.body.slice(-1)[0].body; body.push(node); return in_list ? MAP.splice(body) : make_node(AST_BlockStatement, node, { body: body }); } } if (node instanceof AST_Scope && node !== self) return node; } ); self.transform(tt); } }); AST_Scope.DEFMETHOD("hoist_declarations", function(compressor){ var self = this; if (compressor.has_directive("use asm")) return self; var hoist_funs = compressor.option("hoist_funs"); var hoist_vars = compressor.option("hoist_vars"); if (hoist_funs || hoist_vars) { var dirs = []; var hoisted = []; var vars = new Dictionary(), vars_found = 0, var_decl = 0; // let's count var_decl first, we seem to waste a lot of // space if we hoist `var` when there's only one. self.walk(new TreeWalker(function(node){ if (node instanceof AST_Scope && node !== self) return true; if (node instanceof AST_Var) { ++var_decl; return true; } })); hoist_vars = hoist_vars && var_decl > 1; var tt = new TreeTransformer( function before(node) { if (node !== self) { if (node instanceof AST_Directive) { dirs.push(node); return make_node(AST_EmptyStatement, node); } if (node instanceof AST_Defun && hoist_funs) { hoisted.push(node); return make_node(AST_EmptyStatement, node); } if (node instanceof AST_Var && hoist_vars) { node.definitions.forEach(function(def){ vars.set(def.name.name, def); ++vars_found; }); var seq = node.to_assignments(); var p = tt.parent(); if (p instanceof AST_ForIn && p.init === node) { if (seq == null) return node.definitions[0].name; return seq; } if (p instanceof AST_For && p.init === node) { return seq; } if (!seq) return make_node(AST_EmptyStatement, node); return make_node(AST_SimpleStatement, node, { body: seq }); } if (node instanceof AST_Scope) return node; // to avoid descending in nested scopes } } ); self = self.transform(tt); if (vars_found > 0) { // collect only vars which don't show up in self's arguments list var defs = []; vars.each(function(def, name){ if (self instanceof AST_Lambda && find_if(function(x){ return x.name == def.name.name }, self.argnames)) { vars.del(name); } else { def = def.clone(); def.value = null; defs.push(def); vars.set(name, def); } }); if (defs.length > 0) { // try to merge in assignments for (var i = 0; i < self.body.length;) { if (self.body[i] instanceof AST_SimpleStatement) { var expr = self.body[i].body, sym, assign; if (expr instanceof AST_Assign && expr.operator == "=" && (sym = expr.left) instanceof AST_Symbol && vars.has(sym.name)) { var def = vars.get(sym.name); if (def.value) break; def.value = expr.right; remove(defs, def); defs.push(def); self.body.splice(i, 1); continue; } if (expr instanceof AST_Seq && (assign = expr.car) instanceof AST_Assign && assign.operator == "=" && (sym = assign.left) instanceof AST_Symbol && vars.has(sym.name)) { var def = vars.get(sym.name); if (def.value) break; def.value = assign.right; remove(defs, def); defs.push(def); self.body[i].body = expr.cdr; continue; } } if (self.body[i] instanceof AST_EmptyStatement) { self.body.splice(i, 1); continue; } if (self.body[i] instanceof AST_BlockStatement) { var tmp = [ i, 1 ].concat(self.body[i].body); self.body.splice.apply(self.body, tmp); continue; } break; } defs = make_node(AST_Var, self, { definitions: defs }); hoisted.push(defs); }; } self.body = dirs.concat(hoisted, self.body); } return self; }); OPT(AST_SimpleStatement, function(self, compressor){ if (compressor.option("side_effects")) { if (!self.body.has_side_effects(compressor)) { compressor.warn("Dropping side-effect-free statement [{file}:{line},{col}]", self.start); return make_node(AST_EmptyStatement, self); } } return self; }); OPT(AST_DWLoop, function(self, compressor){ var cond = self.condition.evaluate(compressor); self.condition = cond[0]; if (!compressor.option("loops")) return self; if (cond.length > 1) { if (cond[1]) { return make_node(AST_For, self, { body: self.body }); } else if (self instanceof AST_While) { if (compressor.option("dead_code")) { var a = []; extract_declarations_from_unreachable_code(compressor, self.body, a); return make_node(AST_BlockStatement, self, { body: a }); } } } return self; }); function if_break_in_loop(self, compressor) { function drop_it(rest) { rest = as_statement_array(rest); if (self.body instanceof AST_BlockStatement) { self.body = self.body.clone(); self.body.body = rest.concat(self.body.body.slice(1)); self.body = self.body.transform(compressor); } else { self.body = make_node(AST_BlockStatement, self.body, { body: rest }).transform(compressor); } if_break_in_loop(self, compressor); } var first = self.body instanceof AST_BlockStatement ? self.body.body[0] : self.body; if (first instanceof AST_If) { if (first.body instanceof AST_Break && compressor.loopcontrol_target(first.body.label) === self) { if (self.condition) { self.condition = make_node(AST_Binary, self.condition, { left: self.condition, operator: "&&", right: first.condition.negate(compressor), }); } else { self.condition = first.condition.negate(compressor); } drop_it(first.alternative); } else if (first.alternative instanceof AST_Break && compressor.loopcontrol_target(first.alternative.label) === self) { if (self.condition) { self.condition = make_node(AST_Binary, self.condition, { left: self.condition, operator: "&&", right: first.condition, }); } else { self.condition = first.condition; } drop_it(first.body); } } }; OPT(AST_While, function(self, compressor) { if (!compressor.option("loops")) return self; self = AST_DWLoop.prototype.optimize.call(self, compressor); if (self instanceof AST_While) { if_break_in_loop(self, compressor); self = make_node(AST_For, self, self).transform(compressor); } return self; }); OPT(AST_For, function(self, compressor){ var cond = self.condition; if (cond) { cond = cond.evaluate(compressor); self.condition = cond[0]; } if (!compressor.option("loops")) return self; if (cond) { if (cond.length > 1 && !cond[1]) { if (compressor.option("dead_code")) { var a = []; if (self.init instanceof AST_Statement) { a.push(self.init); } else if (self.init) { a.push(make_node(AST_SimpleStatement, self.init, { body: self.init })); } extract_declarations_from_unreachable_code(compressor, self.body, a); return make_node(AST_BlockStatement, self, { body: a }); } } } if_break_in_loop(self, compressor); return self; }); OPT(AST_If, function(self, compressor){ if (!compressor.option("conditionals")) return self; // if condition can be statically determined, warn and drop // one of the blocks. note, statically determined implies // “has no side effects”; also it doesn't work for cases like // `x && true`, though it probably should. var cond = self.condition.evaluate(compressor); self.condition = cond[0]; if (cond.length > 1) { if (cond[1]) { compressor.warn("Condition always true [{file}:{line},{col}]", self.condition.start); if (compressor.option("dead_code")) { var a = []; if (self.alternative) { extract_declarations_from_unreachable_code(compressor, self.alternative, a); } a.push(self.body); return make_node(AST_BlockStatement, self, { body: a }).transform(compressor); } } else { compressor.warn("Condition always false [{file}:{line},{col}]", self.condition.start); if (compressor.option("dead_code")) { var a = []; extract_declarations_from_unreachable_code(compressor, self.body, a); if (self.alternative) a.push(self.alternative); return make_node(AST_BlockStatement, self, { body: a }).transform(compressor); } } } if (is_empty(self.alternative)) self.alternative = null; var negated = self.condition.negate(compressor); var negated_is_best = best_of(self.condition, negated) === negated; if (self.alternative && negated_is_best) { negated_is_best = false; // because we already do the switch here. self.condition = negated; var tmp = self.body; self.body = self.alternative || make_node(AST_EmptyStatement); self.alternative = tmp; } if (is_empty(self.body) && is_empty(self.alternative)) { return make_node(AST_SimpleStatement, self.condition, { body: self.condition }).transform(compressor); } if (self.body instanceof AST_SimpleStatement && self.alternative instanceof AST_SimpleStatement) { return make_node(AST_SimpleStatement, self, { body: make_node(AST_Conditional, self, { condition : self.condition, consequent : self.body.body, alternative : self.alternative.body }) }).transform(compressor); } if (is_empty(self.alternative) && self.body instanceof AST_SimpleStatement) { if (negated_is_best) return make_node(AST_SimpleStatement, self, { body: make_node(AST_Binary, self, { operator : "||", left : negated, right : self.body.body }) }).transform(compressor); return make_node(AST_SimpleStatement, self, { body: make_node(AST_Binary, self, { operator : "&&", left : self.condition, right : self.body.body }) }).transform(compressor); } if (self.body instanceof AST_EmptyStatement && self.alternative && self.alternative instanceof AST_SimpleStatement) { return make_node(AST_SimpleStatement, self, { body: make_node(AST_Binary, self, { operator : "||", left : self.condition, right : self.alternative.body }) }).transform(compressor); } if (self.body instanceof AST_Exit && self.alternative instanceof AST_Exit && self.body.TYPE == self.alternative.TYPE) { return make_node(self.body.CTOR, self, { value: make_node(AST_Conditional, self, { condition : self.condition, consequent : self.body.value || make_node(AST_Undefined, self.body).optimize(compressor), alternative : self.alternative.value || make_node(AST_Undefined, self.alternative).optimize(compressor) }) }).transform(compressor); } if (self.body instanceof AST_If && !self.body.alternative && !self.alternative) { self.condition = make_node(AST_Binary, self.condition, { operator: "&&", left: self.condition, right: self.body.condition }).transform(compressor); self.body = self.body.body; } if (aborts(self.body)) { if (self.alternative) { var alt = self.alternative; self.alternative = null; return make_node(AST_BlockStatement, self, { body: [ self, alt ] }).transform(compressor); } } if (aborts(self.alternative)) { var body = self.body; self.body = self.alternative; self.condition = negated_is_best ? negated : self.condition.negate(compressor); self.alternative = null; return make_node(AST_BlockStatement, self, { body: [ self, body ] }).transform(compressor); } return self; }); OPT(AST_Switch, function(self, compressor){ if (self.body.length == 0 && compressor.option("conditionals")) { return make_node(AST_SimpleStatement, self, { body: self.expression }).transform(compressor); } for(;;) { var last_branch = self.body[self.body.length - 1]; if (last_branch) { var stat = last_branch.body[last_branch.body.length - 1]; // last statement if (stat instanceof AST_Break && loop_body(compressor.loopcontrol_target(stat.label)) === self) last_branch.body.pop(); if (last_branch instanceof AST_Default && last_branch.body.length == 0) { self.body.pop(); continue; } } break; } var exp = self.expression.evaluate(compressor); out: if (exp.length == 2) try { // constant expression self.expression = exp[0]; if (!compressor.option("dead_code")) break out; var value = exp[1]; var in_if = false; var in_block = false; var started = false; var stopped = false; var ruined = false; var tt = new TreeTransformer(function(node, descend, in_list){ if (node instanceof AST_Lambda || node instanceof AST_SimpleStatement) { // no need to descend these node types return node; } else if (node instanceof AST_Switch && node === self) { node = node.clone(); descend(node, this); return ruined ? node : make_node(AST_BlockStatement, node, { body: node.body.reduce(function(a, branch){ return a.concat(branch.body); }, []) }).transform(compressor); } else if (node instanceof AST_If || node instanceof AST_Try) { var save = in_if; in_if = !in_block; descend(node, this); in_if = save; return node; } else if (node instanceof AST_StatementWithBody || node instanceof AST_Switch) { var save = in_block; in_block = true; descend(node, this); in_block = save; return node; } else if (node instanceof AST_Break && this.loopcontrol_target(node.label) === self) { if (in_if) { ruined = true; return node; } if (in_block) return node; stopped = true; return in_list ? MAP.skip : make_node(AST_EmptyStatement, node); } else if (node instanceof AST_SwitchBranch && this.parent() === self) { if (stopped) return MAP.skip; if (node instanceof AST_Case) { var exp = node.expression.evaluate(compressor); if (exp.length < 2) { // got a case with non-constant expression, baling out throw self; } if (exp[1] === value || started) { started = true; if (aborts(node)) stopped = true; descend(node, this); return node; } return MAP.skip; } descend(node, this); return node; } }); tt.stack = compressor.stack.slice(); // so that's able to see parent nodes self = self.transform(tt); } catch(ex) { if (ex !== self) throw ex; } return self; }); OPT(AST_Case, function(self, compressor){ self.body = tighten_body(self.body, compressor); return self; }); OPT(AST_Try, function(self, compressor){ self.body = tighten_body(self.body, compressor); return self; }); AST_Definitions.DEFMETHOD("remove_initializers", function(){ this.definitions.forEach(function(def){ def.value = null }); }); AST_Definitions.DEFMETHOD("to_assignments", function(){ var assignments = this.definitions.reduce(function(a, def){ if (def.value) { var name = make_node(AST_SymbolRef, def.name, def.name); a.push(make_node(AST_Assign, def, { operator : "=", left : name, right : def.value })); } return a; }, []); if (assignments.length == 0) return null; return AST_Seq.from_array(assignments); }); OPT(AST_Definitions, function(self, compressor){ if (self.definitions.length == 0) return make_node(AST_EmptyStatement, self); return self; }); OPT(AST_Function, function(self, compressor){ self = AST_Lambda.prototype.optimize.call(self, compressor); if (compressor.option("unused") && !compressor.option("keep_fnames")) { if (self.name && self.name.unreferenced()) { self.name = null; } } return self; }); OPT(AST_Call, function(self, compressor){ if (compressor.option("unsafe")) { var exp = self.expression; if (exp instanceof AST_SymbolRef && exp.undeclared()) { switch (exp.name) { case "Array": if (self.args.length != 1) { return make_node(AST_Array, self, { elements: self.args }).transform(compressor); } break; case "Object": if (self.args.length == 0) { return make_node(AST_Object, self, { properties: [] }); } break; case "String": if (self.args.length == 0) return make_node(AST_String, self, { value: "" }); if (self.args.length <= 1) return make_node(AST_Binary, self, { left: self.args[0], operator: "+", right: make_node(AST_String, self, { value: "" }) }).transform(compressor); break; case "Number": if (self.args.length == 0) return make_node(AST_Number, self, { value: 0 }); if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, { expression: self.args[0], operator: "+" }).transform(compressor); case "Boolean": if (self.args.length == 0) return make_node(AST_False, self); if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, { expression: make_node(AST_UnaryPrefix, null, { expression: self.args[0], operator: "!" }), operator: "!" }).transform(compressor); break; case "Function": // new Function() => function(){} if (self.args.length == 0) return make_node(AST_Function, self, { argnames: [], body: [] }); if (all(self.args, function(x){ return x instanceof AST_String })) { // quite a corner-case, but we can handle it: // https://github.com/mishoo/UglifyJS2/issues/203 // if the code argument is a constant, then we can minify it. try { var code = "(function(" + self.args.slice(0, -1).map(function(arg){ return arg.value; }).join(",") + "){" + self.args[self.args.length - 1].value + "})()"; var ast = parse(code); ast.figure_out_scope({ screw_ie8: compressor.option("screw_ie8") }); var comp = new Compressor(compressor.options); ast = ast.transform(comp); ast.figure_out_scope({ screw_ie8: compressor.option("screw_ie8") }); ast.mangle_names(); var fun; try { ast.walk(new TreeWalker(function(node){ if (node instanceof AST_Lambda) { fun = node; throw ast; } })); } catch(ex) { if (ex !== ast) throw ex; }; if (!fun) return self; var args = fun.argnames.map(function(arg, i){ return make_node(AST_String, self.args[i], { value: arg.print_to_string() }); }); var code = OutputStream(); AST_BlockStatement.prototype._codegen.call(fun, fun, code); code = code.toString().replace(/^\{|\}$/g, ""); args.push(make_node(AST_String, self.args[self.args.length - 1], { value: code })); self.args = args; return self; } catch(ex) { if (ex instanceof JS_Parse_Error) { compressor.warn("Error parsing code passed to new Function [{file}:{line},{col}]", self.args[self.args.length - 1].start); compressor.warn(ex.toString()); } else { console.log(ex); throw ex; } } } break; } } else if (exp instanceof AST_Dot && exp.property == "toString" && self.args.length == 0) { return make_node(AST_Binary, self, { left: make_node(AST_String, self, { value: "" }), operator: "+", right: exp.expression }).transform(compressor); } else if (exp instanceof AST_Dot && exp.expression instanceof AST_Array && exp.property == "join") EXIT: { var separator = self.args.length == 0 ? "," : self.args[0].evaluate(compressor)[1]; if (separator == null) break EXIT; // not a constant var elements = exp.expression.elements.reduce(function(a, el){ el = el.evaluate(compressor); if (a.length == 0 || el.length == 1) { a.push(el); } else { var last = a[a.length - 1]; if (last.length == 2) { // it's a constant var val = "" + last[1] + separator + el[1]; a[a.length - 1] = [ make_node_from_constant(compressor, val, last[0]), val ]; } else { a.push(el); } } return a; }, []); if (elements.length == 0) return make_node(AST_String, self, { value: "" }); if (elements.length == 1) return elements[0][0]; if (separator == "") { var first; if (elements[0][0] instanceof AST_String || elements[1][0] instanceof AST_String) { first = elements.shift()[0]; } else { first = make_node(AST_String, self, { value: "" }); } return elements.reduce(function(prev, el){ return make_node(AST_Binary, el[0], { operator : "+", left : prev, right : el[0], }); }, first).transform(compressor); } // need this awkward cloning to not affect original element // best_of will decide which one to get through. var node = self.clone(); node.expression = node.expression.clone(); node.expression.expression = node.expression.expression.clone(); node.expression.expression.elements = elements.map(function(el){ return el[0]; }); return best_of(self, node); } } if (compressor.option("side_effects")) { if (self.expression instanceof AST_Function && self.args.length == 0 && !AST_Block.prototype.has_side_effects.call(self.expression, compressor)) { return make_node(AST_Undefined, self).transform(compressor); } } if (compressor.option("drop_console")) { if (self.expression instanceof AST_PropAccess) { var name = self.expression.expression; while (name.expression) { name = name.expression; } if (name instanceof AST_SymbolRef && name.name == "console" && name.undeclared()) { return make_node(AST_Undefined, self).transform(compressor); } } } return self.evaluate(compressor)[0]; }); OPT(AST_New, function(self, compressor){ if (compressor.option("unsafe")) { var exp = self.expression; if (exp instanceof AST_SymbolRef && exp.undeclared()) { switch (exp.name) { case "Object": case "RegExp": case "Function": case "Error": case "Array": return make_node(AST_Call, self, self).transform(compressor); } } } return self; }); OPT(AST_Seq, function(self, compressor){ if (!compressor.option("side_effects")) return self; if (!self.car.has_side_effects(compressor)) { // we shouldn't compress (1,func)(something) to // func(something) because that changes the meaning of // the func (becomes lexical instead of global). var p = compressor.parent(); if (!(p instanceof AST_Call && p.expression === self)) { return self.cdr; } } if (compressor.option("cascade")) { if (self.car instanceof AST_Assign && !self.car.left.has_side_effects(compressor)) { if (self.car.left.equivalent_to(self.cdr)) { return self.car; } if (self.cdr instanceof AST_Call && self.cdr.expression.equivalent_to(self.car.left)) { self.cdr.expression = self.car; return self.cdr; } } if (!self.car.has_side_effects(compressor) && !self.cdr.has_side_effects(compressor) && self.car.equivalent_to(self.cdr)) { return self.car; } } if (self.cdr instanceof AST_UnaryPrefix && self.cdr.operator == "void" && !self.cdr.expression.has_side_effects(compressor)) { self.cdr.expression = self.car; return self.cdr; } if (self.cdr instanceof AST_Undefined) { return make_node(AST_UnaryPrefix, self, { operator : "void", expression : self.car }); } return self; }); AST_Unary.DEFMETHOD("lift_sequences", function(compressor){ if (compressor.option("sequences")) { if (this.expression instanceof AST_Seq) { var seq = this.expression; var x = seq.to_array(); this.expression = x.pop(); x.push(this); seq = AST_Seq.from_array(x).transform(compressor); return seq; } } return this; }); OPT(AST_UnaryPostfix, function(self, compressor){ return self.lift_sequences(compressor); }); OPT(AST_UnaryPrefix, function(self, compressor){ self = self.lift_sequences(compressor); var e = self.expression; if (compressor.option("booleans") && compressor.in_boolean_context()) { switch (self.operator) { case "!": if (e instanceof AST_UnaryPrefix && e.operator == "!") { // !!foo ==> foo, if we're in boolean context return e.expression; } break; case "typeof": // typeof always returns a non-empty string, thus it's // always true in booleans compressor.warn("Boolean expression always true [{file}:{line},{col}]", self.start); return make_node(AST_True, self); } if (e instanceof AST_Binary && self.operator == "!") { self = best_of(self, e.negate(compressor)); } } return self.evaluate(compressor)[0]; }); function has_side_effects_or_prop_access(node, compressor) { var save_pure_getters = compressor.option("pure_getters"); compressor.options.pure_getters = false; var ret = node.has_side_effects(compressor); compressor.options.pure_getters = save_pure_getters; return ret; } AST_Binary.DEFMETHOD("lift_sequences", function(compressor){ if (compressor.option("sequences")) { if (this.left instanceof AST_Seq) { var seq = this.left; var x = seq.to_array(); this.left = x.pop(); x.push(this); seq = AST_Seq.from_array(x).transform(compressor); return seq; } if (this.right instanceof AST_Seq && this instanceof AST_Assign && !has_side_effects_or_prop_access(this.left, compressor)) { var seq = this.right; var x = seq.to_array(); this.right = x.pop(); x.push(this); seq = AST_Seq.from_array(x).transform(compressor); return seq; } } return this; }); var commutativeOperators = makePredicate("== === != !== * & | ^"); OPT(AST_Binary, function(self, compressor){ function reverse(op, force) { if (force || !(self.left.has_side_effects(compressor) || self.right.has_side_effects(compressor))) { if (op) self.operator = op; var tmp = self.left; self.left = self.right; self.right = tmp; } } if (commutativeOperators(self.operator)) { if (self.right instanceof AST_Constant && !(self.left instanceof AST_Constant)) { // if right is a constant, whatever side effects the // left side might have could not influence the // result. hence, force switch. if (!(self.left instanceof AST_Binary && PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) { reverse(null, true); } } if (/^[!=]==?$/.test(self.operator)) { if (self.left instanceof AST_SymbolRef && self.right instanceof AST_Conditional) { if (self.right.consequent instanceof AST_SymbolRef && self.right.consequent.definition() === self.left.definition()) { if (/^==/.test(self.operator)) return self.right.condition; if (/^!=/.test(self.operator)) return self.right.condition.negate(compressor); } if (self.right.alternative instanceof AST_SymbolRef && self.right.alternative.definition() === self.left.definition()) { if (/^==/.test(self.operator)) return self.right.condition.negate(compressor); if (/^!=/.test(self.operator)) return self.right.condition; } } if (self.right instanceof AST_SymbolRef && self.left instanceof AST_Conditional) { if (self.left.consequent instanceof AST_SymbolRef && self.left.consequent.definition() === self.right.definition()) { if (/^==/.test(self.operator)) return self.left.condition; if (/^!=/.test(self.operator)) return self.left.condition.negate(compressor); } if (self.left.alternative instanceof AST_SymbolRef && self.left.alternative.definition() === self.right.definition()) { if (/^==/.test(self.operator)) return self.left.condition.negate(compressor); if (/^!=/.test(self.operator)) return self.left.condition; } } } } self = self.lift_sequences(compressor); if (compressor.option("comparisons")) switch (self.operator) { case "===": case "!==": if ((self.left.is_string(compressor) && self.right.is_string(compressor)) || (self.left.is_boolean() && self.right.is_boolean())) { self.operator = self.operator.substr(0, 2); } // XXX: intentionally falling down to the next case case "==": case "!=": if (self.left instanceof AST_String && self.left.value == "undefined" && self.right instanceof AST_UnaryPrefix && self.right.operator == "typeof" && compressor.option("unsafe")) { if (!(self.right.expression instanceof AST_SymbolRef) || !self.right.expression.undeclared()) { self.right = self.right.expression; self.left = make_node(AST_Undefined, self.left).optimize(compressor); if (self.operator.length == 2) self.operator += "="; } } break; } if (compressor.option("conditionals")) { if (self.operator == "&&") { var ll = self.left.evaluate(compressor); if (ll.length > 1) { if (ll[1]) { compressor.warn("Condition left of && always true [{file}:{line},{col}]", self.start); var rr = self.right.evaluate(compressor); return rr[0]; } else { compressor.warn("Condition left of && always false [{file}:{line},{col}]", self.start); return ll[0]; } } } else if (self.operator == "||") { var ll = self.left.evaluate(compressor); if (ll.length > 1) { if (ll[1]) { compressor.warn("Condition left of || always true [{file}:{line},{col}]", self.start); return ll[0]; } else { compressor.warn("Condition left of || always false [{file}:{line},{col}]", self.start); var rr = self.right.evaluate(compressor); return rr[0]; } } } } if (compressor.option("booleans") && compressor.in_boolean_context()) switch (self.operator) { case "&&": var ll = self.left.evaluate(compressor); var rr = self.right.evaluate(compressor); if ((ll.length > 1 && !ll[1]) || (rr.length > 1 && !rr[1])) { compressor.warn("Boolean && always false [{file}:{line},{col}]", self.start); if (self.left.has_side_effects(compressor)) { return make_node(AST_Seq, self, { car: self.left, cdr: make_node(AST_False) }).optimize(compressor); } return make_node(AST_False, self); } if (ll.length > 1 && ll[1]) { return rr[0]; } if (rr.length > 1 && rr[1]) { return ll[0]; } break; case "||": var ll = self.left.evaluate(compressor); var rr = self.right.evaluate(compressor); if ((ll.length > 1 && ll[1]) || (rr.length > 1 && rr[1])) { compressor.warn("Boolean || always true [{file}:{line},{col}]", self.start); if (self.left.has_side_effects(compressor)) { return make_node(AST_Seq, self, { car: self.left, cdr: make_node(AST_True) }).optimize(compressor); } return make_node(AST_True, self); } if (ll.length > 1 && !ll[1]) { return rr[0]; } if (rr.length > 1 && !rr[1]) { return ll[0]; } break; case "+": var ll = self.left.evaluate(compressor); var rr = self.right.evaluate(compressor); if ((ll.length > 1 && ll[0] instanceof AST_String && ll[1]) || (rr.length > 1 && rr[0] instanceof AST_String && rr[1])) { compressor.warn("+ in boolean context always true [{file}:{line},{col}]", self.start); return make_node(AST_True, self); } break; } if (compressor.option("comparisons") && self.is_boolean()) { if (!(compressor.parent() instanceof AST_Binary) || compressor.parent() instanceof AST_Assign) { var negated = make_node(AST_UnaryPrefix, self, { operator: "!", expression: self.negate(compressor) }); self = best_of(self, negated); } switch (self.operator) { case "<": reverse(">"); break; case "<=": reverse(">="); break; } } if (self.operator == "+" && self.right instanceof AST_String && self.right.getValue() === "" && self.left instanceof AST_Binary && self.left.operator == "+" && self.left.is_string(compressor)) { return self.left; } if (compressor.option("evaluate")) { if (self.operator == "+") { if (self.left instanceof AST_Constant && self.right instanceof AST_Binary && self.right.operator == "+" && self.right.left instanceof AST_Constant && self.right.is_string(compressor)) { self = make_node(AST_Binary, self, { operator: "+", left: make_node(AST_String, null, { value: "" + self.left.getValue() + self.right.left.getValue(), start: self.left.start, end: self.right.left.end }), right: self.right.right }); } if (self.right instanceof AST_Constant && self.left instanceof AST_Binary && self.left.operator == "+" && self.left.right instanceof AST_Constant && self.left.is_string(compressor)) { self = make_node(AST_Binary, self, { operator: "+", left: self.left.left, right: make_node(AST_String, null, { value: "" + self.left.right.getValue() + self.right.getValue(), start: self.left.right.start, end: self.right.end }) }); } if (self.left instanceof AST_Binary && self.left.operator == "+" && self.left.is_string(compressor) && self.left.right instanceof AST_Constant && self.right instanceof AST_Binary && self.right.operator == "+" && self.right.left instanceof AST_Constant && self.right.is_string(compressor)) { self = make_node(AST_Binary, self, { operator: "+", left: make_node(AST_Binary, self.left, { operator: "+", left: self.left.left, right: make_node(AST_String, null, { value: "" + self.left.right.getValue() + self.right.left.getValue(), start: self.left.right.start, end: self.right.left.end }) }), right: self.right.right }); } } } // x && (y && z) ==> x && y && z // x || (y || z) ==> x || y || z if (self.right instanceof AST_Binary && self.right.operator == self.operator && (self.operator == "&&" || self.operator == "||")) { self.left = make_node(AST_Binary, self.left, { operator : self.operator, left : self.left, right : self.right.left }); self.right = self.right.right; return self.transform(compressor); } return self.evaluate(compressor)[0]; }); OPT(AST_SymbolRef, function(self, compressor){ function isLHS(symbol, parent) { return ( parent instanceof AST_Binary && parent.operator === '=' && parent.left === symbol ); } if (self.undeclared() && !isLHS(self, compressor.parent())) { var defines = compressor.option("global_defs"); if (defines && defines.hasOwnProperty(self.name)) { return make_node_from_constant(compressor, defines[self.name], self); } switch (self.name) { case "undefined": return make_node(AST_Undefined, self); case "NaN": return make_node(AST_NaN, self).transform(compressor); case "Infinity": return make_node(AST_Infinity, self).transform(compressor); } } return self; }); OPT(AST_Infinity, function (self, compressor) { return make_node(AST_Binary, self, { operator : '/', left : make_node(AST_Number, self, {value: 1}), right : make_node(AST_Number, self, {value: 0}) }); }); OPT(AST_Undefined, function(self, compressor){ if (compressor.option("unsafe")) { var scope = compressor.find_parent(AST_Scope); var undef = scope.find_variable("undefined"); if (undef) { var ref = make_node(AST_SymbolRef, self, { name : "undefined", scope : scope, thedef : undef }); ref.reference(); return ref; } } return self; }); var ASSIGN_OPS = [ '+', '-', '/', '*', '%', '>>', '<<', '>>>', '|', '^', '&' ]; OPT(AST_Assign, function(self, compressor){ self = self.lift_sequences(compressor); if (self.operator == "=" && self.left instanceof AST_SymbolRef && self.right instanceof AST_Binary && self.right.left instanceof AST_SymbolRef && self.right.left.name == self.left.name && member(self.right.operator, ASSIGN_OPS)) { self.operator = self.right.operator + "="; self.right = self.right.right; } return self; }); OPT(AST_Conditional, function(self, compressor){ if (!compressor.option("conditionals")) return self; if (self.condition instanceof AST_Seq) { var car = self.condition.car; self.condition = self.condition.cdr; return AST_Seq.cons(car, self); } var cond = self.condition.evaluate(compressor); if (cond.length > 1) { if (cond[1]) { compressor.warn("Condition always true [{file}:{line},{col}]", self.start); return self.consequent; } else { compressor.warn("Condition always false [{file}:{line},{col}]", self.start); return self.alternative; } } var negated = cond[0].negate(compressor); if (best_of(cond[0], negated) === negated) { self = make_node(AST_Conditional, self, { condition: negated, consequent: self.alternative, alternative: self.consequent }); } var consequent = self.consequent; var alternative = self.alternative; if (consequent instanceof AST_Assign && alternative instanceof AST_Assign && consequent.operator == alternative.operator && consequent.left.equivalent_to(alternative.left) && !consequent.left.has_side_effects(compressor) ) { /* * Stuff like this: * if (foo) exp = something; else exp = something_else; * ==> * exp = foo ? something : something_else; */ return make_node(AST_Assign, self, { operator: consequent.operator, left: consequent.left, right: make_node(AST_Conditional, self, { condition: self.condition, consequent: consequent.right, alternative: alternative.right }) }); } if (consequent instanceof AST_Call && alternative.TYPE === consequent.TYPE && consequent.args.length == alternative.args.length && !consequent.expression.has_side_effects(compressor) && consequent.expression.equivalent_to(alternative.expression)) { if (consequent.args.length == 0) { return make_node(AST_Seq, self, { car: self.condition, cdr: consequent }); } if (consequent.args.length == 1) { consequent.args[0] = make_node(AST_Conditional, self, { condition: self.condition, consequent: consequent.args[0], alternative: alternative.args[0] }); return consequent; } } // x?y?z:a:a --> x&&y?z:a if (consequent instanceof AST_Conditional && consequent.alternative.equivalent_to(alternative)) { return make_node(AST_Conditional, self, { condition: make_node(AST_Binary, self, { left: self.condition, operator: "&&", right: consequent.condition }), consequent: consequent.consequent, alternative: alternative }); } // x=y?1:1 --> x=1 if (consequent instanceof AST_Constant && alternative instanceof AST_Constant && consequent.equivalent_to(alternative)) { if (self.condition.has_side_effects(compressor)) { return AST_Seq.from_array([self.condition, make_node_from_constant(compressor, consequent.value, self)]); } else { return make_node_from_constant(compressor, consequent.value, self); } } // x=y?true:false --> x=!!y if (consequent instanceof AST_True && alternative instanceof AST_False) { self.condition = self.condition.negate(compressor); return make_node(AST_UnaryPrefix, self.condition, { operator: "!", expression: self.condition }); } // x=y?false:true --> x=!y if (consequent instanceof AST_False && alternative instanceof AST_True) { return self.condition.negate(compressor) } return self; }); OPT(AST_Boolean, function(self, compressor){ if (compressor.option("booleans")) { var p = compressor.parent(); if (p instanceof AST_Binary && (p.operator == "==" || p.operator == "!=")) { compressor.warn("Non-strict equality against boolean: {operator} {value} [{file}:{line},{col}]", { operator : p.operator, value : self.value, file : p.start.file, line : p.start.line, col : p.start.col, }); return make_node(AST_Number, self, { value: +self.value }); } return make_node(AST_UnaryPrefix, self, { operator: "!", expression: make_node(AST_Number, self, { value: 1 - self.value }) }); } return self; }); OPT(AST_Sub, function(self, compressor){ var prop = self.property; if (prop instanceof AST_String && compressor.option("properties")) { prop = prop.getValue(); if (RESERVED_WORDS(prop) ? compressor.option("screw_ie8") : is_identifier_string(prop)) { return make_node(AST_Dot, self, { expression : self.expression, property : prop }).optimize(compressor); } var v = parseFloat(prop); if (!isNaN(v) && v.toString() == prop) { self.property = make_node(AST_Number, self.property, { value: v }); } } return self; }); OPT(AST_Dot, function(self, compressor){ var prop = self.property; if (RESERVED_WORDS(prop) && !compressor.option("screw_ie8")) { return make_node(AST_Sub, self, { expression : self.expression, property : make_node(AST_String, self, { value: prop }) }).optimize(compressor); } return self.evaluate(compressor)[0]; }); function literals_in_boolean_context(self, compressor) { if (compressor.option("booleans") && compressor.in_boolean_context() && !self.has_side_effects(compressor)) { return make_node(AST_True, self); } return self; }; OPT(AST_Array, literals_in_boolean_context); OPT(AST_Object, literals_in_boolean_context); OPT(AST_RegExp, literals_in_boolean_context); OPT(AST_Return, function(self, compressor){ if (self.value instanceof AST_Undefined) { self.value = null; } return self; }); })(); /*********************************************************************** A JavaScript tokenizer / parser / beautifier / compressor. https://github.com/mishoo/UglifyJS2 -------------------------------- (C) --------------------------------- Author: Mihai Bazon <mihai.bazon@gmail.com> http://mihai.bazon.net/blog Distributed under the BSD license: Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************/ "use strict"; // a small wrapper around fitzgen's source-map library function SourceMap(options) { options = defaults(options, { file : null, root : null, orig : null, orig_line_diff : 0, dest_line_diff : 0, }); var orig_map = options.orig && new MOZ_SourceMap.SourceMapConsumer(options.orig); var generator; if (orig_map) { generator = MOZ_SourceMap.SourceMapGenerator.fromSourceMap(orig_map); } else { generator = new MOZ_SourceMap.SourceMapGenerator({ file : options.file, sourceRoot : options.root }); } function add(source, gen_line, gen_col, orig_line, orig_col, name) { if (orig_map) { var info = orig_map.originalPositionFor({ line: orig_line, column: orig_col }); if (info.source === null) { return; } source = info.source; orig_line = info.line; orig_col = info.column; name = info.name || name; } generator.addMapping({ generated : { line: gen_line + options.dest_line_diff, column: gen_col }, original : { line: orig_line + options.orig_line_diff, column: orig_col }, source : source, name : name }); } return { add : add, get : function() { return generator }, toString : function() { return JSON.stringify(generator.toJSON()); } }; }; /*********************************************************************** A JavaScript tokenizer / parser / beautifier / compressor. https://github.com/mishoo/UglifyJS2 -------------------------------- (C) --------------------------------- Author: Mihai Bazon <mihai.bazon@gmail.com> http://mihai.bazon.net/blog Distributed under the BSD license: Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************/ "use strict"; (function(){ var MOZ_TO_ME = { ExpressionStatement: function(M) { var expr = M.expression; if (expr.type === "Literal" && typeof expr.value === "string") { return new AST_Directive({ start: my_start_token(M), end: my_end_token(M), value: expr.value }); } return new AST_SimpleStatement({ start: my_start_token(M), end: my_end_token(M), body: from_moz(expr) }); }, TryStatement: function(M) { var handlers = M.handlers || [M.handler]; if (handlers.length > 1 || M.guardedHandlers && M.guardedHandlers.length) { throw new Error("Multiple catch clauses are not supported."); } return new AST_Try({ start : my_start_token(M), end : my_end_token(M), body : from_moz(M.block).body, bcatch : from_moz(handlers[0]), bfinally : M.finalizer ? new AST_Finally(from_moz(M.finalizer)) : null }); }, Property: function(M) { var key = M.key; var name = key.type == "Identifier" ? key.name : key.value; var args = { start : my_start_token(key), end : my_end_token(M.value), key : name, value : from_moz(M.value) }; switch (M.kind) { case "init": return new AST_ObjectKeyVal(args); case "set": args.value.name = from_moz(key); return new AST_ObjectSetter(args); case "get": args.value.name = from_moz(key); return new AST_ObjectGetter(args); } }, ObjectExpression: function(M) { return new AST_Object({ start : my_start_token(M), end : my_end_token(M), properties : M.properties.map(function(prop){ prop.type = "Property"; return from_moz(prop) }) }); }, SequenceExpression: function(M) { return AST_Seq.from_array(M.expressions.map(from_moz)); }, MemberExpression: function(M) { return new (M.computed ? AST_Sub : AST_Dot)({ start : my_start_token(M), end : my_end_token(M), property : M.computed ? from_moz(M.property) : M.property.name, expression : from_moz(M.object) }); }, SwitchCase: function(M) { return new (M.test ? AST_Case : AST_Default)({ start : my_start_token(M), end : my_end_token(M), expression : from_moz(M.test), body : M.consequent.map(from_moz) }); }, VariableDeclaration: function(M) { return new (M.kind === "const" ? AST_Const : AST_Var)({ start : my_start_token(M), end : my_end_token(M), definitions : M.declarations.map(from_moz) }); }, Literal: function(M) { var val = M.value, args = { start : my_start_token(M), end : my_end_token(M) }; if (val === null) return new AST_Null(args); switch (typeof val) { case "string": args.value = val; return new AST_String(args); case "number": args.value = val; return new AST_Number(args); case "boolean": return new (val ? AST_True : AST_False)(args); default: var rx = M.regex; if (rx && rx.pattern) { // RegExpLiteral as per ESTree AST spec args.value = new RegExp(rx.pattern, rx.flags).toString(); } else { // support legacy RegExp args.value = M.regex && M.raw ? M.raw : val; } return new AST_RegExp(args); } }, Identifier: function(M) { var p = FROM_MOZ_STACK[FROM_MOZ_STACK.length - 2]; return new ( p.type == "LabeledStatement" ? AST_Label : p.type == "VariableDeclarator" && p.id === M ? (p.kind == "const" ? AST_SymbolConst : AST_SymbolVar) : p.type == "FunctionExpression" ? (p.id === M ? AST_SymbolLambda : AST_SymbolFunarg) : p.type == "FunctionDeclaration" ? (p.id === M ? AST_SymbolDefun : AST_SymbolFunarg) : p.type == "CatchClause" ? AST_SymbolCatch : p.type == "BreakStatement" || p.type == "ContinueStatement" ? AST_LabelRef : AST_SymbolRef)({ start : my_start_token(M), end : my_end_token(M), name : M.name }); } }; MOZ_TO_ME.UpdateExpression = MOZ_TO_ME.UnaryExpression = function To_Moz_Unary(M) { var prefix = "prefix" in M ? M.prefix : M.type == "UnaryExpression" ? true : false; return new (prefix ? AST_UnaryPrefix : AST_UnaryPostfix)({ start : my_start_token(M), end : my_end_token(M), operator : M.operator, expression : from_moz(M.argument) }); }; map("Program", AST_Toplevel, "body@body"); map("EmptyStatement", AST_EmptyStatement); map("BlockStatement", AST_BlockStatement, "body@body"); map("IfStatement", AST_If, "test>condition, consequent>body, alternate>alternative"); map("LabeledStatement", AST_LabeledStatement, "label>label, body>body"); map("BreakStatement", AST_Break, "label>label"); map("ContinueStatement", AST_Continue, "label>label"); map("WithStatement", AST_With, "object>expression, body>body"); map("SwitchStatement", AST_Switch, "discriminant>expression, cases@body"); map("ReturnStatement", AST_Return, "argument>value"); map("ThrowStatement", AST_Throw, "argument>value"); map("WhileStatement", AST_While, "test>condition, body>body"); map("DoWhileStatement", AST_Do, "test>condition, body>body"); map("ForStatement", AST_For, "init>init, test>condition, update>step, body>body"); map("ForInStatement", AST_ForIn, "left>init, right>object, body>body"); map("DebuggerStatement", AST_Debugger); map("FunctionDeclaration", AST_Defun, "id>name, params@argnames, body%body"); map("VariableDeclarator", AST_VarDef, "id>name, init>value"); map("CatchClause", AST_Catch, "param>argname, body%body"); map("ThisExpression", AST_This); map("ArrayExpression", AST_Array, "elements@elements"); map("FunctionExpression", AST_Function, "id>name, params@argnames, body%body"); map("BinaryExpression", AST_Binary, "operator=operator, left>left, right>right"); map("LogicalExpression", AST_Binary, "operator=operator, left>left, right>right"); map("AssignmentExpression", AST_Assign, "operator=operator, left>left, right>right"); map("ConditionalExpression", AST_Conditional, "test>condition, consequent>consequent, alternate>alternative"); map("NewExpression", AST_New, "callee>expression, arguments@args"); map("CallExpression", AST_Call, "callee>expression, arguments@args"); def_to_moz(AST_Directive, function To_Moz_Directive(M) { return { type: "ExpressionStatement", expression: { type: "Literal", value: M.value } }; }); def_to_moz(AST_SimpleStatement, function To_Moz_ExpressionStatement(M) { return { type: "ExpressionStatement", expression: to_moz(M.body) }; }); def_to_moz(AST_SwitchBranch, function To_Moz_SwitchCase(M) { return { type: "SwitchCase", test: to_moz(M.expression), consequent: M.body.map(to_moz) }; }); def_to_moz(AST_Try, function To_Moz_TryStatement(M) { return { type: "TryStatement", block: to_moz_block(M), handler: to_moz(M.bcatch), guardedHandlers: [], finalizer: to_moz(M.bfinally) }; }); def_to_moz(AST_Catch, function To_Moz_CatchClause(M) { return { type: "CatchClause", param: to_moz(M.argname), guard: null, body: to_moz_block(M) }; }); def_to_moz(AST_Definitions, function To_Moz_VariableDeclaration(M) { return { type: "VariableDeclaration", kind: M instanceof AST_Const ? "const" : "var", declarations: M.definitions.map(to_moz) }; }); def_to_moz(AST_Seq, function To_Moz_SequenceExpression(M) { return { type: "SequenceExpression", expressions: M.to_array().map(to_moz) }; }); def_to_moz(AST_PropAccess, function To_Moz_MemberExpression(M) { var isComputed = M instanceof AST_Sub; return { type: "MemberExpression", object: to_moz(M.expression), computed: isComputed, property: isComputed ? to_moz(M.property) : {type: "Identifier", name: M.property} }; }); def_to_moz(AST_Unary, function To_Moz_Unary(M) { return { type: M.operator == "++" || M.operator == "--" ? "UpdateExpression" : "UnaryExpression", operator: M.operator, prefix: M instanceof AST_UnaryPrefix, argument: to_moz(M.expression) }; }); def_to_moz(AST_Binary, function To_Moz_BinaryExpression(M) { return { type: M.operator == "&&" || M.operator == "||" ? "LogicalExpression" : "BinaryExpression", left: to_moz(M.left), operator: M.operator, right: to_moz(M.right) }; }); def_to_moz(AST_Object, function To_Moz_ObjectExpression(M) { return { type: "ObjectExpression", properties: M.properties.map(to_moz) }; }); def_to_moz(AST_ObjectProperty, function To_Moz_Property(M) { var key = ( is_identifier(M.key) ? {type: "Identifier", name: M.key} : {type: "Literal", value: M.key} ); var kind; if (M instanceof AST_ObjectKeyVal) { kind = "init"; } else if (M instanceof AST_ObjectGetter) { kind = "get"; } else if (M instanceof AST_ObjectSetter) { kind = "set"; } return { type: "Property", kind: kind, key: key, value: to_moz(M.value) }; }); def_to_moz(AST_Symbol, function To_Moz_Identifier(M) { var def = M.definition(); return { type: "Identifier", name: def ? def.mangled_name || def.name : M.name }; }); def_to_moz(AST_RegExp, function To_Moz_RegExpLiteral(M) { var value = M.value; return { type: "Literal", value: value, raw: value.toString(), regex: { pattern: value.source, flags: value.toString().match(/[gimuy]*$/)[0] } }; }); def_to_moz(AST_Constant, function To_Moz_Literal(M) { var value = M.value; if (typeof value === 'number' && (value < 0 || (value === 0 && 1 / value < 0))) { return { type: "UnaryExpression", operator: "-", prefix: true, argument: { type: "Literal", value: -value, raw: M.start.raw } }; } return { type: "Literal", value: value, raw: M.start.raw }; }); def_to_moz(AST_Atom, function To_Moz_Atom(M) { return { type: "Identifier", name: String(M.value) }; }); AST_Boolean.DEFMETHOD("to_mozilla_ast", AST_Constant.prototype.to_mozilla_ast); AST_Null.DEFMETHOD("to_mozilla_ast", AST_Constant.prototype.to_mozilla_ast); AST_Hole.DEFMETHOD("to_mozilla_ast", function To_Moz_ArrayHole() { return null }); AST_Block.DEFMETHOD("to_mozilla_ast", AST_BlockStatement.prototype.to_mozilla_ast); AST_Lambda.DEFMETHOD("to_mozilla_ast", AST_Function.prototype.to_mozilla_ast); /* -----[ tools ]----- */ function raw_token(moznode) { if (moznode.type == "Literal") { return moznode.raw != null ? moznode.raw : moznode.value + ""; } } function my_start_token(moznode) { var loc = moznode.loc, start = loc && loc.start; var range = moznode.range; return new AST_Token({ file : loc && loc.source, line : start && start.line, col : start && start.column, pos : range ? range[0] : moznode.start, endline : start && start.line, endcol : start && start.column, endpos : range ? range[0] : moznode.start, raw : raw_token(moznode), }); }; function my_end_token(moznode) { var loc = moznode.loc, end = loc && loc.end; var range = moznode.range; return new AST_Token({ file : loc && loc.source, line : end && end.line, col : end && end.column, pos : range ? range[1] : moznode.end, endline : end && end.line, endcol : end && end.column, endpos : range ? range[1] : moznode.end, raw : raw_token(moznode), }); }; function map(moztype, mytype, propmap) { var moz_to_me = "function From_Moz_" + moztype + "(M){\n"; moz_to_me += "return new U2." + mytype.name + "({\n" + "start: my_start_token(M),\n" + "end: my_end_token(M)"; var me_to_moz = "function To_Moz_" + moztype + "(M){\n"; me_to_moz += "return {\n" + "type: " + JSON.stringify(moztype); if (propmap) propmap.split(/\s*,\s*/).forEach(function(prop){ var m = /([a-z0-9$_]+)(=|@|>|%)([a-z0-9$_]+)/i.exec(prop); if (!m) throw new Error("Can't understand property map: " + prop); var moz = m[1], how = m[2], my = m[3]; moz_to_me += ",\n" + my + ": "; me_to_moz += ",\n" + moz + ": "; switch (how) { case "@": moz_to_me += "M." + moz + ".map(from_moz)"; me_to_moz += "M." + my + ".map(to_moz)"; break; case ">": moz_to_me += "from_moz(M." + moz + ")"; me_to_moz += "to_moz(M." + my + ")"; break; case "=": moz_to_me += "M." + moz; me_to_moz += "M." + my; break; case "%": moz_to_me += "from_moz(M." + moz + ").body"; me_to_moz += "to_moz_block(M)"; break; default: throw new Error("Can't understand operator in propmap: " + prop); } }); moz_to_me += "\n})\n}"; me_to_moz += "\n}\n}"; //moz_to_me = parse(moz_to_me).print_to_string({ beautify: true }); //me_to_moz = parse(me_to_moz).print_to_string({ beautify: true }); //console.log(moz_to_me); moz_to_me = new Function("U2", "my_start_token", "my_end_token", "from_moz", "return(" + moz_to_me + ")")( exports, my_start_token, my_end_token, from_moz ); me_to_moz = new Function("to_moz", "to_moz_block", "return(" + me_to_moz + ")")( to_moz, to_moz_block ); MOZ_TO_ME[moztype] = moz_to_me; def_to_moz(mytype, me_to_moz); }; var FROM_MOZ_STACK = null; function from_moz(node) { FROM_MOZ_STACK.push(node); var ret = node != null ? MOZ_TO_ME[node.type](node) : null; FROM_MOZ_STACK.pop(); return ret; }; AST_Node.from_mozilla_ast = function(node){ var save_stack = FROM_MOZ_STACK; FROM_MOZ_STACK = []; var ast = from_moz(node); FROM_MOZ_STACK = save_stack; return ast; }; function set_moz_loc(mynode, moznode, myparent) { var start = mynode.start; var end = mynode.end; if (start.pos != null && end.endpos != null) { moznode.range = [start.pos, end.endpos]; } if (start.line) { moznode.loc = { start: {line: start.line, column: start.col}, end: end.endline ? {line: end.endline, column: end.endcol} : null }; if (start.file) { moznode.loc.source = start.file; } } return moznode; }; function def_to_moz(mytype, handler) { mytype.DEFMETHOD("to_mozilla_ast", function() { return set_moz_loc(this, handler(this)); }); }; function to_moz(node) { return node != null ? node.to_mozilla_ast() : null; }; function to_moz_block(node) { return { type: "BlockStatement", body: node.body.map(to_moz) }; }; })(); /*********************************************************************** A JavaScript tokenizer / parser / beautifier / compressor. https://github.com/mishoo/UglifyJS2 -------------------------------- (C) --------------------------------- Author: Mihai Bazon <mihai.bazon@gmail.com> http://mihai.bazon.net/blog Distributed under the BSD license: Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************/ "use strict"; function find_builtins() { var a = []; [ Object, Array, Function, Number, String, Boolean, Error, Math, Date, RegExp ].forEach(function(ctor){ Object.getOwnPropertyNames(ctor).map(add); if (ctor.prototype) { Object.getOwnPropertyNames(ctor.prototype).map(add); } }); function add(name) { push_uniq(a, name); } return a; } function mangle_properties(ast, options) { options = defaults(options, { reserved : null, cache : null, only_cache : false, regex : null }); var reserved = options.reserved; if (reserved == null) reserved = find_builtins(); var cache = options.cache; if (cache == null) { cache = { cname: -1, props: new Dictionary() }; } var regex = options.regex; var names_to_mangle = []; var unmangleable = []; // step 1: find candidates to mangle ast.walk(new TreeWalker(function(node){ if (node instanceof AST_ObjectKeyVal) { add(node.key); } else if (node instanceof AST_ObjectProperty) { // setter or getter, since KeyVal is handled above add(node.key.name); } else if (node instanceof AST_Dot) { if (this.parent() instanceof AST_Assign) { add(node.property); } } else if (node instanceof AST_Sub) { if (this.parent() instanceof AST_Assign) { addStrings(node.property); } } })); // step 2: transform the tree, renaming properties return ast.transform(new TreeTransformer(function(node){ if (node instanceof AST_ObjectKeyVal) { node.key = mangle(node.key); } else if (node instanceof AST_ObjectProperty) { // setter or getter node.key.name = mangle(node.key.name); } else if (node instanceof AST_Dot) { node.property = mangle(node.property); } else if (node instanceof AST_Sub) { node.property = mangleStrings(node.property); } // else if (node instanceof AST_String) { // if (should_mangle(node.value)) { // AST_Node.warn( // "Found \"{prop}\" property candidate for mangling in an arbitrary string [{file}:{line},{col}]", { // file : node.start.file, // line : node.start.line, // col : node.start.col, // prop : node.value // } // ); // } // } })); // only function declarations after this line function can_mangle(name) { if (unmangleable.indexOf(name) >= 0) return false; if (reserved.indexOf(name) >= 0) return false; if (options.only_cache) { return cache.props.has(name); } if (/^[0-9.]+$/.test(name)) return false; return true; } function should_mangle(name) { if (regex && !regex.test(name)) return false; if (reserved.indexOf(name) >= 0) return false; return cache.props.has(name) || names_to_mangle.indexOf(name) >= 0; } function add(name) { if (can_mangle(name)) push_uniq(names_to_mangle, name); if (!should_mangle(name)) { push_uniq(unmangleable, name); } } function mangle(name) { if (!should_mangle(name)) { return name; } var mangled = cache.props.get(name); if (!mangled) { do { mangled = base54(++cache.cname); } while (!can_mangle(mangled)); cache.props.set(name, mangled); } return mangled; } function addStrings(node) { var out = {}; try { (function walk(node){ node.walk(new TreeWalker(function(node){ if (node instanceof AST_Seq) { walk(node.cdr); return true; } if (node instanceof AST_String) { add(node.value); return true; } if (node instanceof AST_Conditional) { walk(node.consequent); walk(node.alternative); return true; } throw out; })); })(node); } catch(ex) { if (ex !== out) throw ex; } } function mangleStrings(node) { return node.transform(new TreeTransformer(function(node){ if (node instanceof AST_Seq) { node.cdr = mangleStrings(node.cdr); } else if (node instanceof AST_String) { node.value = mangle(node.value); } else if (node instanceof AST_Conditional) { node.consequent = mangleStrings(node.consequent); node.alternative = mangleStrings(node.alternative); } return node; })); } } AST_Node.warn_function = function(txt) { logger.error("uglifyjs2 WARN: " + txt); }; exports.minify = function(files, options, name) { options = defaults(options, { spidermonkey : false, outSourceMap : null, sourceRoot : null, inSourceMap : null, fromString : false, warnings : false, mangle : {}, output : null, compress : {} }); base54.reset(); // 1. parse var toplevel = null, sourcesContent = {}; if (options.spidermonkey) { toplevel = AST_Node.from_mozilla_ast(files); } else { if (typeof files == "string") files = [ files ]; files.forEach(function(file, i){ var code = options.fromString ? file : rjsFile.readFile(file, "utf8"); sourcesContent[file] = code; toplevel = parse(code, { filename: options.fromString ? name : file, toplevel: toplevel }); }); } if (options.wrap) { toplevel = toplevel.wrap_commonjs(options.wrap, options.exportAll); } // 2. compress if (options.compress) { var compress = { warnings: options.warnings }; merge(compress, options.compress); toplevel.figure_out_scope(); var sq = Compressor(compress); toplevel = toplevel.transform(sq); } // 3. mangle if (options.mangle) { toplevel.figure_out_scope(options.mangle); toplevel.compute_char_frequency(options.mangle); toplevel.mangle_names(options.mangle); } // 4. output var inMap = options.inSourceMap; var output = {}; if (typeof options.inSourceMap == "string") { inMap = rjsFile.readFile(options.inSourceMap, "utf8"); } if (options.outSourceMap) { output.source_map = SourceMap({ file: options.outSourceMap, orig: inMap, root: options.sourceRoot }); if (options.sourceMapIncludeSources) { for (var file in sourcesContent) { if (sourcesContent.hasOwnProperty(file)) { output.source_map.get().setSourceContent(file, sourcesContent[file]); } } } } if (options.output) { merge(output, options.output); } var stream = OutputStream(output); toplevel.print(stream); if (options.outSourceMap && "string" === typeof options.outSourceMap) { stream += "\n//# sourceMappingURL=" + options.outSourceMap; } var source_map = output.source_map; if (source_map) { source_map = source_map + ""; } return { code : stream + "", map : source_map }; }; // exports.describe_ast = function() { // function doitem(ctor) { // var sub = {}; // ctor.SUBCLASSES.forEach(function(ctor){ // sub[ctor.TYPE] = doitem(ctor); // }); // var ret = {}; // if (ctor.SELF_PROPS.length > 0) ret.props = ctor.SELF_PROPS; // if (ctor.SUBCLASSES.length > 0) ret.sub = sub; // return ret; // } // return doitem(AST_Node).sub; // } exports.describe_ast = function() { var out = OutputStream({ beautify: true }); function doitem(ctor) { out.print("AST_" + ctor.TYPE); var props = ctor.SELF_PROPS.filter(function(prop){ return !/^\$/.test(prop); }); if (props.length > 0) { out.space(); out.with_parens(function(){ props.forEach(function(prop, i){ if (i) out.space(); out.print(prop); }); }); } if (ctor.documentation) { out.space(); out.print_string(ctor.documentation); } if (ctor.SUBCLASSES.length > 0) { out.space(); out.with_block(function(){ ctor.SUBCLASSES.forEach(function(ctor, i){ out.indent(); doitem(ctor); out.newline(); }); }); } }; doitem(AST_Node); return out + ""; }; }); /*jslint plusplus: true */ /*global define: false */ define('parse', ['./esprimaAdapter', 'lang'], function (esprima, lang) { 'use strict'; function arrayToString(ary) { var output = '['; if (ary) { ary.forEach(function (item, i) { output += (i > 0 ? ',' : '') + '"' + lang.jsEscape(item) + '"'; }); } output += ']'; return output; } //This string is saved off because JSLint complains //about obj.arguments use, as 'reserved word' var argPropName = 'arguments', //Default object to use for "scope" checking for UMD identifiers. emptyScope = {}, mixin = lang.mixin, hasProp = lang.hasProp; //From an esprima example for traversing its ast. function traverse(object, visitor) { var child; if (!object) { return; } if (visitor.call(null, object) === false) { return false; } for (var i = 0, keys = Object.keys(object); i < keys.length; i++) { child = object[keys[i]]; if (typeof child === 'object' && child !== null) { if (traverse(child, visitor) === false) { return false; } } } } //Like traverse, but visitor returning false just //stops that subtree analysis, not the rest of tree //visiting. function traverseBroad(object, visitor) { var child; if (!object) { return; } if (visitor.call(null, object) === false) { return false; } for (var i = 0, keys = Object.keys(object); i < keys.length; i++) { child = object[key]; if (typeof child === 'object' && child !== null) { traverseBroad(child, visitor); } } } /** * Pulls out dependencies from an array literal with just string members. * If string literals, will just return those string values in an array, * skipping other items in the array. * * @param {Node} node an AST node. * * @returns {Array} an array of strings. * If null is returned, then it means the input node was not a valid * dependency. */ function getValidDeps(node) { if (!node || node.type !== 'ArrayExpression' || !node.elements) { return; } var deps = []; node.elements.some(function (elem) { if (elem.type === 'Literal') { deps.push(elem.value); } }); return deps.length ? deps : undefined; } // Detects regular or arrow function expressions as the desired expression // type. function isFnExpression(node) { return (node && (node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression')); } /** * Main parse function. Returns a string of any valid require or * define/require.def calls as part of one JavaScript source string. * @param {String} moduleName the module name that represents this file. * It is used to create a default define if there is not one already for the * file. This allows properly tracing dependencies for builds. Otherwise, if * the file just has a require() call, the file dependencies will not be * properly reflected: the file will come before its dependencies. * @param {String} moduleName * @param {String} fileName * @param {String} fileContents * @param {Object} options optional options. insertNeedsDefine: true will * add calls to require.needsDefine() if appropriate. * @returns {String} JS source string or null, if no require or * define/require.def calls are found. */ function parse(moduleName, fileName, fileContents, options) { options = options || {}; //Set up source input var i, moduleCall, depString, moduleDeps = [], result = '', moduleList = [], needsDefine = true, astRoot = esprima.parse(fileContents); parse.recurse(astRoot, function (callName, config, name, deps, node, factoryIdentifier, fnExpScope) { if (!deps) { deps = []; } if (callName === 'define' && (!name || name === moduleName)) { needsDefine = false; } if (!name) { //If there is no module name, the dependencies are for //this file/default module name. moduleDeps = moduleDeps.concat(deps); } else { moduleList.push({ name: name, deps: deps }); } if (callName === 'define' && factoryIdentifier && hasProp(fnExpScope, factoryIdentifier)) { return factoryIdentifier; } //If define was found, no need to dive deeper, unless //the config explicitly wants to dig deeper. return !!options.findNestedDependencies; }, options); if (options.insertNeedsDefine && needsDefine) { result += 'require.needsDefine("' + moduleName + '");'; } if (moduleDeps.length || moduleList.length) { for (i = 0; i < moduleList.length; i++) { moduleCall = moduleList[i]; if (result) { result += '\n'; } //If this is the main module for this file, combine any //"anonymous" dependencies (could come from a nested require //call) with this module. if (moduleCall.name === moduleName) { moduleCall.deps = moduleCall.deps.concat(moduleDeps); moduleDeps = []; } depString = arrayToString(moduleCall.deps); result += 'define("' + moduleCall.name + '",' + depString + ');'; } if (moduleDeps.length) { if (result) { result += '\n'; } depString = arrayToString(moduleDeps); result += 'define("' + moduleName + '",' + depString + ');'; } } return result || null; } parse.traverse = traverse; parse.traverseBroad = traverseBroad; parse.isFnExpression = isFnExpression; /** * Handles parsing a file recursively for require calls. * @param {Array} parentNode the AST node to start with. * @param {Function} onMatch function to call on a parse match. * @param {Object} [options] This is normally the build config options if * it is passed. * @param {Object} [fnExpScope] holds list of function expresssion * argument identifiers, set up internally, not passed in */ parse.recurse = function (object, onMatch, options, fnExpScope) { //Like traverse, but skips if branches that would not be processed //after has application that results in tests of true or false boolean //literal values. var keys, child, result, i, params, param, tempObject, hasHas = options && options.has; fnExpScope = fnExpScope || emptyScope; if (!object) { return; } //If has replacement has resulted in if(true){} or if(false){}, take //the appropriate branch and skip the other one. if (hasHas && object.type === 'IfStatement' && object.test.type && object.test.type === 'Literal') { if (object.test.value) { //Take the if branch this.recurse(object.consequent, onMatch, options, fnExpScope); } else { //Take the else branch this.recurse(object.alternate, onMatch, options, fnExpScope); } } else { result = this.parseNode(object, onMatch, fnExpScope); if (result === false) { return; } else if (typeof result === 'string') { return result; } //Build up a "scope" object that informs nested recurse calls if //the define call references an identifier that is likely a UMD //wrapped function expression argument. //Catch (function(a) {... wrappers if (object.type === 'ExpressionStatement' && object.expression && object.expression.type === 'CallExpression' && object.expression.callee && isFnExpression(object.expression.callee)) { tempObject = object.expression.callee; } // Catch !function(a) {... wrappers if (object.type === 'UnaryExpression' && object.argument && object.argument.type === 'CallExpression' && object.argument.callee && isFnExpression(object.argument.callee)) { tempObject = object.argument.callee; } if (tempObject && tempObject.params && tempObject.params.length) { params = tempObject.params; fnExpScope = mixin({}, fnExpScope, true); for (i = 0; i < params.length; i++) { param = params[i]; if (param.type === 'Identifier') { fnExpScope[param.name] = true; } } } for (i = 0, keys = Object.keys(object); i < keys.length; i++) { child = object[keys[i]]; if (typeof child === 'object' && child !== null) { result = this.recurse(child, onMatch, options, fnExpScope); if (typeof result === 'string' && hasProp(fnExpScope, result)) { //The result was still in fnExpScope so break. Otherwise, //was a return from a a tree that had a UMD definition, //but now out of that scope so keep siblings. break; } } } //Check for an identifier for a factory function identifier being //passed in as a function expression, indicating a UMD-type of //wrapping. if (typeof result === 'string') { if (hasProp(fnExpScope, result)) { //result still in scope, keep jumping out indicating the //identifier still in use. return result; } return; } } }; /** * Determines if the file defines the require/define module API. * Specifically, it looks for the `define.amd = ` expression. * @param {String} fileName * @param {String} fileContents * @returns {Boolean} */ parse.definesRequire = function (fileName, fileContents) { var foundDefine = false, foundDefineAmd = false; traverse(esprima.parse(fileContents), function (node) { // Look for a top level declaration of a define, like // var requirejs, require, define, off Program body. if (node.type === 'Program' && node.body && node.body.length) { foundDefine = node.body.some(function(bodyNode) { // var define if (bodyNode.type === 'VariableDeclaration') { var decls = bodyNode.declarations; if (decls) { var hasVarDefine = decls.some(function(declNode) { return (declNode.type === 'VariableDeclarator' && declNode.id && declNode.id.type === 'Identifier' && declNode.id.name === 'define'); }); if (hasVarDefine) { return true; } } } // function define() {} if (bodyNode.type === 'FunctionDeclaration' && bodyNode.id && bodyNode.id.type === 'Identifier' && bodyNode.id.name === 'define') { return true; } }); } // Need define variable found first, before detecting define.amd. if (foundDefine && parse.hasDefineAmd(node)) { foundDefineAmd = true; //Stop traversal return false; } }); return foundDefine && foundDefineAmd; }; /** * Finds require("") calls inside a CommonJS anonymous module wrapped in a * define(function(require, exports, module){}) wrapper. These dependencies * will be added to a modified define() call that lists the dependencies * on the outside of the function. * @param {String} fileName * @param {String|Object} fileContents: a string of contents, or an already * parsed AST tree. * @returns {Array} an array of module names that are dependencies. Always * returns an array, but could be of length zero. */ parse.getAnonDeps = function (fileName, fileContents) { var astRoot = typeof fileContents === 'string' ? esprima.parse(fileContents) : fileContents, defFunc = this.findAnonDefineFactory(astRoot); return parse.getAnonDepsFromNode(defFunc); }; /** * Finds require("") calls inside a CommonJS anonymous module wrapped * in a define function, given an AST node for the definition function. * @param {Node} node the AST node for the definition function. * @returns {Array} and array of dependency names. Can be of zero length. */ parse.getAnonDepsFromNode = function (node) { var deps = [], funcArgLength; if (node) { this.findRequireDepNames(node, deps); //If no deps, still add the standard CommonJS require, exports, //module, in that order, to the deps, but only if specified as //function args. In particular, if exports is used, it is favored //over the return value of the function, so only add it if asked. funcArgLength = node.params && node.params.length; if (funcArgLength) { deps = (funcArgLength > 1 ? ["require", "exports", "module"] : ["require"]).concat(deps); } } return deps; }; parse.isDefineNodeWithArgs = function (node) { return node && node.type === 'CallExpression' && node.callee && node.callee.type === 'Identifier' && node.callee.name === 'define' && node[argPropName]; }; /** * Finds the function in define(function (require, exports, module){}); * @param {Array} node * @returns {Boolean} */ parse.findAnonDefineFactory = function (node) { var match; traverse(node, function (node) { var arg0, arg1; if (parse.isDefineNodeWithArgs(node)) { //Just the factory function passed to define arg0 = node[argPropName][0]; if (isFnExpression(arg0)) { match = arg0; return false; } //A string literal module ID followed by the factory function. arg1 = node[argPropName][1]; if (arg0.type === 'Literal' && isFnExpression(arg1)) { match = arg1; return false; } } }); return match; }; /** * Finds any config that is passed to requirejs. That includes calls to * require/requirejs.config(), as well as require({}, ...) and * requirejs({}, ...) * @param {String} fileContents * * @returns {Object} a config details object with the following properties: * - config: {Object} the config object found. Can be undefined if no * config found. * - range: {Array} the start index and end index in the contents where * the config was found. Can be undefined if no config found. * Can throw an error if the config in the file cannot be evaluated in * a build context to valid JavaScript. */ parse.findConfig = function (fileContents) { /*jslint evil: true */ var jsConfig, foundConfig, stringData, foundRange, quote, quoteMatch, quoteRegExp = /(:\s|\[\s*)(['"])/, astRoot = esprima.parse(fileContents, { loc: true }); traverse(astRoot, function (node) { var arg, requireType = parse.hasRequire(node); if (requireType && (requireType === 'require' || requireType === 'requirejs' || requireType === 'requireConfig' || requireType === 'requirejsConfig')) { arg = node[argPropName] && node[argPropName][0]; if (arg && arg.type === 'ObjectExpression') { stringData = parse.nodeToString(fileContents, arg); jsConfig = stringData.value; foundRange = stringData.range; return false; } } else { arg = parse.getRequireObjectLiteral(node); if (arg) { stringData = parse.nodeToString(fileContents, arg); jsConfig = stringData.value; foundRange = stringData.range; return false; } } }); if (jsConfig) { // Eval the config quoteMatch = quoteRegExp.exec(jsConfig); quote = (quoteMatch && quoteMatch[2]) || '"'; foundConfig = eval('(' + jsConfig + ')'); } return { config: foundConfig, range: foundRange, quote: quote }; }; /** Returns the node for the object literal assigned to require/requirejs, * for holding a declarative config. */ parse.getRequireObjectLiteral = function (node) { if (node.id && node.id.type === 'Identifier' && (node.id.name === 'require' || node.id.name === 'requirejs') && node.init && node.init.type === 'ObjectExpression') { return node.init; } }; /** * Renames require/requirejs/define calls to be ns + '.' + require/requirejs/define * Does *not* do .config calls though. See pragma.namespace for the complete * set of namespace transforms. This function is used because require calls * inside a define() call should not be renamed, so a simple regexp is not * good enough. * @param {String} fileContents the contents to transform. * @param {String} ns the namespace, *not* including trailing dot. * @return {String} the fileContents with the namespace applied */ parse.renameNamespace = function (fileContents, ns) { var lines, locs = [], astRoot = esprima.parse(fileContents, { loc: true }); parse.recurse(astRoot, function (callName, config, name, deps, node) { locs.push(node.loc); //Do not recurse into define functions, they should be using //local defines. return callName !== 'define'; }, {}); if (locs.length) { lines = fileContents.split('\n'); //Go backwards through the found locs, adding in the namespace name //in front. locs.reverse(); locs.forEach(function (loc) { var startIndex = loc.start.column, //start.line is 1-based, not 0 based. lineIndex = loc.start.line - 1, line = lines[lineIndex]; lines[lineIndex] = line.substring(0, startIndex) + ns + '.' + line.substring(startIndex, line.length); }); fileContents = lines.join('\n'); } return fileContents; }; /** * Finds all dependencies specified in dependency arrays and inside * simplified commonjs wrappers. * @param {String} fileName * @param {String} fileContents * * @returns {Array} an array of dependency strings. The dependencies * have not been normalized, they may be relative IDs. */ parse.findDependencies = function (fileName, fileContents, options) { var dependencies = [], astRoot = esprima.parse(fileContents); parse.recurse(astRoot, function (callName, config, name, deps) { if (deps) { dependencies = dependencies.concat(deps); } }, options); return dependencies; }; /** * Finds only CJS dependencies, ones that are the form * require('stringLiteral') */ parse.findCjsDependencies = function (fileName, fileContents) { var dependencies = []; traverse(esprima.parse(fileContents), function (node) { var arg; if (node && node.type === 'CallExpression' && node.callee && node.callee.type === 'Identifier' && node.callee.name === 'require' && node[argPropName] && node[argPropName].length === 1) { arg = node[argPropName][0]; if (arg.type === 'Literal') { dependencies.push(arg.value); } } }); return dependencies; }; //function define() {} parse.hasDefDefine = function (node) { return node.type === 'FunctionDeclaration' && node.id && node.id.type === 'Identifier' && node.id.name === 'define'; }; //define.amd = ... parse.hasDefineAmd = function (node) { return node && node.type === 'AssignmentExpression' && node.left && node.left.type === 'MemberExpression' && node.left.object && node.left.object.name === 'define' && node.left.property && node.left.property.name === 'amd'; }; //define.amd reference, as in: if (define.amd) parse.refsDefineAmd = function (node) { return node && node.type === 'MemberExpression' && node.object && node.object.name === 'define' && node.object.type === 'Identifier' && node.property && node.property.name === 'amd' && node.property.type === 'Identifier'; }; //require(), requirejs(), require.config() and requirejs.config() parse.hasRequire = function (node) { var callName, c = node && node.callee; if (node && node.type === 'CallExpression' && c) { if (c.type === 'Identifier' && (c.name === 'require' || c.name === 'requirejs')) { //A require/requirejs({}, ...) call callName = c.name; } else if (c.type === 'MemberExpression' && c.object && c.object.type === 'Identifier' && (c.object.name === 'require' || c.object.name === 'requirejs') && c.property && c.property.name === 'config') { // require/requirejs.config({}) call callName = c.object.name + 'Config'; } } return callName; }; //define() parse.hasDefine = function (node) { return node && node.type === 'CallExpression' && node.callee && node.callee.type === 'Identifier' && node.callee.name === 'define'; }; /** * If there is a named define in the file, returns the name. Does not * scan for mulitple names, just the first one. */ parse.getNamedDefine = function (fileContents) { var name; traverse(esprima.parse(fileContents), function (node) { if (node && node.type === 'CallExpression' && node.callee && node.callee.type === 'Identifier' && node.callee.name === 'define' && node[argPropName] && node[argPropName][0] && node[argPropName][0].type === 'Literal') { name = node[argPropName][0].value; return false; } }); return name; }; /** * Finds all the named define module IDs in a file. */ parse.getAllNamedDefines = function (fileContents, excludeMap) { var names = []; parse.recurse(esprima.parse(fileContents), function (callName, config, name, deps, node, factoryIdentifier, fnExpScope) { if (callName === 'define' && name) { if (!excludeMap.hasOwnProperty(name)) { names.push(name); } } //If a UMD definition that points to a factory that is an Identifier, //indicate processing should not traverse inside the UMD definition. if (callName === 'define' && factoryIdentifier && hasProp(fnExpScope, factoryIdentifier)) { return factoryIdentifier; } //If define was found, no need to dive deeper, unless //the config explicitly wants to dig deeper. return true; }, {}); return names; }; /** * Determines if define(), require({}|[]) or requirejs was called in the * file. Also finds out if define() is declared and if define.amd is called. */ parse.usesAmdOrRequireJs = function (fileName, fileContents) { var uses; traverse(esprima.parse(fileContents), function (node) { var type, callName, arg; if (parse.hasDefDefine(node)) { //function define() {} type = 'declaresDefine'; } else if (parse.hasDefineAmd(node)) { type = 'defineAmd'; } else { callName = parse.hasRequire(node); if (callName) { arg = node[argPropName] && node[argPropName][0]; if (arg && (arg.type === 'ObjectExpression' || arg.type === 'ArrayExpression')) { type = callName; } } else if (parse.hasDefine(node)) { type = 'define'; } } if (type) { if (!uses) { uses = {}; } uses[type] = true; } }); return uses; }; /** * Determines if require(''), exports.x =, module.exports =, * __dirname, __filename are used. So, not strictly traditional CommonJS, * also checks for Node variants. */ parse.usesCommonJs = function (fileName, fileContents) { var uses = null, assignsExports = false; traverse(esprima.parse(fileContents), function (node) { var type, exp = node.expression || node.init; if (node.type === 'Identifier' && (node.name === '__dirname' || node.name === '__filename')) { type = node.name.substring(2); } else if (node.type === 'VariableDeclarator' && node.id && node.id.type === 'Identifier' && node.id.name === 'exports') { //Hmm, a variable assignment for exports, so does not use cjs //exports. type = 'varExports'; } else if (exp && exp.type === 'AssignmentExpression' && exp.left && exp.left.type === 'MemberExpression' && exp.left.object) { if (exp.left.object.name === 'module' && exp.left.property && exp.left.property.name === 'exports') { type = 'moduleExports'; } else if (exp.left.object.name === 'exports' && exp.left.property) { type = 'exports'; } else if (exp.left.object.type === 'MemberExpression' && exp.left.object.object.name === 'module' && exp.left.object.property.name === 'exports' && exp.left.object.property.type === 'Identifier') { type = 'moduleExports'; } } else if (node && node.type === 'CallExpression' && node.callee && node.callee.type === 'Identifier' && node.callee.name === 'require' && node[argPropName] && node[argPropName].length === 1 && node[argPropName][0].type === 'Literal') { type = 'require'; } if (type) { if (type === 'varExports') { assignsExports = true; } else if (type !== 'exports' || !assignsExports) { if (!uses) { uses = {}; } uses[type] = true; } } }); return uses; }; parse.findRequireDepNames = function (node, deps) { traverse(node, function (node) { var arg; if (node && node.type === 'CallExpression' && node.callee && node.callee.type === 'Identifier' && node.callee.name === 'require' && node[argPropName] && node[argPropName].length === 1) { arg = node[argPropName][0]; if (arg.type === 'Literal') { deps.push(arg.value); } } }); }; /** * Determines if a specific node is a valid require or define/require.def * call. * @param {Array} node * @param {Function} onMatch a function to call when a match is found. * It is passed the match name, and the config, name, deps possible args. * The config, name and deps args are not normalized. * @param {Object} fnExpScope an object whose keys are all function * expression identifiers that should be in scope. Useful for UMD wrapper * detection to avoid parsing more into the wrapped UMD code. * * @returns {String} a JS source string with the valid require/define call. * Otherwise null. */ parse.parseNode = function (node, onMatch, fnExpScope) { var name, deps, cjsDeps, arg, factory, exp, refsDefine, bodyNode, args = node && node[argPropName], callName = parse.hasRequire(node), isUmd = false; if (callName === 'require' || callName === 'requirejs') { //A plain require/requirejs call arg = node[argPropName] && node[argPropName][0]; if (arg && arg.type !== 'ArrayExpression') { if (arg.type === 'ObjectExpression') { //A config call, try the second arg. arg = node[argPropName][1]; } } deps = getValidDeps(arg); if (!deps) { return; } return onMatch("require", null, null, deps, node); } else if (parse.hasDefine(node) && args && args.length) { name = args[0]; deps = args[1]; factory = args[2]; if (name.type === 'ArrayExpression') { //No name, adjust args factory = deps; deps = name; name = null; } else if (isFnExpression(name)) { //Just the factory, no name or deps factory = name; name = deps = null; } else if (name.type === 'Identifier' && args.length === 1 && hasProp(fnExpScope, name.name)) { //define(e) where e is a UMD identifier for the factory //function. isUmd = true; factory = name; name = null; } else if (name.type !== 'Literal') { //An object literal, just null out name = deps = factory = null; } if (name && name.type === 'Literal' && deps) { if (isFnExpression(deps)) { //deps is the factory factory = deps; deps = null; } else if (deps.type === 'ObjectExpression') { //deps is object literal, null out deps = factory = null; } else if (deps.type === 'Identifier') { if (args.length === 2) { //define('id', factory) deps = factory = null; } else if (args.length === 3 && isFnExpression(factory)) { //define('id', depsIdentifier, factory) //Since identifier, cannot know the deps, but do not //error out, assume they are taken care of outside of //static parsing. deps = null; } } } if (deps && deps.type === 'ArrayExpression') { deps = getValidDeps(deps); } else if (isFnExpression(factory)) { //If no deps and a factory function, could be a commonjs sugar //wrapper, scan the function for dependencies. cjsDeps = parse.getAnonDepsFromNode(factory); if (cjsDeps.length) { deps = cjsDeps; } } else if (deps || (factory && !isUmd)) { //Does not match the shape of an AMD call. return; } //Just save off the name as a string instead of an AST object. if (name && name.type === 'Literal') { name = name.value; } return onMatch("define", null, name, deps, node, (factory && factory.type === 'Identifier' ? factory.name : undefined), fnExpScope); } else if (node.type === 'CallExpression' && node.callee && isFnExpression(node.callee) && node.callee.body && node.callee.body.body && node.callee.body.body.length === 1 && node.callee.body.body[0].type === 'IfStatement') { bodyNode = node.callee.body.body[0]; //Look for a define(Identifier) case, but only if inside an //if that has a define.amd test if (bodyNode.consequent && bodyNode.consequent.body) { exp = bodyNode.consequent.body[0]; if (exp.type === 'ExpressionStatement' && exp.expression && parse.hasDefine(exp.expression) && exp.expression.arguments && exp.expression.arguments.length === 1 && exp.expression.arguments[0].type === 'Identifier') { //Calls define(Identifier) as first statement in body. //Confirm the if test references define.amd traverse(bodyNode.test, function (node) { if (parse.refsDefineAmd(node)) { refsDefine = true; return false; } }); if (refsDefine) { return onMatch("define", null, null, null, exp.expression, exp.expression.arguments[0].name, fnExpScope); } } } } }; /** * Converts an AST node into a JS source string by extracting * the node's location from the given contents string. Assumes * esprima.parse() with loc was done. * @param {String} contents * @param {Object} node * @returns {String} a JS source string. */ parse.nodeToString = function (contents, node) { var extracted, loc = node.loc, lines = contents.split('\n'), firstLine = loc.start.line > 1 ? lines.slice(0, loc.start.line - 1).join('\n') + '\n' : '', preamble = firstLine + lines[loc.start.line - 1].substring(0, loc.start.column); if (loc.start.line === loc.end.line) { extracted = lines[loc.start.line - 1].substring(loc.start.column, loc.end.column); } else { extracted = lines[loc.start.line - 1].substring(loc.start.column) + '\n' + lines.slice(loc.start.line, loc.end.line - 1).join('\n') + '\n' + lines[loc.end.line - 1].substring(0, loc.end.column); } return { value: extracted, range: [ preamble.length, preamble.length + extracted.length ] }; }; /** * Extracts license comments from JS text. * @param {String} fileName * @param {String} contents * @returns {String} a string of license comments. */ parse.getLicenseComments = function (fileName, contents) { var commentNode, refNode, subNode, value, i, j, //xpconnect's Reflect does not support comment or range, but //prefer continued operation vs strict parity of operation, //as license comments can be expressed in other ways, like //via wrap args, or linked via sourcemaps. ast = esprima.parse(contents, { comment: true, range: true }), result = '', existsMap = {}, lineEnd = contents.indexOf('\r') === -1 ? '\n' : '\r\n'; if (ast.comments) { for (i = 0; i < ast.comments.length; i++) { commentNode = ast.comments[i]; if (commentNode.type === 'Line') { value = '//' + commentNode.value + lineEnd; refNode = commentNode; if (i + 1 >= ast.comments.length) { value += lineEnd; } else { //Look for immediately adjacent single line comments //since it could from a multiple line comment made out //of single line comments. Like this comment. for (j = i + 1; j < ast.comments.length; j++) { subNode = ast.comments[j]; if (subNode.type === 'Line' && subNode.range[0] === refNode.range[1] + 1) { //Adjacent single line comment. Collect it. value += '//' + subNode.value + lineEnd; refNode = subNode; } else { //No more single line comment blocks. Break out //and continue outer looping. break; } } value += lineEnd; i = j - 1; } } else { value = '/*' + commentNode.value + '*/' + lineEnd + lineEnd; } if (!existsMap[value] && (value.indexOf('license') !== -1 || (commentNode.type === 'Block' && value.indexOf('/*!') === 0) || value.indexOf('opyright') !== -1 || value.indexOf('(c)') !== -1)) { result += value; existsMap[value] = true; } } } return result; }; return parse; }); /*global define */ define('transform', [ './esprimaAdapter', './parse', 'logger', 'lang'], function (esprima, parse, logger, lang) { 'use strict'; var transform, baseIndentRegExp = /^([ \t]+)/, indentRegExp = /\{[\r\n]+([ \t]+)/, keyRegExp = /^[_A-Za-z]([A-Za-z\d_]*)$/, bulkIndentRegExps = { '\n': /\n/g, '\r\n': /\r\n/g }; function applyIndent(str, indent, lineReturn) { var regExp = bulkIndentRegExps[lineReturn]; return str.replace(regExp, '$&' + indent); } transform = { toTransport: function (namespace, moduleName, path, contents, onFound, options) { options = options || {}; var astRoot, contentLines, modLine, foundAnon, scanCount = 0, scanReset = false, defineInfos = [], applySourceUrl = function (contents) { if (options.useSourceUrl) { contents = 'eval("' + lang.jsEscape(contents) + '\\n//# sourceURL=' + (path.indexOf('/') === 0 ? '' : '/') + path + '");\n'; } return contents; }; try { astRoot = esprima.parse(contents, { loc: true }); } catch (e) { logger.trace('toTransport skipping ' + path + ': ' + e.toString()); return contents; } //Find the define calls and their position in the files. parse.traverse(astRoot, function (node) { var args, firstArg, firstArgLoc, factoryNode, needsId, depAction, foundId, init, sourceUrlData, range, namespaceExists = false; // If a bundle script with a define declaration, do not // parse any further at this level. Likely a built layer // by some other tool. if (node.type === 'VariableDeclarator' && node.id && node.id.name === 'define' && node.id.type === 'Identifier') { init = node.init; if (init && init.callee && init.callee.type === 'CallExpression' && init.callee.callee && init.callee.callee.type === 'Identifier' && init.callee.callee.name === 'require' && init.callee.arguments && init.callee.arguments.length === 1 && init.callee.arguments[0].type === 'Literal' && init.callee.arguments[0].value && init.callee.arguments[0].value.indexOf('amdefine') !== -1) { // the var define = require('amdefine')(module) case, // keep going in that case. } else { return false; } } namespaceExists = namespace && node.type === 'CallExpression' && node.callee && node.callee.object && node.callee.object.type === 'Identifier' && node.callee.object.name === namespace && node.callee.property.type === 'Identifier' && node.callee.property.name === 'define'; if (namespaceExists || parse.isDefineNodeWithArgs(node)) { //The arguments are where its at. args = node.arguments; if (!args || !args.length) { return; } firstArg = args[0]; firstArgLoc = firstArg.loc; if (args.length === 1) { if (firstArg.type === 'Identifier') { //The define(factory) case, but //only allow it if one Identifier arg, //to limit impact of false positives. needsId = true; depAction = 'empty'; } else if (parse.isFnExpression(firstArg)) { //define(function(){}) factoryNode = firstArg; needsId = true; depAction = 'scan'; } else if (firstArg.type === 'ObjectExpression') { //define({}); needsId = true; depAction = 'skip'; } else if (firstArg.type === 'Literal' && typeof firstArg.value === 'number') { //define('12345'); needsId = true; depAction = 'skip'; } else if (firstArg.type === 'UnaryExpression' && firstArg.operator === '-' && firstArg.argument && firstArg.argument.type === 'Literal' && typeof firstArg.argument.value === 'number') { //define('-12345'); needsId = true; depAction = 'skip'; } else if (firstArg.type === 'MemberExpression' && firstArg.object && firstArg.property && firstArg.property.type === 'Identifier') { //define(this.key); needsId = true; depAction = 'empty'; } } else if (firstArg.type === 'ArrayExpression') { //define([], ...); needsId = true; depAction = 'skip'; } else if (firstArg.type === 'Literal' && typeof firstArg.value === 'string') { //define('string', ....) //Already has an ID. needsId = false; if (args.length === 2 && parse.isFnExpression(args[1])) { //Needs dependency scanning. factoryNode = args[1]; depAction = 'scan'; } else { depAction = 'skip'; } } else { //Unknown define entity, keep looking, even //in the subtree for this node. return; } range = { foundId: foundId, needsId: needsId, depAction: depAction, namespaceExists: namespaceExists, node: node, defineLoc: node.loc, firstArgLoc: firstArgLoc, factoryNode: factoryNode, sourceUrlData: sourceUrlData }; //Only transform ones that do not have IDs. If it has an //ID but no dependency array, assume it is something like //a phonegap implementation, that has its own internal //define that cannot handle dependency array constructs, //and if it is a named module, then it means it has been //set for transport form. if (range.needsId) { if (foundAnon) { logger.trace(path + ' has more than one anonymous ' + 'define. May be a built file from another ' + 'build system like, Ender. Skipping normalization.'); defineInfos = []; return false; } else { foundAnon = range; defineInfos.push(range); } } else if (depAction === 'scan') { scanCount += 1; if (scanCount > 1) { //Just go back to an array that just has the //anon one, since this is an already optimized //file like the phonegap one. if (!scanReset) { defineInfos = foundAnon ? [foundAnon] : []; scanReset = true; } } else { defineInfos.push(range); } } } }); if (!defineInfos.length) { return applySourceUrl(contents); } //Reverse the matches, need to start from the bottom of //the file to modify it, so that the ranges are still true //further up. defineInfos.reverse(); contentLines = contents.split('\n'); modLine = function (loc, contentInsertion) { var startIndex = loc.start.column, //start.line is 1-based, not 0 based. lineIndex = loc.start.line - 1, line = contentLines[lineIndex]; contentLines[lineIndex] = line.substring(0, startIndex) + contentInsertion + line.substring(startIndex, line.length); }; defineInfos.forEach(function (info) { var deps, contentInsertion = '', depString = ''; //Do the modifications "backwards", in other words, start with the //one that is farthest down and work up, so that the ranges in the //defineInfos still apply. So that means deps, id, then namespace. if (info.needsId && moduleName) { contentInsertion += "'" + moduleName + "',"; } if (info.depAction === 'scan') { deps = parse.getAnonDepsFromNode(info.factoryNode); if (deps.length) { depString = '[' + deps.map(function (dep) { return "'" + dep + "'"; }) + ']'; } else { depString = '[]'; } depString += ','; if (info.factoryNode) { //Already have a named module, need to insert the //dependencies after the name. modLine(info.factoryNode.loc, depString); } else { contentInsertion += depString; } } if (contentInsertion) { modLine(info.firstArgLoc, contentInsertion); } //Do namespace last so that ui does not mess upthe parenRange //used above. if (namespace && !info.namespaceExists) { modLine(info.defineLoc, namespace + '.'); } //Notify any listener for the found info if (onFound) { onFound(info); } }); contents = contentLines.join('\n'); return applySourceUrl(contents); }, /** * Modify the contents of a require.config/requirejs.config call. This * call will LOSE any existing comments that are in the config string. * * @param {String} fileContents String that may contain a config call * @param {Function} onConfig Function called when the first config * call is found. It will be passed an Object which is the current * config, and the onConfig function should return an Object to use * as the config. * @return {String} the fileContents with the config changes applied. */ modifyConfig: function (fileContents, onConfig) { var details = parse.findConfig(fileContents), config = details.config; if (config) { config = onConfig(config); if (config) { return transform.serializeConfig(config, fileContents, details.range[0], details.range[1], { quote: details.quote }); } } return fileContents; }, serializeConfig: function (config, fileContents, start, end, options) { //Calculate base level of indent var indent, match, configString, outDentRegExp, baseIndent = '', startString = fileContents.substring(0, start), existingConfigString = fileContents.substring(start, end), lineReturn = existingConfigString.indexOf('\r') === -1 ? '\n' : '\r\n', lastReturnIndex = startString.lastIndexOf('\n'); //Get the basic amount of indent for the require config call. if (lastReturnIndex === -1) { lastReturnIndex = 0; } match = baseIndentRegExp.exec(startString.substring(lastReturnIndex + 1, start)); if (match && match[1]) { baseIndent = match[1]; } //Calculate internal indentation for config match = indentRegExp.exec(existingConfigString); if (match && match[1]) { indent = match[1]; } if (!indent || indent.length < baseIndent) { indent = ' '; } else { indent = indent.substring(baseIndent.length); } outDentRegExp = new RegExp('(' + lineReturn + ')' + indent, 'g'); configString = transform.objectToString(config, { indent: indent, lineReturn: lineReturn, outDentRegExp: outDentRegExp, quote: options && options.quote }); //Add in the base indenting level. configString = applyIndent(configString, baseIndent, lineReturn); return startString + configString + fileContents.substring(end); }, /** * Tries converting a JS object to a string. This will likely suck, and * is tailored to the type of config expected in a loader config call. * So, hasOwnProperty fields, strings, numbers, arrays and functions, * no weird recursively referenced stuff. * @param {Object} obj the object to convert * @param {Object} options options object with the following values: * {String} indent the indentation to use for each level * {String} lineReturn the type of line return to use * {outDentRegExp} outDentRegExp the regexp to use to outdent functions * {String} quote the quote type to use, ' or ". Optional. Default is " * @param {String} totalIndent the total indent to print for this level * @return {String} a string representation of the object. */ objectToString: function (obj, options, totalIndent) { var startBrace, endBrace, nextIndent, first = true, value = '', lineReturn = options.lineReturn, indent = options.indent, outDentRegExp = options.outDentRegExp, quote = options.quote || '"'; totalIndent = totalIndent || ''; nextIndent = totalIndent + indent; if (obj === null) { value = 'null'; } else if (obj === undefined) { value = 'undefined'; } else if (typeof obj === 'number' || typeof obj === 'boolean') { value = obj; } else if (typeof obj === 'string') { //Use double quotes in case the config may also work as JSON. value = quote + lang.jsEscape(obj) + quote; } else if (lang.isArray(obj)) { lang.each(obj, function (item, i) { value += (i !== 0 ? ',' + lineReturn : '' ) + nextIndent + transform.objectToString(item, options, nextIndent); }); startBrace = '['; endBrace = ']'; } else if (lang.isFunction(obj) || lang.isRegExp(obj)) { //The outdent regexp just helps pretty up the conversion //just in node. Rhino strips comments and does a different //indent scheme for Function toString, so not really helpful //there. value = obj.toString().replace(outDentRegExp, '$1'); } else { //An object lang.eachProp(obj, function (v, prop) { value += (first ? '': ',' + lineReturn) + nextIndent + (keyRegExp.test(prop) ? prop : quote + lang.jsEscape(prop) + quote )+ ': ' + transform.objectToString(v, options, nextIndent); first = false; }); startBrace = '{'; endBrace = '}'; } if (startBrace) { value = startBrace + lineReturn + value + lineReturn + totalIndent + endBrace; } return value; } }; return transform; }); /*jslint regexp: true, plusplus: true */ /*global define: false */ define('pragma', ['parse', 'logger'], function (parse, logger) { 'use strict'; function Temp() {} function create(obj, mixin) { Temp.prototype = obj; var temp = new Temp(), prop; //Avoid any extra memory hanging around Temp.prototype = null; if (mixin) { for (prop in mixin) { if (mixin.hasOwnProperty(prop) && !temp.hasOwnProperty(prop)) { temp[prop] = mixin[prop]; } } } return temp; // Object } var pragma = { conditionalRegExp: /(exclude|include)Start\s*\(\s*["'](\w+)["']\s*,(.*)\)/, useStrictRegExp: /(^|[^{]\r?\n)['"]use strict['"];/g, hasRegExp: /has\s*\(\s*['"]([^'"]+)['"]\s*\)/g, configRegExp: /(^|[^\.])(requirejs|require)(\.config)\s*\(/g, nsWrapRegExp: /\/\*requirejs namespace: true \*\//, apiDefRegExp: /var requirejs,\s*require,\s*define;/, defineCheckRegExp: /typeof(\s+|\s*\(\s*)define(\s*\))?\s*===?\s*["']function["']\s*&&\s*define\s*\.\s*amd/g, defineStringCheckRegExp: /typeof\s+define\s*===?\s*["']function["']\s*&&\s*define\s*\[\s*["']amd["']\s*\]/g, defineTypeFirstCheckRegExp: /\s*["']function["']\s*==(=?)\s*typeof\s+define\s*&&\s*define\s*\.\s*amd/g, defineJQueryRegExp: /typeof\s+define\s*===?\s*["']function["']\s*&&\s*define\s*\.\s*amd\s*&&\s*define\s*\.\s*amd\s*\.\s*jQuery/g, defineHasRegExp: /typeof\s+define\s*==(=)?\s*['"]function['"]\s*&&\s*typeof\s+define\.amd\s*==(=)?\s*['"]object['"]\s*&&\s*define\.amd/g, defineTernaryRegExp: /typeof\s+define\s*===?\s*['"]function["']\s*&&\s*define\s*\.\s*amd\s*\?\s*define/, defineExistsRegExp: /\s+typeof\s+define\s*!==?\s*['"]undefined["']\s*/, defineExistsAndAmdRegExp: /typeof\s+define\s*!==?\s*['"]undefined["']\s*&&\s*define\s*\.\s*amd\s*/, amdefineRegExp: /if\s*\(\s*typeof define\s*\!==\s*['"]function['"]\s*\)\s*\{\s*[^\{\}]+amdefine[^\{\}]+\}/g, removeStrict: function (contents, config) { return config.useStrict ? contents : contents.replace(pragma.useStrictRegExp, '$1'); }, namespace: function (fileContents, ns, onLifecycleName) { if (ns) { //Namespace require/define calls fileContents = fileContents.replace(pragma.configRegExp, '$1' + ns + '.$2$3('); fileContents = parse.renameNamespace(fileContents, ns); //Namespace define ternary use: fileContents = fileContents.replace(pragma.defineTernaryRegExp, "typeof " + ns + ".define === 'function' && " + ns + ".define.amd ? " + ns + ".define"); //Namespace define jquery use: fileContents = fileContents.replace(pragma.defineJQueryRegExp, "typeof " + ns + ".define === 'function' && " + ns + ".define.amd && " + ns + ".define.amd.jQuery"); //Namespace has.js define use: fileContents = fileContents.replace(pragma.defineHasRegExp, "typeof " + ns + ".define === 'function' && typeof " + ns + ".define.amd === 'object' && " + ns + ".define.amd"); //Namespace async.js define use: fileContents = fileContents.replace(pragma.defineExistsAndAmdRegExp, "typeof " + ns + ".define !== 'undefined' && " + ns + ".define.amd"); //Namespace define checks. //Do these ones last, since they are a subset of the more specific //checks above. fileContents = fileContents.replace(pragma.defineCheckRegExp, "typeof " + ns + ".define === 'function' && " + ns + ".define.amd"); fileContents = fileContents.replace(pragma.defineStringCheckRegExp, "typeof " + ns + ".define === 'function' && " + ns + ".define['amd']"); fileContents = fileContents.replace(pragma.defineTypeFirstCheckRegExp, "'function' === typeof " + ns + ".define && " + ns + ".define.amd"); fileContents = fileContents.replace(pragma.defineExistsRegExp, "typeof " + ns + ".define !== 'undefined'"); //Check for require.js with the require/define definitions if (pragma.apiDefRegExp.test(fileContents) && fileContents.indexOf("if (!" + ns + " || !" + ns + ".requirejs)") === -1) { //Wrap the file contents in a typeof check, and a function //to contain the API globals. fileContents = "var " + ns + ";(function () { if (!" + ns + " || !" + ns + ".requirejs) {\n" + "if (!" + ns + ") { " + ns + ' = {}; } else { require = ' + ns + '; }\n' + fileContents + "\n" + ns + ".requirejs = requirejs;" + ns + ".require = require;" + ns + ".define = define;\n" + "}\n}());"; } //Finally, if the file wants a special wrapper because it ties //in to the requirejs internals in a way that would not fit //the above matches, do that. Look for /*requirejs namespace: true*/ if (pragma.nsWrapRegExp.test(fileContents)) { //Remove the pragma. fileContents = fileContents.replace(pragma.nsWrapRegExp, ''); //Alter the contents. fileContents = '(function () {\n' + 'var require = ' + ns + '.require,' + 'requirejs = ' + ns + '.requirejs,' + 'define = ' + ns + '.define;\n' + fileContents + '\n}());'; } } return fileContents; }, /** * processes the fileContents for some //>> conditional statements */ process: function (fileName, fileContents, config, onLifecycleName, pluginCollector) { /*jslint evil: true */ var foundIndex = -1, startIndex = 0, lineEndIndex, conditionLine, matches, type, marker, condition, isTrue, endRegExp, endMatches, endMarkerIndex, shouldInclude, startLength, lifecycleHas, deps, i, dep, moduleName, collectorMod, lifecyclePragmas, pragmas = config.pragmas, hasConfig = config.has, //Legacy arg defined to help in dojo conversion script. Remove later //when dojo no longer needs conversion: kwArgs = pragmas; //Mix in a specific lifecycle scoped object, to allow targeting //some pragmas/has tests to only when files are saved, or at different //lifecycle events. Do not bother with kwArgs in this section, since //the old dojo kwArgs were for all points in the build lifecycle. if (onLifecycleName) { lifecyclePragmas = config['pragmas' + onLifecycleName]; lifecycleHas = config['has' + onLifecycleName]; if (lifecyclePragmas) { pragmas = create(pragmas || {}, lifecyclePragmas); } if (lifecycleHas) { hasConfig = create(hasConfig || {}, lifecycleHas); } } //Replace has references if desired if (hasConfig) { fileContents = fileContents.replace(pragma.hasRegExp, function (match, test) { if (hasConfig.hasOwnProperty(test)) { return !!hasConfig[test]; } return match; }); } if (!config.skipPragmas) { while ((foundIndex = fileContents.indexOf("//>>", startIndex)) !== -1) { //Found a conditional. Get the conditional line. lineEndIndex = fileContents.indexOf("\n", foundIndex); if (lineEndIndex === -1) { lineEndIndex = fileContents.length - 1; } //Increment startIndex past the line so the next conditional search can be done. startIndex = lineEndIndex + 1; //Break apart the conditional. conditionLine = fileContents.substring(foundIndex, lineEndIndex + 1); matches = conditionLine.match(pragma.conditionalRegExp); if (matches) { type = matches[1]; marker = matches[2]; condition = matches[3]; isTrue = false; //See if the condition is true. try { isTrue = !!eval("(" + condition + ")"); } catch (e) { throw "Error in file: " + fileName + ". Conditional comment: " + conditionLine + " failed with this error: " + e; } //Find the endpoint marker. endRegExp = new RegExp('\\/\\/\\>\\>\\s*' + type + 'End\\(\\s*[\'"]' + marker + '[\'"]\\s*\\)', "g"); endMatches = endRegExp.exec(fileContents.substring(startIndex, fileContents.length)); if (endMatches) { endMarkerIndex = startIndex + endRegExp.lastIndex - endMatches[0].length; //Find the next line return based on the match position. lineEndIndex = fileContents.indexOf("\n", endMarkerIndex); if (lineEndIndex === -1) { lineEndIndex = fileContents.length - 1; } //Should we include the segment? shouldInclude = ((type === "exclude" && !isTrue) || (type === "include" && isTrue)); //Remove the conditional comments, and optionally remove the content inside //the conditional comments. startLength = startIndex - foundIndex; fileContents = fileContents.substring(0, foundIndex) + (shouldInclude ? fileContents.substring(startIndex, endMarkerIndex) : "") + fileContents.substring(lineEndIndex + 1, fileContents.length); //Move startIndex to foundIndex, since that is the new position in the file //where we need to look for more conditionals in the next while loop pass. startIndex = foundIndex; } else { throw "Error in file: " + fileName + ". Cannot find end marker for conditional comment: " + conditionLine; } } } } //If need to find all plugin resources to optimize, do that now, //before namespacing, since the namespacing will change the API //names. //If there is a plugin collector, scan the file for plugin resources. if (config.optimizeAllPluginResources && pluginCollector) { try { deps = parse.findDependencies(fileName, fileContents); if (deps.length) { for (i = 0; i < deps.length; i++) { dep = deps[i]; if (dep.indexOf('!') !== -1) { moduleName = dep.split('!')[0]; collectorMod = pluginCollector[moduleName]; if (!collectorMod) { collectorMod = pluginCollector[moduleName] = []; } collectorMod.push(dep); } } } } catch (eDep) { logger.error('Parse error looking for plugin resources in ' + fileName + ', skipping.'); } } //Strip amdefine use for node-shared modules. if (!config.keepAmdefine) { fileContents = fileContents.replace(pragma.amdefineRegExp, ''); } //Do namespacing if (onLifecycleName === 'OnSave' && config.namespace) { fileContents = pragma.namespace(fileContents, config.namespace, onLifecycleName); } return pragma.removeStrict(fileContents, config); } }; return pragma; }); if(env === 'browser') { /*jslint strict: false */ /*global define: false */ define('browser/optimize', {}); } if(env === 'node') { /*jslint strict: false */ /*global define: false */ define('node/optimize', {}); } if(env === 'rhino') { /*jslint sloppy: true, plusplus: true */ /*global define, java, Packages, com */ define('rhino/optimize', ['logger', 'env!env/file'], function (logger, file) { //Add .reduce to Rhino so UglifyJS can run in Rhino, //inspired by https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/reduce //but rewritten for brevity, and to be good enough for use by UglifyJS. if (!Array.prototype.reduce) { Array.prototype.reduce = function (fn /*, initialValue */) { var i = 0, length = this.length, accumulator; if (arguments.length >= 2) { accumulator = arguments[1]; } else { if (length) { while (!(i in this)) { i++; } accumulator = this[i++]; } } for (; i < length; i++) { if (i in this) { accumulator = fn.call(undefined, accumulator, this[i], i, this); } } return accumulator; }; } var JSSourceFilefromCode, optimize, mapRegExp = /"file":"[^"]+"/; //Bind to Closure compiler, but if it is not available, do not sweat it. try { // Try older closure compiler that worked on Java 6 JSSourceFilefromCode = java.lang.Class.forName('com.google.javascript.jscomp.JSSourceFile').getMethod('fromCode', [java.lang.String, java.lang.String]); } catch (e) { try { // Try for newer closure compiler that needs Java 7+ JSSourceFilefromCode = java.lang.Class.forName('com.google.javascript.jscomp.SourceFile').getMethod('fromCode', [java.lang.String, java.lang.String]); } catch (e) { try { // Try Nashorn style var stringClass = Java.type("java.lang.String").class; JSSourceFilefromCode = Java.type("com.google.javascript.jscomp.SourceFile").class.getMethod("fromCode", [stringClass, stringClass]); } catch (e) {} } } //Helper for closure compiler, because of weird Java-JavaScript interactions. function closurefromCode(filename, content) { return JSSourceFilefromCode.invoke(null, [filename, content]); } function getFileWriter(fileName, encoding) { var outFile = new java.io.File(fileName), outWriter, parentDir; parentDir = outFile.getAbsoluteFile().getParentFile(); if (!parentDir.exists()) { if (!parentDir.mkdirs()) { throw "Could not create directory: " + parentDir.getAbsolutePath(); } } if (encoding) { outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile), encoding); } else { outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile)); } return new java.io.BufferedWriter(outWriter); } optimize = { closure: function (fileName, fileContents, outFileName, keepLines, config) { config = config || {}; var result, mappings, optimized, compressed, baseName, writer, outBaseName, outFileNameMap, outFileNameMapContent, srcOutFileName, concatNameMap, jscomp = Packages.com.google.javascript.jscomp, flags = Packages.com.google.common.flags, //Set up source input jsSourceFile = closurefromCode(String(fileName), String(fileContents)), sourceListArray = new java.util.ArrayList(), externList = new java.util.ArrayList(), options, option, FLAG_compilation_level, compiler, externExportsPath, Compiler = Packages.com.google.javascript.jscomp.Compiler, CommandLineRunner = Packages.com.google.javascript.jscomp.CommandLineRunner; logger.trace("Minifying file: " + fileName); baseName = (new java.io.File(fileName)).getName(); //Set up options options = new jscomp.CompilerOptions(); for (option in config.CompilerOptions) { // options are false by default and jslint wanted an if statement in this for loop if (config.CompilerOptions[option]) { options[option] = config.CompilerOptions[option]; } } options.prettyPrint = keepLines || options.prettyPrint; FLAG_compilation_level = jscomp.CompilationLevel[config.CompilationLevel || 'SIMPLE_OPTIMIZATIONS']; FLAG_compilation_level.setOptionsForCompilationLevel(options); if (config.generateSourceMaps) { mappings = new java.util.ArrayList(); mappings.add(new com.google.javascript.jscomp.SourceMap.LocationMapping(fileName, baseName + ".src.js")); options.setSourceMapLocationMappings(mappings); options.setSourceMapOutputPath(fileName + ".map"); } //If we need to pass an externs file to Closure so that it does not create aliases //for certain symbols, do so here. externList.addAll(CommandLineRunner.getDefaultExterns()); if (config.externExportsPath) { externExportsPath = config.externExportsPath; externList.add(jscomp.SourceFile.fromFile(externExportsPath)); } //Trigger the compiler Compiler.setLoggingLevel(Packages.java.util.logging.Level[config.loggingLevel || 'WARNING']); compiler = new Compiler(); //fill the sourceArrrayList; we need the ArrayList because the only overload of compile //accepting the getDefaultExterns return value (a List) also wants the sources as a List sourceListArray.add(jsSourceFile); result = compiler.compile(externList, sourceListArray, options); if (result.success) { optimized = String(compiler.toSource()); if (config.generateSourceMaps && result.sourceMap && outFileName) { outBaseName = (new java.io.File(outFileName)).getName(); srcOutFileName = outFileName + ".src.js"; outFileNameMap = outFileName + ".map"; //If previous .map file exists, move it to the ".src.js" //location. Need to update the sourceMappingURL part in the //src.js file too. if (file.exists(outFileNameMap)) { concatNameMap = outFileNameMap.replace(/\.map$/, '.src.js.map'); file.saveFile(concatNameMap, file.readFile(outFileNameMap)); file.saveFile(srcOutFileName, fileContents.replace(/\/\# sourceMappingURL=(.+).map/, '/# sourceMappingURL=$1.src.js.map')); } else { file.saveUtf8File(srcOutFileName, fileContents); } writer = getFileWriter(outFileNameMap, "utf-8"); result.sourceMap.appendTo(writer, outFileName); writer.close(); //Not sure how better to do this, but right now the .map file //leaks the full OS path in the "file" property. Manually //modify it to not do that. file.saveFile(outFileNameMap, file.readFile(outFileNameMap).replace(mapRegExp, '"file":"' + baseName + '"')); fileContents = optimized + "\n//# sourceMappingURL=" + outBaseName + ".map"; } else { fileContents = optimized; } return fileContents; } else { throw new Error('Cannot closure compile file: ' + fileName + '. Skipping it.'); } return fileContents; } }; return optimize; }); } if(env === 'xpconnect') { define('xpconnect/optimize', {}); } /*jslint plusplus: true, nomen: true, regexp: true */ /*global define: false */ define('optimize', [ 'lang', 'logger', 'env!env/optimize', 'env!env/file', 'parse', 'pragma', 'uglifyjs', 'source-map'], function (lang, logger, envOptimize, file, parse, pragma, uglify, sourceMap) { 'use strict'; var optimize, cssImportRegExp = /\@import\s+(url\()?\s*([^);]+)\s*(\))?([\w, ]*)(;)?/ig, cssCommentImportRegExp = /\/\*[^\*]*@import[^\*]*\*\//g, cssUrlRegExp = /\url\(\s*([^\)]+)\s*\)?/g, protocolRegExp = /^\w+:/, SourceMapGenerator = sourceMap.SourceMapGenerator, SourceMapConsumer =sourceMap.SourceMapConsumer; /** * If an URL from a CSS url value contains start/end quotes, remove them. * This is not done in the regexp, since my regexp fu is not that strong, * and the CSS spec allows for ' and " in the URL if they are backslash escaped. * @param {String} url */ function cleanCssUrlQuotes(url) { //Make sure we are not ending in whitespace. //Not very confident of the css regexps above that there will not be ending //whitespace. url = url.replace(/\s+$/, ""); if (url.charAt(0) === "'" || url.charAt(0) === "\"") { url = url.substring(1, url.length - 1); } return url; } function fixCssUrlPaths(fileName, path, contents, cssPrefix) { return contents.replace(cssUrlRegExp, function (fullMatch, urlMatch) { var firstChar, hasProtocol, parts, i, fixedUrlMatch = cleanCssUrlQuotes(urlMatch); fixedUrlMatch = fixedUrlMatch.replace(lang.backSlashRegExp, "/"); //Only do the work for relative URLs. Skip things that start with / or #, or have //a protocol. firstChar = fixedUrlMatch.charAt(0); hasProtocol = protocolRegExp.test(fixedUrlMatch); if (firstChar !== "/" && firstChar !== "#" && !hasProtocol) { //It is a relative URL, tack on the cssPrefix and path prefix urlMatch = cssPrefix + path + fixedUrlMatch; } else if (!hasProtocol) { logger.trace(fileName + "\n URL not a relative URL, skipping: " + urlMatch); } //Collapse .. and . parts = urlMatch.split("/"); for (i = parts.length - 1; i > 0; i--) { if (parts[i] === ".") { parts.splice(i, 1); } else if (parts[i] === "..") { if (i !== 0 && parts[i - 1] !== "..") { parts.splice(i - 1, 2); i -= 1; } } } return "url(" + parts.join("/") + ")"; }); } /** * Inlines nested stylesheets that have @import calls in them. * @param {String} fileName the file name * @param {String} fileContents the file contents * @param {String} cssImportIgnore comma delimited string of files to ignore * @param {String} cssPrefix string to be prefixed before relative URLs * @param {Object} included an object used to track the files already imported */ function flattenCss(fileName, fileContents, cssImportIgnore, cssPrefix, included, topLevel) { //Find the last slash in the name. fileName = fileName.replace(lang.backSlashRegExp, "/"); var endIndex = fileName.lastIndexOf("/"), //Make a file path based on the last slash. //If no slash, so must be just a file name. Use empty string then. filePath = (endIndex !== -1) ? fileName.substring(0, endIndex + 1) : "", //store a list of merged files importList = [], skippedList = []; //First make a pass by removing any commented out @import calls. fileContents = fileContents.replace(cssCommentImportRegExp, ''); //Make sure we have a delimited ignore list to make matching faster if (cssImportIgnore && cssImportIgnore.charAt(cssImportIgnore.length - 1) !== ",") { cssImportIgnore += ","; } fileContents = fileContents.replace(cssImportRegExp, function (fullMatch, urlStart, importFileName, urlEnd, mediaTypes) { //Only process media type "all" or empty media type rules. if (mediaTypes && ((mediaTypes.replace(/^\s\s*/, '').replace(/\s\s*$/, '')) !== "all")) { skippedList.push(fileName); return fullMatch; } importFileName = cleanCssUrlQuotes(importFileName); //Ignore the file import if it is part of an ignore list. if (cssImportIgnore && cssImportIgnore.indexOf(importFileName + ",") !== -1) { return fullMatch; } //Make sure we have a unix path for the rest of the operation. importFileName = importFileName.replace(lang.backSlashRegExp, "/"); try { //if a relative path, then tack on the filePath. //If it is not a relative path, then the readFile below will fail, //and we will just skip that import. var fullImportFileName = importFileName.charAt(0) === "/" ? importFileName : filePath + importFileName, importContents = file.readFile(fullImportFileName), importEndIndex, importPath, flat; //Skip the file if it has already been included. if (included[fullImportFileName]) { return ''; } included[fullImportFileName] = true; //Make sure to flatten any nested imports. flat = flattenCss(fullImportFileName, importContents, cssImportIgnore, cssPrefix, included); importContents = flat.fileContents; if (flat.importList.length) { importList.push.apply(importList, flat.importList); } if (flat.skippedList.length) { skippedList.push.apply(skippedList, flat.skippedList); } //Make the full import path importEndIndex = importFileName.lastIndexOf("/"); //Make a file path based on the last slash. //If no slash, so must be just a file name. Use empty string then. importPath = (importEndIndex !== -1) ? importFileName.substring(0, importEndIndex + 1) : ""; //fix url() on relative import (#5) importPath = importPath.replace(/^\.\//, ''); //Modify URL paths to match the path represented by this file. importContents = fixCssUrlPaths(importFileName, importPath, importContents, cssPrefix); importList.push(fullImportFileName); return importContents; } catch (e) { logger.warn(fileName + "\n Cannot inline css import, skipping: " + importFileName); return fullMatch; } }); if (cssPrefix && topLevel) { //Modify URL paths to match the path represented by this file. fileContents = fixCssUrlPaths(fileName, '', fileContents, cssPrefix); } return { importList : importList, skippedList: skippedList, fileContents : fileContents }; } optimize = { /** * Optimizes a file that contains JavaScript content. Optionally collects * plugin resources mentioned in a file, and then passes the content * through an minifier if one is specified via config.optimize. * * @param {String} fileName the name of the file to optimize * @param {String} fileContents the contents to optimize. If this is * a null value, then fileName will be used to read the fileContents. * @param {String} outFileName the name of the file to use for the * saved optimized content. * @param {Object} config the build config object. * @param {Array} [pluginCollector] storage for any plugin resources * found. */ jsFile: function (fileName, fileContents, outFileName, config, pluginCollector) { if (!fileContents) { fileContents = file.readFile(fileName); } fileContents = optimize.js(fileName, fileContents, outFileName, config, pluginCollector); file.saveUtf8File(outFileName, fileContents); }, /** * Optimizes a file that contains JavaScript content. Optionally collects * plugin resources mentioned in a file, and then passes the content * through an minifier if one is specified via config.optimize. * * @param {String} fileName the name of the file that matches the * fileContents. * @param {String} fileContents the string of JS to optimize. * @param {Object} [config] the build config object. * @param {Array} [pluginCollector] storage for any plugin resources * found. */ js: function (fileName, fileContents, outFileName, config, pluginCollector) { var optFunc, optConfig, parts = (String(config.optimize)).split('.'), optimizerName = parts[0], keepLines = parts[1] === 'keepLines', licenseContents = ''; config = config || {}; //Apply pragmas/namespace renaming fileContents = pragma.process(fileName, fileContents, config, 'OnSave', pluginCollector); //Optimize the JS files if asked. if (optimizerName && optimizerName !== 'none') { optFunc = envOptimize[optimizerName] || optimize.optimizers[optimizerName]; if (!optFunc) { throw new Error('optimizer with name of "' + optimizerName + '" not found for this environment'); } optConfig = config[optimizerName] || {}; if (config.generateSourceMaps) { optConfig.generateSourceMaps = !!config.generateSourceMaps; optConfig._buildSourceMap = config._buildSourceMap; } try { if (config.preserveLicenseComments) { //Pull out any license comments for prepending after optimization. try { licenseContents = parse.getLicenseComments(fileName, fileContents); } catch (e) { throw new Error('Cannot parse file: ' + fileName + ' for comments. Skipping it. Error is:\n' + e.toString()); } } fileContents = licenseContents + optFunc(fileName, fileContents, outFileName, keepLines, optConfig); if (optConfig._buildSourceMap && optConfig._buildSourceMap !== config._buildSourceMap) { config._buildSourceMap = optConfig._buildSourceMap; } } catch (e) { if (config.throwWhen && config.throwWhen.optimize) { throw e; } else { logger.error(e); } } } else { if (config._buildSourceMap) { config._buildSourceMap = null; } } return fileContents; }, /** * Optimizes one CSS file, inlining @import calls, stripping comments, and * optionally removes line returns. * @param {String} fileName the path to the CSS file to optimize * @param {String} outFileName the path to save the optimized file. * @param {Object} config the config object with the optimizeCss and * cssImportIgnore options. */ cssFile: function (fileName, outFileName, config) { //Read in the file. Make sure we have a JS string. var originalFileContents = file.readFile(fileName), flat = flattenCss(fileName, originalFileContents, config.cssImportIgnore, config.cssPrefix, {}, true), //Do not use the flattened CSS if there was one that was skipped. fileContents = flat.skippedList.length ? originalFileContents : flat.fileContents, startIndex, endIndex, buildText, comment; if (flat.skippedList.length) { logger.warn('Cannot inline @imports for ' + fileName + ',\nthe following files had media queries in them:\n' + flat.skippedList.join('\n')); } //Do comment removal. try { if (config.optimizeCss.indexOf(".keepComments") === -1) { startIndex = 0; //Get rid of comments. while ((startIndex = fileContents.indexOf("/*", startIndex)) !== -1) { endIndex = fileContents.indexOf("*/", startIndex + 2); if (endIndex === -1) { throw "Improper comment in CSS file: " + fileName; } comment = fileContents.substring(startIndex, endIndex); if (config.preserveLicenseComments && (comment.indexOf('license') !== -1 || comment.indexOf('opyright') !== -1 || comment.indexOf('(c)') !== -1)) { //Keep the comment, just increment the startIndex startIndex = endIndex; } else { fileContents = fileContents.substring(0, startIndex) + fileContents.substring(endIndex + 2, fileContents.length); startIndex = 0; } } } //Get rid of newlines. if (config.optimizeCss.indexOf(".keepLines") === -1) { fileContents = fileContents.replace(/[\r\n]/g, " "); fileContents = fileContents.replace(/\s+/g, " "); fileContents = fileContents.replace(/\{\s/g, "{"); fileContents = fileContents.replace(/\s\}/g, "}"); } else { //Remove multiple empty lines. fileContents = fileContents.replace(/(\r\n)+/g, "\r\n"); fileContents = fileContents.replace(/(\n)+/g, "\n"); } //Remove unnecessary whitespace if (config.optimizeCss.indexOf(".keepWhitespace") === -1) { //Remove leading and trailing whitespace from lines fileContents = fileContents.replace(/^[ \t]+/gm, ""); fileContents = fileContents.replace(/[ \t]+$/gm, ""); //Remove whitespace after semicolon, colon, curly brackets and commas fileContents = fileContents.replace(/(;|:|\{|}|,)[ \t]+/g, "$1"); //Remove whitespace before opening curly brackets fileContents = fileContents.replace(/[ \t]+(\{)/g, "$1"); //Truncate double whitespace fileContents = fileContents.replace(/([ \t])+/g, "$1"); //Remove empty lines fileContents = fileContents.replace(/^[ \t]*[\r\n]/gm,''); } } catch (e) { fileContents = originalFileContents; logger.error("Could not optimized CSS file: " + fileName + ", error: " + e); } file.saveUtf8File(outFileName, fileContents); //text output to stdout and/or written to build.txt file buildText = "\n"+ outFileName.replace(config.dir, "") +"\n----------------\n"; flat.importList.push(fileName); buildText += flat.importList.map(function(path){ return path.replace(config.dir, ""); }).join("\n"); return { importList: flat.importList, buildText: buildText +"\n" }; }, /** * Optimizes CSS files, inlining @import calls, stripping comments, and * optionally removes line returns. * @param {String} startDir the path to the top level directory * @param {Object} config the config object with the optimizeCss and * cssImportIgnore options. */ css: function (startDir, config) { var buildText = "", importList = [], shouldRemove = config.dir && config.removeCombined, i, fileName, result, fileList; if (config.optimizeCss.indexOf("standard") !== -1) { fileList = file.getFilteredFileList(startDir, /\.css$/, true); if (fileList) { for (i = 0; i < fileList.length; i++) { fileName = fileList[i]; logger.trace("Optimizing (" + config.optimizeCss + ") CSS file: " + fileName); result = optimize.cssFile(fileName, fileName, config); buildText += result.buildText; if (shouldRemove) { result.importList.pop(); importList = importList.concat(result.importList); } } } if (shouldRemove) { importList.forEach(function (path) { if (file.exists(path)) { file.deleteFile(path); } }); } } return buildText; }, optimizers: { uglify: function (fileName, fileContents, outFileName, keepLines, config) { var result, existingMap, resultMap, finalMap, sourceIndex, uconfig = {}, existingMapPath = outFileName + '.map', baseName = fileName && fileName.split('/').pop(); config = config || {}; lang.mixin(uconfig, config, true); uconfig.fromString = true; if (config.generateSourceMaps && (outFileName || config._buildSourceMap)) { uconfig.outSourceMap = baseName + '.map'; if (config._buildSourceMap) { existingMap = JSON.parse(config._buildSourceMap); uconfig.inSourceMap = existingMap; } else if (file.exists(existingMapPath)) { uconfig.inSourceMap = existingMapPath; existingMap = JSON.parse(file.readFile(existingMapPath)); } } logger.trace("Uglify file: " + fileName); try { //var tempContents = fileContents.replace(/\/\/\# sourceMappingURL=.*$/, ''); result = uglify.minify(fileContents, uconfig, baseName + '.src.js'); if (uconfig.outSourceMap && result.map) { resultMap = result.map; if (!existingMap && !config._buildSourceMap) { file.saveFile(outFileName + '.src.js', fileContents); } fileContents = result.code; if (config._buildSourceMap) { config._buildSourceMap = resultMap; } else { file.saveFile(outFileName + '.map', resultMap); } } else { fileContents = result.code; } } catch (e) { throw new Error('Cannot uglify file: ' + fileName + '. Skipping it. Error is:\n' + e.toString()); } return fileContents; } } }; return optimize; }); /* * This file patches require.js to communicate with the build system. */ //Using sloppy since this uses eval for some code like plugins, //which may not be strict mode compliant. So if use strict is used //below they will have strict rules applied and may cause an error. /*jslint sloppy: true, nomen: true, plusplus: true, regexp: true */ /*global require, define: true */ //NOT asking for require as a dependency since the goal is to modify the //global require below define('requirePatch', [ 'env!env/file', 'pragma', 'parse', 'lang', 'logger', 'commonJs', 'prim'], function ( file, pragma, parse, lang, logger, commonJs, prim ) { var allowRun = true, hasProp = lang.hasProp, falseProp = lang.falseProp, getOwn = lang.getOwn, // Used to strip out use strict from toString()'d functions for the // shim config since they will explicitly want to not be bound by strict, // but some envs, explicitly xpcshell, adds a use strict. useStrictRegExp = /['"]use strict['"];/g, //Absolute path if starts with /, \, or x: absoluteUrlRegExp = /^[\/\\]|^\w:/; //Turn off throwing on resolution conflict, that was just an older prim //idea about finding errors early, but does not comply with how promises //should operate. prim.hideResolutionConflict = true; //This method should be called when the patches to require should take hold. return function () { if (!allowRun) { return; } allowRun = false; var layer, pluginBuilderRegExp = /(["']?)pluginBuilder(["']?)\s*[=\:]\s*["']([^'"\s]+)["']/, oldNewContext = require.s.newContext, oldDef, //create local undefined values for module and exports, //so that when files are evaled in this function they do not //see the node values used for r.js exports, module; /** * Reset "global" build caches that are kept around between * build layer builds. Useful to do when there are multiple * top level requirejs.optimize() calls. */ require._cacheReset = function () { //Stored raw text caches, used by browser use. require._cachedRawText = {}; //Stored cached file contents for reuse in other layers. require._cachedFileContents = {}; //Store which cached files contain a require definition. require._cachedDefinesRequireUrls = {}; }; require._cacheReset(); /** * Makes sure the URL is something that can be supported by the * optimization tool. * @param {String} url * @returns {Boolean} */ require._isSupportedBuildUrl = function (url) { //Ignore URLs with protocols, hosts or question marks, means either network //access is needed to fetch it or it is too dynamic. Note that //on Windows, full paths are used for some urls, which include //the drive, like c:/something, so need to test for something other //than just a colon. if (url.indexOf("://") === -1 && url.indexOf("?") === -1 && url.indexOf('empty:') !== 0 && url.indexOf('//') !== 0) { return true; } else { if (!layer.ignoredUrls[url]) { if (url.indexOf('empty:') === -1) { logger.info('Cannot optimize network URL, skipping: ' + url); } layer.ignoredUrls[url] = true; } return false; } }; function normalizeUrlWithBase(context, moduleName, url) { //Adjust the URL if it was not transformed to use baseUrl, but only //if the URL is not already an absolute path. if (require.jsExtRegExp.test(moduleName) && !absoluteUrlRegExp.test(url)) { url = (context.config.dir || context.config.dirBaseUrl) + url; } return url; } //Overrides the new context call to add existing tracking features. require.s.newContext = function (name) { var context = oldNewContext(name), oldEnable = context.enable, moduleProto = context.Module.prototype, oldInit = moduleProto.init, oldCallPlugin = moduleProto.callPlugin; //Only do this for the context used for building. if (name === '_') { //For build contexts, do everything sync context.nextTick = function (fn) { fn(); }; context.needFullExec = {}; context.fullExec = {}; context.plugins = {}; context.buildShimExports = {}; //Override the shim exports function generator to just //spit out strings that can be used in the stringified //build output. context.makeShimExports = function (value) { var fn; if (context.config.wrapShim) { fn = function () { var str = 'return '; // If specifies an export that is just a global // name, no dot for a `this.` and such, then also // attach to the global, for `var a = {}` files // where the function closure would hide that from // the global object. if (value.exports && value.exports.indexOf('.') === -1) { str += 'root.' + value.exports + ' = '; } if (value.init) { str += '(' + value.init.toString() .replace(useStrictRegExp, '') + '.apply(this, arguments))'; } if (value.init && value.exports) { str += ' || '; } if (value.exports) { str += value.exports; } str += ';'; return str; }; } else { fn = function () { return '(function (global) {\n' + ' return function () {\n' + ' var ret, fn;\n' + (value.init ? (' fn = ' + value.init.toString() .replace(useStrictRegExp, '') + ';\n' + ' ret = fn.apply(global, arguments);\n') : '') + (value.exports ? ' return ret || global.' + value.exports + ';\n' : ' return ret;\n') + ' };\n' + '}(this))'; }; } return fn; }; context.enable = function (depMap, parent) { var id = depMap.id, parentId = parent && parent.map.id, needFullExec = context.needFullExec, fullExec = context.fullExec, mod = getOwn(context.registry, id); if (mod && !mod.defined) { if (parentId && getOwn(needFullExec, parentId)) { needFullExec[id] = depMap; } } else if ((getOwn(needFullExec, id) && falseProp(fullExec, id)) || (parentId && getOwn(needFullExec, parentId) && falseProp(fullExec, id))) { context.require.undef(id); } return oldEnable.apply(context, arguments); }; //Override load so that the file paths can be collected. context.load = function (moduleName, url) { /*jslint evil: true */ var contents, pluginBuilderMatch, builderName, shim, shimExports; //Do not mark the url as fetched if it is //not an empty: URL, used by the optimizer. //In that case we need to be sure to call //load() for each module that is mapped to //empty: so that dependencies are satisfied //correctly. if (url.indexOf('empty:') === 0) { delete context.urlFetched[url]; } //Only handle urls that can be inlined, so that means avoiding some //URLs like ones that require network access or may be too dynamic, //like JSONP if (require._isSupportedBuildUrl(url)) { //Adjust the URL if it was not transformed to use baseUrl. url = normalizeUrlWithBase(context, moduleName, url); //Save the module name to path and path to module name mappings. layer.buildPathMap[moduleName] = url; layer.buildFileToModule[url] = moduleName; if (hasProp(context.plugins, moduleName)) { //plugins need to have their source evaled as-is. context.needFullExec[moduleName] = true; } prim().start(function () { if (hasProp(require._cachedFileContents, url) && (falseProp(context.needFullExec, moduleName) || getOwn(context.fullExec, moduleName))) { contents = require._cachedFileContents[url]; //If it defines require, mark it so it can be hoisted. //Done here and in the else below, before the //else block removes code from the contents. //Related to #263 if (!layer.existingRequireUrl && require._cachedDefinesRequireUrls[url]) { layer.existingRequireUrl = url; } } else { //Load the file contents, process for conditionals, then //evaluate it. return require._cacheReadAsync(url).then(function (text) { contents = text; if (context.config.cjsTranslate && (!context.config.shim || !lang.hasProp(context.config.shim, moduleName))) { contents = commonJs.convert(url, contents); } //If there is a read filter, run it now. if (context.config.onBuildRead) { contents = context.config.onBuildRead(moduleName, url, contents); } contents = pragma.process(url, contents, context.config, 'OnExecute'); //Find out if the file contains a require() definition. Need to know //this so we can inject plugins right after it, but before they are needed, //and to make sure this file is first, so that define calls work. try { if (!layer.existingRequireUrl && parse.definesRequire(url, contents)) { layer.existingRequireUrl = url; require._cachedDefinesRequireUrls[url] = true; } } catch (e1) { throw new Error('Parse error using esprima ' + 'for file: ' + url + '\n' + e1); } }).then(function () { if (hasProp(context.plugins, moduleName)) { //This is a loader plugin, check to see if it has a build extension, //otherwise the plugin will act as the plugin builder too. pluginBuilderMatch = pluginBuilderRegExp.exec(contents); if (pluginBuilderMatch) { //Load the plugin builder for the plugin contents. builderName = context.makeModuleMap(pluginBuilderMatch[3], context.makeModuleMap(moduleName), null, true).id; return require._cacheReadAsync(context.nameToUrl(builderName)); } } return contents; }).then(function (text) { contents = text; //Parse out the require and define calls. //Do this even for plugins in case they have their own //dependencies that may be separate to how the pluginBuilder works. try { if (falseProp(context.needFullExec, moduleName)) { contents = parse(moduleName, url, contents, { insertNeedsDefine: true, has: context.config.has, findNestedDependencies: context.config.findNestedDependencies }); } } catch (e2) { throw new Error('Parse error using esprima ' + 'for file: ' + url + '\n' + e2); } require._cachedFileContents[url] = contents; }); } }).then(function () { if (contents) { eval(contents); } try { //If have a string shim config, and this is //a fully executed module, try to see if //it created a variable in this eval scope if (getOwn(context.needFullExec, moduleName)) { shim = getOwn(context.config.shim, moduleName); if (shim && shim.exports) { shimExports = eval(shim.exports); if (typeof shimExports !== 'undefined') { context.buildShimExports[moduleName] = shimExports; } } } //Need to close out completion of this module //so that listeners will get notified that it is available. context.completeLoad(moduleName); } catch (e) { //Track which module could not complete loading. if (!e.moduleTree) { e.moduleTree = []; } e.moduleTree.push(moduleName); throw e; } }).then(null, function (eOuter) { if (!eOuter.fileName) { eOuter.fileName = url; } throw eOuter; }).end(); } else { //With unsupported URLs still need to call completeLoad to //finish loading. context.completeLoad(moduleName); } }; //Marks module has having a name, and optionally executes the //callback, but only if it meets certain criteria. context.execCb = function (name, cb, args, exports) { var buildShimExports = getOwn(layer.context.buildShimExports, name); if (buildShimExports) { return buildShimExports; } else if (cb.__requireJsBuild || getOwn(layer.context.needFullExec, name)) { return cb.apply(exports, args); } return undefined; }; moduleProto.init = function (depMaps) { if (context.needFullExec[this.map.id]) { lang.each(depMaps, lang.bind(this, function (depMap) { if (typeof depMap === 'string') { depMap = context.makeModuleMap(depMap, (this.map.isDefine ? this.map : this.map.parentMap)); } if (!context.fullExec[depMap.id]) { context.require.undef(depMap.id); } })); } return oldInit.apply(this, arguments); }; moduleProto.callPlugin = function () { var map = this.map, pluginMap = context.makeModuleMap(map.prefix), pluginId = pluginMap.id, pluginMod = getOwn(context.registry, pluginId); context.plugins[pluginId] = true; context.needFullExec[pluginId] = map; //If the module is not waiting to finish being defined, //undef it and start over, to get full execution. if (falseProp(context.fullExec, pluginId) && (!pluginMod || pluginMod.defined)) { context.require.undef(pluginMap.id); } return oldCallPlugin.apply(this, arguments); }; } return context; }; //Clear up the existing context so that the newContext modifications //above will be active. delete require.s.contexts._; /** Reset state for each build layer pass. */ require._buildReset = function () { var oldContext = require.s.contexts._; //Clear up the existing context. delete require.s.contexts._; //Set up new context, so the layer object can hold onto it. require({}); layer = require._layer = { buildPathMap: {}, buildFileToModule: {}, buildFilePaths: [], pathAdded: {}, modulesWithNames: {}, needsDefine: {}, existingRequireUrl: "", ignoredUrls: {}, context: require.s.contexts._ }; //Return the previous context in case it is needed, like for //the basic config object. return oldContext; }; require._buildReset(); //Override define() to catch modules that just define an object, so that //a dummy define call is not put in the build file for them. They do //not end up getting defined via context.execCb, so we need to catch them //at the define call. oldDef = define; //This function signature does not have to be exact, just match what we //are looking for. define = function (name) { if (typeof name === "string" && falseProp(layer.needsDefine, name)) { layer.modulesWithNames[name] = true; } return oldDef.apply(require, arguments); }; define.amd = oldDef.amd; //Add some utilities for plugins require._readFile = file.readFile; require._fileExists = function (path) { return file.exists(path); }; //Called when execAdmin runs for a dependency. Used to figure out //what order of execution. require.onResourceLoad = function (context, map) { var id = map.id, url; // Fix up any maps that need to be normalized as part of the fullExec // plumbing for plugins to participate in the build. if (context.plugins && lang.hasProp(context.plugins, id)) { lang.eachProp(context.needFullExec, function(value, prop) { // For plugin entries themselves, they do not have a map // value in needFullExec, just a "true" entry. if (value !== true && value.prefix === id && value.unnormalized) { var map = context.makeModuleMap(value.originalName, value.parentMap); context.needFullExec[map.id] = map; } }); } //If build needed a full execution, indicate it //has been done now. But only do it if the context is tracking //that. Only valid for the context used in a build, not for //other contexts being run, like for useLib, plain requirejs //use in node/rhino. if (context.needFullExec && getOwn(context.needFullExec, id)) { context.fullExec[id] = map; } //A plugin. if (map.prefix) { if (falseProp(layer.pathAdded, id)) { layer.buildFilePaths.push(id); //For plugins the real path is not knowable, use the name //for both module to file and file to module mappings. layer.buildPathMap[id] = id; layer.buildFileToModule[id] = id; layer.modulesWithNames[id] = true; layer.pathAdded[id] = true; } } else if (map.url && require._isSupportedBuildUrl(map.url)) { //If the url has not been added to the layer yet, and it //is from an actual file that was loaded, add it now. url = normalizeUrlWithBase(context, id, map.url); if (!layer.pathAdded[url] && getOwn(layer.buildPathMap, id)) { //Remember the list of dependencies for this layer. layer.buildFilePaths.push(url); layer.pathAdded[url] = true; } } }; //Called by output of the parse() function, when a file does not //explicitly call define, probably just require, but the parse() //function normalizes on define() for dependency mapping and file //ordering works correctly. require.needsDefine = function (moduleName) { layer.needsDefine[moduleName] = true; }; }; }); /*jslint */ /*global define: false, console: false */ define('commonJs', ['env!env/file', 'parse'], function (file, parse) { 'use strict'; var commonJs = { //Set to false if you do not want this file to log. Useful in environments //like node where you want the work to happen without noise. useLog: true, convertDir: function (commonJsPath, savePath) { var fileList, i, jsFileRegExp = /\.js$/, fileName, convertedFileName, fileContents; //Get list of files to convert. fileList = file.getFilteredFileList(commonJsPath, /\w/, true); //Normalize on front slashes and make sure the paths do not end in a slash. commonJsPath = commonJsPath.replace(/\\/g, "/"); savePath = savePath.replace(/\\/g, "/"); if (commonJsPath.charAt(commonJsPath.length - 1) === "/") { commonJsPath = commonJsPath.substring(0, commonJsPath.length - 1); } if (savePath.charAt(savePath.length - 1) === "/") { savePath = savePath.substring(0, savePath.length - 1); } //Cycle through all the JS files and convert them. if (!fileList || !fileList.length) { if (commonJs.useLog) { if (commonJsPath === "convert") { //A request just to convert one file. console.log('\n\n' + commonJs.convert(savePath, file.readFile(savePath))); } else { console.log("No files to convert in directory: " + commonJsPath); } } } else { for (i = 0; i < fileList.length; i++) { fileName = fileList[i]; convertedFileName = fileName.replace(commonJsPath, savePath); //Handle JS files. if (jsFileRegExp.test(fileName)) { fileContents = file.readFile(fileName); fileContents = commonJs.convert(fileName, fileContents); file.saveUtf8File(convertedFileName, fileContents); } else { //Just copy the file over. file.copyFile(fileName, convertedFileName, true); } } } }, /** * Does the actual file conversion. * * @param {String} fileName the name of the file. * * @param {String} fileContents the contents of a file :) * * @returns {String} the converted contents */ convert: function (fileName, fileContents) { //Strip out comments. try { var preamble = '', commonJsProps = parse.usesCommonJs(fileName, fileContents); //First see if the module is not already RequireJS-formatted. if (parse.usesAmdOrRequireJs(fileName, fileContents) || !commonJsProps) { return fileContents; } if (commonJsProps.dirname || commonJsProps.filename) { preamble = 'var __filename = module.uri || "", ' + '__dirname = __filename.substring(0, __filename.lastIndexOf("/") + 1); '; } //Construct the wrapper boilerplate. fileContents = 'define(function (require, exports, module) {' + preamble + fileContents + '\n});\n'; } catch (e) { console.log("commonJs.convert: COULD NOT CONVERT: " + fileName + ", so skipping it. Error was: " + e); return fileContents; } return fileContents; } }; return commonJs; }); /*jslint plusplus: true, nomen: true, regexp: true */ /*global define, requirejs, java, process, console */ define('build', function (require) { 'use strict'; var build, lang = require('lang'), prim = require('prim'), logger = require('logger'), file = require('env!env/file'), parse = require('parse'), optimize = require('optimize'), pragma = require('pragma'), transform = require('transform'), requirePatch = require('requirePatch'), env = require('env'), commonJs = require('commonJs'), SourceMapGenerator = require('source-map').SourceMapGenerator, hasProp = lang.hasProp, getOwn = lang.getOwn, falseProp = lang.falseProp, endsWithSemiColonRegExp = /;\s*$/, endsWithSlashRegExp = /[\/\\]$/, resourceIsModuleIdRegExp = /^[\w\/\\\.]+$/, deepCopyProps = { layer: true }; //Deep copy a config object, but do not copy over the "layer" property, //as it can be a deeply nested structure with a full requirejs context. function copyConfig(obj) { return lang.deeplikeCopy(obj, deepCopyProps); } prim.nextTick = function (fn) { fn(); }; //Now map require to the outermost requirejs, now that we have //local dependencies for this module. The rest of the require use is //manipulating the requirejs loader. require = requirejs; //Caching function for performance. Attached to //require so it can be reused in requirePatch.js. _cachedRawText //set up by requirePatch.js require._cacheReadAsync = function (path, encoding) { var d; if (lang.hasProp(require._cachedRawText, path)) { d = prim(); d.resolve(require._cachedRawText[path]); return d.promise; } else { return file.readFileAsync(path, encoding).then(function (text) { require._cachedRawText[path] = text; return text; }); } }; function makeBuildBaseConfig() { return { appDir: "", pragmas: {}, paths: {}, optimize: "uglify", optimizeCss: "standard.keepLines.keepWhitespace", inlineText: true, isBuild: true, optimizeAllPluginResources: false, findNestedDependencies: false, preserveLicenseComments: true, writeBuildTxt: true, //Some builds can take a while, up the default limit. waitSeconds: 30, //By default, all files/directories are copied, unless //they match this regexp, by default just excludes .folders dirExclusionRegExp: file.dirExclusionRegExp, _buildPathToModuleIndex: {} }; } /** * Some JS may not be valid if concatenated with other JS, in particular * the style of omitting semicolons and rely on ASI. Add a semicolon in * those cases. */ function addSemiColon(text, config) { if (config.skipSemiColonInsertion || endsWithSemiColonRegExp.test(text)) { return text; } else { return text + ";"; } } function endsWithSlash(dirName) { if (dirName.charAt(dirName.length - 1) !== "/") { dirName += "/"; } return dirName; } function endsWithNewLine(text) { if (text.charAt(text.length - 1) !== "\n") { text += "\n"; } return text; } //Method used by plugin writeFile calls, defined up here to avoid //jslint warning about "making a function in a loop". function makeWriteFile(namespace, layer) { function writeFile(name, contents) { logger.trace('Saving plugin-optimized file: ' + name); file.saveUtf8File(name, contents); } writeFile.asModule = function (moduleName, fileName, contents) { writeFile(fileName, build.toTransport(namespace, moduleName, fileName, contents, layer)); }; return writeFile; } /** * Appends singleContents to fileContents and returns the result. If a sourceMapGenerator * is provided, adds singleContents to the source map. * * @param {string} fileContents - The file contents to which to append singleContents * @param {string} singleContents - The additional contents to append to fileContents * @param {string} path - An absolute path of a file whose name to use in the source map. * The file need not actually exist if the code in singleContents is generated. * @param {{out: ?string, baseUrl: ?string}} config - The build configuration object. * @param {?{_buildPath: ?string}} module - An object with module information. * @param {?SourceMapGenerator} sourceMapGenerator - An instance of Mozilla's SourceMapGenerator, * or null if no source map is being generated. * @returns {string} fileContents with singleContents appended */ function appendToFileContents(fileContents, singleContents, path, config, module, sourceMapGenerator) { var refPath, sourceMapPath, resourcePath, pluginId, sourceMapLineNumber, lineCount, parts, i; if (sourceMapGenerator) { if (config.out) { refPath = config.baseUrl; } else if (module && module._buildPath) { refPath = module._buildPath; } else { refPath = ""; } parts = path.split('!'); if (parts.length === 1) { //Not a plugin resource, fix the path sourceMapPath = build.makeRelativeFilePath(refPath, path); } else { //Plugin resource. If it looks like just a plugin //followed by a module ID, pull off the plugin //and put it at the end of the name, otherwise //just leave it alone. pluginId = parts.shift(); resourcePath = parts.join('!'); if (resourceIsModuleIdRegExp.test(resourcePath)) { sourceMapPath = build.makeRelativeFilePath(refPath, require.toUrl(resourcePath)) + '!' + pluginId; } else { sourceMapPath = path; } } sourceMapLineNumber = fileContents.split('\n').length - 1; lineCount = singleContents.split('\n').length; for (i = 1; i <= lineCount; i += 1) { sourceMapGenerator.addMapping({ generated: { line: sourceMapLineNumber + i, column: 0 }, original: { line: i, column: 0 }, source: sourceMapPath }); } //Store the content of the original in the source //map since other transforms later like minification //can mess up translating back to the original //source. sourceMapGenerator.setSourceContent(sourceMapPath, singleContents); } fileContents += singleContents; return fileContents; } /** * Main API entry point into the build. The args argument can either be * an array of arguments (like the onese passed on a command-line), * or it can be a JavaScript object that has the format of a build profile * file. * * If it is an object, then in addition to the normal properties allowed in * a build profile file, the object should contain one other property: * * The object could also contain a "buildFile" property, which is a string * that is the file path to a build profile that contains the rest * of the build profile directives. * * This function does not return a status, it should throw an error if * there is a problem completing the build. */ build = function (args) { var buildFile, cmdConfig, errorMsg, errorStack, stackMatch, errorTree, i, j, errorMod, stackRegExp = /( {4}at[^\n]+)\n/, standardIndent = ' '; return prim().start(function () { if (!args || lang.isArray(args)) { if (!args || args.length < 1) { logger.error("build.js buildProfile.js\n" + "where buildProfile.js is the name of the build file (see example.build.js for hints on how to make a build file)."); return undefined; } //Next args can include a build file path as well as other build args. //build file path comes first. If it does not contain an = then it is //a build file path. Otherwise, just all build args. if (args[0].indexOf("=") === -1) { buildFile = args[0]; args.splice(0, 1); } //Remaining args are options to the build cmdConfig = build.convertArrayToObject(args); cmdConfig.buildFile = buildFile; } else { cmdConfig = args; } return build._run(cmdConfig); }).then(null, function (e) { var err; errorMsg = e.toString(); errorTree = e.moduleTree; stackMatch = stackRegExp.exec(errorMsg); if (stackMatch) { errorMsg += errorMsg.substring(0, stackMatch.index + stackMatch[0].length + 1); } //If a module tree that shows what module triggered the error, //print it out. if (errorTree && errorTree.length > 0) { errorMsg += '\nIn module tree:\n'; for (i = errorTree.length - 1; i > -1; i--) { errorMod = errorTree[i]; if (errorMod) { for (j = errorTree.length - i; j > -1; j--) { errorMsg += standardIndent; } errorMsg += errorMod + '\n'; } } logger.error(errorMsg); } errorStack = e.stack; if (typeof args === 'string' && args.indexOf('stacktrace=true') !== -1) { errorMsg += '\n' + errorStack; } else { if (!stackMatch && errorStack) { //Just trim out the first "at" in the stack. stackMatch = stackRegExp.exec(errorStack); if (stackMatch) { errorMsg += '\n' + stackMatch[0] || ''; } } } err = new Error(errorMsg); err.originalError = e; throw err; }); }; build._run = function (cmdConfig) { var buildPaths, fileName, fileNames, paths, i, baseConfig, config, modules, srcPath, buildContext, destPath, moduleMap, parentModuleMap, context, resources, resource, plugin, fileContents, pluginProcessed = {}, buildFileContents = "", pluginCollector = {}; return prim().start(function () { var prop; //Can now run the patches to require.js to allow it to be used for //build generation. Do it here instead of at the top of the module //because we want normal require behavior to load the build tool //then want to switch to build mode. requirePatch(); config = build.createConfig(cmdConfig); paths = config.paths; //Remove the previous build dir, in case it contains source transforms, //like the ones done with onBuildRead and onBuildWrite. if (config.dir && !config.keepBuildDir && file.exists(config.dir)) { file.deleteFile(config.dir); } if (!config.out && !config.cssIn) { //This is not just a one-off file build but a full build profile, with //lots of files to process. //First copy all the baseUrl content file.copyDir((config.appDir || config.baseUrl), config.dir, /\w/, true); //Adjust baseUrl if config.appDir is in play, and set up build output paths. buildPaths = {}; if (config.appDir) { //All the paths should be inside the appDir, so just adjust //the paths to use the dirBaseUrl for (prop in paths) { if (hasProp(paths, prop)) { buildPaths[prop] = paths[prop].replace(config.appDir, config.dir); } } } else { //If no appDir, then make sure to copy the other paths to this directory. for (prop in paths) { if (hasProp(paths, prop)) { //Set up build path for each path prefix, but only do so //if the path falls out of the current baseUrl if (paths[prop].indexOf(config.baseUrl) === 0) { buildPaths[prop] = paths[prop].replace(config.baseUrl, config.dirBaseUrl); } else { buildPaths[prop] = paths[prop] === 'empty:' ? 'empty:' : prop; //Make sure source path is fully formed with baseUrl, //if it is a relative URL. srcPath = paths[prop]; if (srcPath.indexOf('/') !== 0 && srcPath.indexOf(':') === -1) { srcPath = config.baseUrl + srcPath; } destPath = config.dirBaseUrl + buildPaths[prop]; //Skip empty: paths if (srcPath !== 'empty:') { //If the srcPath is a directory, copy the whole directory. if (file.exists(srcPath) && file.isDirectory(srcPath)) { //Copy files to build area. Copy all files (the /\w/ regexp) file.copyDir(srcPath, destPath, /\w/, true); } else { //Try a .js extension srcPath += '.js'; destPath += '.js'; file.copyFile(srcPath, destPath); } } } } } } } //Figure out source file location for each module layer. Do this by seeding require //with source area configuration. This is needed so that later the module layers //can be manually copied over to the source area, since the build may be //require multiple times and the above copyDir call only copies newer files. require({ baseUrl: config.baseUrl, paths: paths, packagePaths: config.packagePaths, packages: config.packages }); buildContext = require.s.contexts._; modules = config.modules; if (modules) { modules.forEach(function (module) { if (module.name) { module._sourcePath = buildContext.nameToUrl(module.name); //If the module does not exist, and this is not a "new" module layer, //as indicated by a true "create" property on the module, and //it is not a plugin-loaded resource, and there is no //'rawText' containing the module's source then throw an error. if (!file.exists(module._sourcePath) && !module.create && module.name.indexOf('!') === -1 && (!config.rawText || !lang.hasProp(config.rawText, module.name))) { throw new Error("ERROR: module path does not exist: " + module._sourcePath + " for module named: " + module.name + ". Path is relative to: " + file.absPath('.')); } } }); } if (config.out) { //Just set up the _buildPath for the module layer. require(config); if (!config.cssIn) { config.modules[0]._buildPath = typeof config.out === 'function' ? 'FUNCTION' : config.out; } } else if (!config.cssIn) { //Now set up the config for require to use the build area, and calculate the //build file locations. Pass along any config info too. baseConfig = { baseUrl: config.dirBaseUrl, paths: buildPaths }; lang.mixin(baseConfig, config); require(baseConfig); if (modules) { modules.forEach(function (module) { if (module.name) { module._buildPath = buildContext.nameToUrl(module.name, null); //If buildPath and sourcePath are the same, throw since this //would result in modifying source. This condition can happen //with some more tricky paths: config and appDir/baseUrl //setting, which is a sign of incorrect config. if (module._buildPath === module._sourcePath && !config.allowSourceOverwrites) { throw new Error('Module ID \'' + module.name + '\' has a source path that is same as output path: ' + module._sourcePath + '. Stopping, config is malformed.'); } if (!module.create) { file.copyFile(module._sourcePath, module._buildPath); } } }); } } //Run CSS optimizations before doing JS module tracing, to allow //things like text loader plugins loading CSS to get the optimized //CSS. if (config.optimizeCss && config.optimizeCss !== "none" && config.dir) { buildFileContents += optimize.css(config.dir, config); } }).then(function() { baseConfig = copyConfig(require.s.contexts._.config); }).then(function () { var actions = []; if (modules) { actions = modules.map(function (module, i) { return function () { //Save off buildPath to module index in a hash for quicker //lookup later. config._buildPathToModuleIndex[file.normalize(module._buildPath)] = i; //Call require to calculate dependencies. return build.traceDependencies(module, config, baseConfig) .then(function (layer) { module.layer = layer; }); }; }); return prim.serial(actions); } }).then(function () { var actions; if (modules) { //Now build up shadow layers for anything that should be excluded. //Do this after tracing dependencies for each module, in case one //of those modules end up being one of the excluded values. actions = modules.map(function (module) { return function () { if (module.exclude) { module.excludeLayers = []; return prim.serial(module.exclude.map(function (exclude, i) { return function () { //See if it is already in the list of modules. //If not trace dependencies for it. var found = build.findBuildModule(exclude, modules); if (found) { module.excludeLayers[i] = found; } else { return build.traceDependencies({name: exclude}, config, baseConfig) .then(function (layer) { module.excludeLayers[i] = { layer: layer }; }); } }; })); } }; }); return prim.serial(actions); } }).then(function () { if (modules) { return prim.serial(modules.map(function (module) { return function () { if (module.exclude) { //module.exclude is an array of module names. For each one, //get the nested dependencies for it via a matching entry //in the module.excludeLayers array. module.exclude.forEach(function (excludeModule, i) { var excludeLayer = module.excludeLayers[i].layer, map = excludeLayer.buildFileToModule; excludeLayer.buildFilePaths.forEach(function(filePath){ build.removeModulePath(map[filePath], filePath, module.layer); }); }); } if (module.excludeShallow) { //module.excludeShallow is an array of module names. //shallow exclusions are just that module itself, and not //its nested dependencies. module.excludeShallow.forEach(function (excludeShallowModule) { var path = getOwn(module.layer.buildPathMap, excludeShallowModule); if (path) { build.removeModulePath(excludeShallowModule, path, module.layer); } }); } //Flatten them and collect the build output for each module. return build.flattenModule(module, module.layer, config).then(function (builtModule) { var finalText, baseName; //Save it to a temp file for now, in case there are other layers that //contain optimized content that should not be included in later //layer optimizations. See issue #56. if (module._buildPath === 'FUNCTION') { module._buildText = builtModule.text; module._buildSourceMap = builtModule.sourceMap; } else { finalText = builtModule.text; if (builtModule.sourceMap) { baseName = module._buildPath.split('/'); baseName = baseName.pop(); finalText += '\n//# sourceMappingURL=' + baseName + '.map'; file.saveUtf8File(module._buildPath + '.map', builtModule.sourceMap); } file.saveUtf8File(module._buildPath + '-temp', finalText); } buildFileContents += builtModule.buildText; }); }; })); } }).then(function () { var moduleName, outOrigSourceMap, bundlesConfig = {}, bundlesConfigOutFile = config.bundlesConfigOutFile; if (modules) { //Now move the build layers to their final position. modules.forEach(function (module) { var entryConfig, finalPath = module._buildPath; if (finalPath !== 'FUNCTION') { if (file.exists(finalPath)) { file.deleteFile(finalPath); } file.renameFile(finalPath + '-temp', finalPath); //If bundles config should be written out, scan the //built file for module IDs. Favor doing this reparse //since tracking the IDs as the file is built has some //edge cases around files that had more than one ID in //them already, and likely loader plugin-written contents. if (bundlesConfigOutFile) { entryConfig = bundlesConfig[module.name] = []; var bundleContents = file.readFile(finalPath); var excludeMap = {}; excludeMap[module.name] = true; var parsedIds = parse.getAllNamedDefines(bundleContents, excludeMap); entryConfig.push.apply(entryConfig, parsedIds); } //And finally, if removeCombined is specified, remove //any of the files that were used in this layer. //Be sure not to remove other build layers. if (config.removeCombined && !config.out) { module.layer.buildFilePaths.forEach(function (path) { var isLayer = modules.some(function (mod) { return mod._buildPath === path; }), relPath = build.makeRelativeFilePath(config.dir, path); if (file.exists(path) && // not a build layer target !isLayer && // not outside the build directory relPath.indexOf('..') !== 0) { file.deleteFile(path); } }); } } //Signal layer is done if (config.onModuleBundleComplete) { config.onModuleBundleComplete(module.onCompleteData); } }); //Write out bundles config, if it is wanted. if (bundlesConfigOutFile) { var text = file.readFile(bundlesConfigOutFile); text = transform.modifyConfig(text, function (config) { if (!config.bundles) { config.bundles = {}; } lang.eachProp(bundlesConfig, function (value, prop) { config.bundles[prop] = value; }); return config; }); file.saveUtf8File(bundlesConfigOutFile, text); } } //If removeCombined in play, remove any empty directories that //may now exist because of its use if (config.removeCombined && !config.out && config.dir) { file.deleteEmptyDirs(config.dir); } //Do other optimizations. if (config.out && !config.cssIn) { //Just need to worry about one JS file. fileName = config.modules[0]._buildPath; if (fileName === 'FUNCTION') { outOrigSourceMap = config.modules[0]._buildSourceMap; config._buildSourceMap = outOrigSourceMap; config.modules[0]._buildText = optimize.js((config.modules[0].name || config.modules[0].include[0] || fileName) + '.build.js', config.modules[0]._buildText, null, config); if (config._buildSourceMap && config._buildSourceMap !== outOrigSourceMap) { config.modules[0]._buildSourceMap = config._buildSourceMap; config._buildSourceMap = null; } } else { optimize.jsFile(fileName, null, fileName, config); } } else if (!config.cssIn) { //Normal optimizations across modules. //JS optimizations. fileNames = file.getFilteredFileList(config.dir, /\.js$/, true); fileNames.forEach(function (fileName) { var cfg, override, moduleIndex; //Generate the module name from the config.dir root. moduleName = fileName.replace(config.dir, ''); //Get rid of the extension moduleName = moduleName.substring(0, moduleName.length - 3); //If there is an override for a specific layer build module, //and this file is that module, mix in the override for use //by optimize.jsFile. moduleIndex = getOwn(config._buildPathToModuleIndex, fileName); //Normalize, since getOwn could have returned undefined moduleIndex = moduleIndex === 0 || moduleIndex > 0 ? moduleIndex : -1; //Try to avoid extra work if the other files do not need to //be read. Build layers should be processed at the very //least for optimization. if (moduleIndex > -1 || !config.skipDirOptimize || config.normalizeDirDefines === "all" || config.cjsTranslate) { //Convert the file to transport format, but without a name //inserted (by passing null for moduleName) since the files are //standalone, one module per file. fileContents = file.readFile(fileName); //For builds, if wanting cjs translation, do it now, so that //the individual modules can be loaded cross domain via //plain script tags. if (config.cjsTranslate && (!config.shim || !lang.hasProp(config.shim, moduleName))) { fileContents = commonJs.convert(fileName, fileContents); } if (moduleIndex === -1) { if (config.onBuildRead) { fileContents = config.onBuildRead(moduleName, fileName, fileContents); } //Only do transport normalization if this is not a build //layer (since it was already normalized) and if //normalizeDirDefines indicated all should be done. if (config.normalizeDirDefines === "all") { fileContents = build.toTransport(config.namespace, null, fileName, fileContents); } if (config.onBuildWrite) { fileContents = config.onBuildWrite(moduleName, fileName, fileContents); } } override = moduleIndex > -1 ? config.modules[moduleIndex].override : null; if (override) { cfg = build.createOverrideConfig(config, override); } else { cfg = config; } if (moduleIndex > -1 || !config.skipDirOptimize) { optimize.jsFile(fileName, fileContents, fileName, cfg, pluginCollector); } } }); //Normalize all the plugin resources. context = require.s.contexts._; for (moduleName in pluginCollector) { if (hasProp(pluginCollector, moduleName)) { parentModuleMap = context.makeModuleMap(moduleName); resources = pluginCollector[moduleName]; for (i = 0; i < resources.length; i++) { resource = resources[i]; moduleMap = context.makeModuleMap(resource, parentModuleMap); if (falseProp(context.plugins, moduleMap.prefix)) { //Set the value in context.plugins so it //will be evaluated as a full plugin. context.plugins[moduleMap.prefix] = true; //Do not bother if the plugin is not available. if (!file.exists(require.toUrl(moduleMap.prefix + '.js'))) { continue; } //Rely on the require in the build environment //to be synchronous context.require([moduleMap.prefix]); //Now that the plugin is loaded, redo the moduleMap //since the plugin will need to normalize part of the path. moduleMap = context.makeModuleMap(resource, parentModuleMap); } //Only bother with plugin resources that can be handled //processed by the plugin, via support of the writeFile //method. if (falseProp(pluginProcessed, moduleMap.id)) { //Only do the work if the plugin was really loaded. //Using an internal access because the file may //not really be loaded. plugin = getOwn(context.defined, moduleMap.prefix); if (plugin && plugin.writeFile) { plugin.writeFile( moduleMap.prefix, moduleMap.name, require, makeWriteFile( config.namespace ), context.config ); } pluginProcessed[moduleMap.id] = true; } } } } //console.log('PLUGIN COLLECTOR: ' + JSON.stringify(pluginCollector, null, " ")); //All module layers are done, write out the build.txt file. if (config.writeBuildTxt) { file.saveUtf8File(config.dir + "build.txt", buildFileContents); } } //If just have one CSS file to optimize, do that here. if (config.cssIn) { buildFileContents += optimize.cssFile(config.cssIn, config.out, config).buildText; } if (typeof config.out === 'function') { config.out(config.modules[0]._buildText, config.modules[0]._buildSourceMap); } //Print out what was built into which layers. if (buildFileContents) { logger.info(buildFileContents); return buildFileContents; } return ''; }); }; /** * Converts command line args like "paths.foo=../some/path" * result.paths = { foo: '../some/path' } where prop = paths, * name = paths.foo and value = ../some/path, so it assumes the * name=value splitting has already happened. */ function stringDotToObj(result, name, value) { var parts = name.split('.'); parts.forEach(function (prop, i) { if (i === parts.length - 1) { result[prop] = value; } else { if (falseProp(result, prop)) { result[prop] = {}; } result = result[prop]; } }); } build.objProps = { paths: true, wrap: true, pragmas: true, pragmasOnSave: true, has: true, hasOnSave: true, uglify: true, uglify2: true, closure: true, map: true, throwWhen: true }; build.hasDotPropMatch = function (prop) { var dotProp, index = prop.indexOf('.'); if (index !== -1) { dotProp = prop.substring(0, index); return hasProp(build.objProps, dotProp); } return false; }; /** * Converts an array that has String members of "name=value" * into an object, where the properties on the object are the names in the array. * Also converts the strings "true" and "false" to booleans for the values. * member name/value pairs, and converts some comma-separated lists into * arrays. * @param {Array} ary */ build.convertArrayToObject = function (ary) { var result = {}, i, separatorIndex, prop, value, needArray = { "include": true, "exclude": true, "excludeShallow": true, "insertRequire": true, "stubModules": true, "deps": true, "mainConfigFile": true, "wrap.startFile": true, "wrap.endFile": true }; for (i = 0; i < ary.length; i++) { separatorIndex = ary[i].indexOf("="); if (separatorIndex === -1) { throw "Malformed name/value pair: [" + ary[i] + "]. Format should be name=value"; } value = ary[i].substring(separatorIndex + 1, ary[i].length); if (value === "true") { value = true; } else if (value === "false") { value = false; } prop = ary[i].substring(0, separatorIndex); //Convert to array if necessary if (getOwn(needArray, prop)) { value = value.split(","); } if (build.hasDotPropMatch(prop)) { stringDotToObj(result, prop, value); } else { result[prop] = value; } } return result; //Object }; build.makeAbsPath = function (path, absFilePath) { if (!absFilePath) { return path; } //Add abspath if necessary. If path starts with a slash or has a colon, //then already is an abolute path. if (path.indexOf('/') !== 0 && path.indexOf(':') === -1) { path = absFilePath + (absFilePath.charAt(absFilePath.length - 1) === '/' ? '' : '/') + path; path = file.normalize(path); } return path.replace(lang.backSlashRegExp, '/'); }; build.makeAbsObject = function (props, obj, absFilePath) { var i, prop; if (obj) { for (i = 0; i < props.length; i++) { prop = props[i]; if (hasProp(obj, prop) && typeof obj[prop] === 'string') { obj[prop] = build.makeAbsPath(obj[prop], absFilePath); } } } }; /** * For any path in a possible config, make it absolute relative * to the absFilePath passed in. */ build.makeAbsConfig = function (config, absFilePath) { var props, prop, i; props = ["appDir", "dir", "baseUrl"]; for (i = 0; i < props.length; i++) { prop = props[i]; if (getOwn(config, prop)) { //Add abspath if necessary, make sure these paths end in //slashes if (prop === "baseUrl") { config.originalBaseUrl = config.baseUrl; if (config.appDir) { //If baseUrl with an appDir, the baseUrl is relative to //the appDir, *not* the absFilePath. appDir and dir are //made absolute before baseUrl, so this will work. config.baseUrl = build.makeAbsPath(config.originalBaseUrl, config.appDir); } else { //The dir output baseUrl is same as regular baseUrl, both //relative to the absFilePath. config.baseUrl = build.makeAbsPath(config[prop], absFilePath); } } else { config[prop] = build.makeAbsPath(config[prop], absFilePath); } config[prop] = endsWithSlash(config[prop]); } } build.makeAbsObject((config.out === "stdout" ? ["cssIn"] : ["out", "cssIn"]), config, absFilePath); build.makeAbsObject(["startFile", "endFile"], config.wrap, absFilePath); build.makeAbsObject(["externExportsPath"], config.closure, absFilePath); }; /** * Creates a relative path to targetPath from refPath. * Only deals with file paths, not folders. If folders, * make sure paths end in a trailing '/'. */ build.makeRelativeFilePath = function (refPath, targetPath) { var i, dotLength, finalParts, length, targetParts, targetName, refParts = refPath.split('/'), hasEndSlash = endsWithSlashRegExp.test(targetPath), dotParts = []; targetPath = file.normalize(targetPath); if (hasEndSlash && !endsWithSlashRegExp.test(targetPath)) { targetPath += '/'; } targetParts = targetPath.split('/'); //Pull off file name targetName = targetParts.pop(); //Also pop off the ref file name to make the matches against //targetParts equivalent. refParts.pop(); length = refParts.length; for (i = 0; i < length; i += 1) { if (refParts[i] !== targetParts[i]) { break; } } //Now i is the index in which they diverge. finalParts = targetParts.slice(i); dotLength = length - i; for (i = 0; i > -1 && i < dotLength; i += 1) { dotParts.push('..'); } return dotParts.join('/') + (dotParts.length ? '/' : '') + finalParts.join('/') + (finalParts.length ? '/' : '') + targetName; }; build.nestedMix = { paths: true, has: true, hasOnSave: true, pragmas: true, pragmasOnSave: true }; /** * Mixes additional source config into target config, and merges some * nested config, like paths, correctly. */ function mixConfig(target, source, skipArrays) { var prop, value, isArray, targetValue; for (prop in source) { if (hasProp(source, prop)) { //If the value of the property is a plain object, then //allow a one-level-deep mixing of it. value = source[prop]; isArray = lang.isArray(value); if (typeof value === 'object' && value && !isArray && !lang.isFunction(value) && !lang.isRegExp(value)) { // TODO: need to generalize this work, maybe also reuse // the work done in requirejs configure, perhaps move to // just a deep copy/merge overall. However, given the // amount of observable change, wait for a dot release. // This change is in relation to #645 if (prop === 'map') { if (!target.map) { target.map = {}; } lang.deepMix(target.map, source.map); } else { target[prop] = lang.mixin({}, target[prop], value, true); } } else if (isArray) { if (!skipArrays) { // Some config, like packages, are arrays. For those, // just merge the results. targetValue = target[prop]; if (lang.isArray(targetValue)) { target[prop] = targetValue.concat(value); } else { target[prop] = value; } } } else { target[prop] = value; } } } //Set up log level since it can affect if errors are thrown //or caught and passed to errbacks while doing config setup. if (lang.hasProp(target, 'logLevel')) { logger.logLevel(target.logLevel); } } /** * Converts a wrap.startFile or endFile to be start/end as a string. * the startFile/endFile values can be arrays. */ function flattenWrapFile(config, keyName, absFilePath) { var wrap = config.wrap, keyFileName = keyName + 'File', keyMapName = '__' + keyName + 'Map'; if (typeof wrap[keyName] !== 'string' && wrap[keyFileName]) { wrap[keyName] = ''; if (typeof wrap[keyFileName] === 'string') { wrap[keyFileName] = [wrap[keyFileName]]; } wrap[keyMapName] = []; wrap[keyFileName].forEach(function (fileName) { var absPath = build.makeAbsPath(fileName, absFilePath), fileText = endsWithNewLine(file.readFile(absPath)); wrap[keyMapName].push(function (fileContents, cfg, sourceMapGenerator) { return appendToFileContents(fileContents, fileText, absPath, cfg, null, sourceMapGenerator); }); wrap[keyName] += fileText; }); } else if (wrap[keyName] === null || wrap[keyName] === undefined) { //Allow missing one, just set to empty string. wrap[keyName] = ''; } else if (typeof wrap[keyName] === 'string') { wrap[keyName] = endsWithNewLine(wrap[keyName]); wrap[keyMapName] = [ function (fileContents, cfg, sourceMapGenerator) { var absPath = build.makeAbsPath("config-wrap-" + keyName + "-default.js", absFilePath); return appendToFileContents(fileContents, wrap[keyName], absPath, cfg, null, sourceMapGenerator); } ]; } else { throw new Error('wrap.' + keyName + ' or wrap.' + keyFileName + ' malformed'); } } function normalizeWrapConfig(config, absFilePath) { //Get any wrap text. try { if (config.wrap) { if (config.wrap === true) { //Use default values. config.wrap = { start: '(function () {\n', end: '}());', __startMap: [ function (fileContents, cfg, sourceMapGenerator) { return appendToFileContents(fileContents, "(function () {\n", build.makeAbsPath("config-wrap-start-default.js", absFilePath), cfg, null, sourceMapGenerator); } ], __endMap: [ function (fileContents, cfg, sourceMapGenerator) { return appendToFileContents(fileContents, "}());", build.makeAbsPath("config-wrap-end-default.js", absFilePath), cfg, null, sourceMapGenerator); } ] }; } else { flattenWrapFile(config, 'start', absFilePath); flattenWrapFile(config, 'end', absFilePath); } } } catch (wrapError) { throw new Error('Malformed wrap config: ' + wrapError.toString()); } } /** * Creates a config object for an optimization build. * It will also read the build profile if it is available, to create * the configuration. * * @param {Object} cfg config options that take priority * over defaults and ones in the build file. These options could * be from a command line, for instance. * * @param {Object} the created config object. */ build.createConfig = function (cfg) { /*jslint evil: true */ var buildFileContents, buildFileConfig, mainConfig, mainConfigFile, mainConfigPath, buildFile, absFilePath, config = {}, buildBaseConfig = makeBuildBaseConfig(); //Make sure all paths are relative to current directory. absFilePath = file.absPath('.'); build.makeAbsConfig(cfg, absFilePath); build.makeAbsConfig(buildBaseConfig, absFilePath); lang.mixin(config, buildBaseConfig); lang.mixin(config, cfg, true); //Set up log level early since it can affect if errors are thrown //or caught and passed to errbacks, even while constructing config. if (lang.hasProp(config, 'logLevel')) { logger.logLevel(config.logLevel); } if (config.buildFile) { //A build file exists, load it to get more config. buildFile = file.absPath(config.buildFile); //Find the build file, and make sure it exists, if this is a build //that has a build profile, and not just command line args with an in=path if (!file.exists(buildFile)) { throw new Error("ERROR: build file does not exist: " + buildFile); } absFilePath = config.baseUrl = file.absPath(file.parent(buildFile)); //Load build file options. buildFileContents = file.readFile(buildFile); try { //Be a bit lenient in the file ending in a ; or ending with //a //# sourceMappingUrl comment, mostly for compiled languages //that create a config, like typescript. buildFileContents = buildFileContents .replace(/\/\/\#[^\n\r]+[\n\r]*$/, '') .trim() .replace(/;$/, ''); buildFileConfig = eval("(" + buildFileContents + ")"); build.makeAbsConfig(buildFileConfig, absFilePath); //Mix in the config now so that items in mainConfigFile can //be resolved relative to them if necessary, like if appDir //is set here, but the baseUrl is in mainConfigFile. Will //re-mix in the same build config later after mainConfigFile //is processed, since build config should take priority. mixConfig(config, buildFileConfig); } catch (e) { throw new Error("Build file " + buildFile + " is malformed: " + e); } } mainConfigFile = config.mainConfigFile || (buildFileConfig && buildFileConfig.mainConfigFile); if (mainConfigFile) { if (typeof mainConfigFile === 'string') { mainConfigFile = [mainConfigFile]; } mainConfigFile.forEach(function (configFile) { configFile = build.makeAbsPath(configFile, absFilePath); if (!file.exists(configFile)) { throw new Error(configFile + ' does not exist.'); } try { mainConfig = parse.findConfig(file.readFile(configFile)).config; } catch (configError) { throw new Error('The config in mainConfigFile ' + configFile + ' cannot be used because it cannot be evaluated' + ' correctly while running in the optimizer. Try only' + ' using a config that is also valid JSON, or do not use' + ' mainConfigFile and instead copy the config values needed' + ' into a build file or command line arguments given to the optimizer.\n' + 'Source error from parsing: ' + configFile + ': ' + configError); } if (mainConfig) { mainConfigPath = configFile.substring(0, configFile.lastIndexOf('/')); //Add in some existing config, like appDir, since they can be //used inside the configFile -- paths and baseUrl are //relative to them. if (config.appDir && !mainConfig.appDir) { mainConfig.appDir = config.appDir; } //If no baseUrl, then use the directory holding the main config. if (!mainConfig.baseUrl) { mainConfig.baseUrl = mainConfigPath; } build.makeAbsConfig(mainConfig, mainConfigPath); mixConfig(config, mainConfig); } }); } //Mix in build file config, but only after mainConfig has been mixed in. //Since this is a re-application, skip array merging. if (buildFileConfig) { mixConfig(config, buildFileConfig, true); } //Re-apply the override config values. Command line //args should take precedence over build file values. //Since this is a re-application, skip array merging. mixConfig(config, cfg, true); //Fix paths to full paths so that they can be adjusted consistently //lately to be in the output area. lang.eachProp(config.paths, function (value, prop) { if (lang.isArray(value)) { throw new Error('paths fallback not supported in optimizer. ' + 'Please provide a build config path override ' + 'for ' + prop); } config.paths[prop] = build.makeAbsPath(value, config.baseUrl); }); //Set final output dir if (hasProp(config, "baseUrl")) { if (config.appDir) { if (!config.originalBaseUrl) { throw new Error('Please set a baseUrl in the build config'); } config.dirBaseUrl = build.makeAbsPath(config.originalBaseUrl, config.dir); } else { config.dirBaseUrl = config.dir || config.baseUrl; } //Make sure dirBaseUrl ends in a slash, since it is //concatenated with other strings. config.dirBaseUrl = endsWithSlash(config.dirBaseUrl); } if (config.bundlesConfigOutFile) { if (!config.dir) { throw new Error('bundlesConfigOutFile can only be used with optimizations ' + 'that use "dir".'); } config.bundlesConfigOutFile = build.makeAbsPath(config.bundlesConfigOutFile, config.dir); } //If out=stdout, write output to STDOUT instead of a file. if (config.out && config.out === 'stdout') { config.out = function (content) { var e = env.get(); if (e === 'rhino') { var out = new java.io.PrintStream(java.lang.System.out, true, 'UTF-8'); out.println(content); } else if (e === 'node') { process.stdout.setEncoding('utf8'); process.stdout.write(content); } else { console.log(content); } }; } //Check for errors in config if (config.main) { throw new Error('"main" passed as an option, but the ' + 'supported option is called "name".'); } if (config.out && !config.name && !config.modules && !config.include && !config.cssIn) { throw new Error('Missing either a "name", "include" or "modules" ' + 'option'); } if (config.cssIn) { if (config.dir || config.appDir) { throw new Error('cssIn is only for the output of single file ' + 'CSS optimizations and is not compatible with "dir" or "appDir" configuration.'); } if (!config.out) { throw new Error('"out" option missing.'); } } if (!config.cssIn && !config.baseUrl) { //Just use the current directory as the baseUrl config.baseUrl = './'; } if (!config.out && !config.dir) { throw new Error('Missing either an "out" or "dir" config value. ' + 'If using "appDir" for a full project optimization, ' + 'use "dir". If you want to optimize to one file, ' + 'use "out".'); } if (config.appDir && config.out) { throw new Error('"appDir" is not compatible with "out". Use "dir" ' + 'instead. appDir is used to copy whole projects, ' + 'where "out" with "baseUrl" is used to just ' + 'optimize to one file.'); } if (config.out && config.dir) { throw new Error('The "out" and "dir" options are incompatible.' + ' Use "out" if you are targeting a single file' + ' for optimization, and "dir" if you want the appDir' + ' or baseUrl directories optimized.'); } if (config.dir) { // Make sure the output dir is not set to a parent of the // source dir or the same dir, as it will result in source // code deletion. if (!config.allowSourceOverwrites && (config.dir === config.baseUrl || config.dir === config.appDir || (config.baseUrl && build.makeRelativeFilePath(config.dir, config.baseUrl).indexOf('..') !== 0) || (config.appDir && build.makeRelativeFilePath(config.dir, config.appDir).indexOf('..') !== 0))) { throw new Error('"dir" is set to a parent or same directory as' + ' "appDir" or "baseUrl". This can result in' + ' the deletion of source code. Stopping. If' + ' you want to allow possible overwriting of' + ' source code, set "allowSourceOverwrites"' + ' to true in the build config, but do so at' + ' your own risk. In that case, you may want' + ' to also set "keepBuildDir" to true.'); } } if (config.insertRequire && !lang.isArray(config.insertRequire)) { throw new Error('insertRequire should be a list of module IDs' + ' to insert in to a require([]) call.'); } //Support older configs with uglify2 settings, but now that uglify1 has //been removed, just translate it to 'uglify' settings. if (config.optimize === 'uglify2') { config.optimize = 'uglify'; } if (config.uglify2) { config.uglify = config.uglify2; delete config.uglify2; } if (config.generateSourceMaps) { if (config.preserveLicenseComments && config.optimize !== 'none') { throw new Error('Cannot use preserveLicenseComments and ' + 'generateSourceMaps together. Either explcitly set ' + 'preserveLicenseComments to false (default is true) or ' + 'turn off generateSourceMaps. If you want source maps with ' + 'license comments, see: ' + 'http://requirejs.org/docs/errors.html#sourcemapcomments'); } else if (config.optimize !== 'none' && config.optimize !== 'closure' && config.optimize !== 'uglify') { //Allow optimize: none to pass, since it is useful when toggling //minification on and off to debug something, and it implicitly //works, since it does not need a source map. throw new Error('optimize: "' + config.optimize + '" does not support generateSourceMaps.'); } } if ((config.name || config.include) && !config.modules) { //Just need to build one file, but may be part of a whole appDir/ //baseUrl copy, but specified on the command line, so cannot do //the modules array setup. So create a modules section in that //case. config.modules = [ { name: config.name, out: config.out, create: config.create, include: config.include, exclude: config.exclude, excludeShallow: config.excludeShallow, insertRequire: config.insertRequire, stubModules: config.stubModules } ]; delete config.stubModules; } else if (config.modules && config.out) { throw new Error('If the "modules" option is used, then there ' + 'should be a "dir" option set and "out" should ' + 'not be used since "out" is only for single file ' + 'optimization output.'); } else if (config.modules && config.name) { throw new Error('"name" and "modules" options are incompatible. ' + 'Either use "name" if doing a single file ' + 'optimization, or "modules" if you want to target ' + 'more than one file for optimization.'); } if (config.out && !config.cssIn) { //Just one file to optimize. //Does not have a build file, so set up some defaults. //Optimizing CSS should not be allowed, unless explicitly //asked for on command line. In that case the only task is //to optimize a CSS file. if (!cfg.optimizeCss) { config.optimizeCss = "none"; } } //Normalize cssPrefix if (config.cssPrefix) { //Make sure cssPrefix ends in a slash config.cssPrefix = endsWithSlash(config.cssPrefix); } else { config.cssPrefix = ''; } //Cycle through modules and normalize if (config.modules && config.modules.length) { config.modules.forEach(function (mod) { if (lang.isArray(mod) || typeof mod === 'string' || !mod) { throw new Error('modules config item is malformed: it should' + ' be an object with a \'name\' property.'); } //Combine any local stubModules with global values. if (config.stubModules) { mod.stubModules = config.stubModules.concat(mod.stubModules || []); } //Create a hash lookup for the stubModules config to make lookup //cheaper later. if (mod.stubModules) { mod.stubModules._byName = {}; mod.stubModules.forEach(function (id) { mod.stubModules._byName[id] = true; }); } // Legacy command support, which allowed a single string ID // for include. if (typeof mod.include === 'string') { mod.include = [mod.include]; } //Allow wrap config in overrides, but normalize it. if (mod.override) { normalizeWrapConfig(mod.override, absFilePath); } }); } normalizeWrapConfig(config, absFilePath); //Do final input verification if (config.context) { throw new Error('The build argument "context" is not supported' + ' in a build. It should only be used in web' + ' pages.'); } //Set up normalizeDirDefines. If not explicitly set, if optimize "none", //set to "skip" otherwise set to "all". if (!hasProp(config, 'normalizeDirDefines')) { if (config.optimize === 'none' || config.skipDirOptimize) { config.normalizeDirDefines = 'skip'; } else { config.normalizeDirDefines = 'all'; } } //Set file.fileExclusionRegExp if desired if (hasProp(config, 'fileExclusionRegExp')) { if (typeof config.fileExclusionRegExp === "string") { file.exclusionRegExp = new RegExp(config.fileExclusionRegExp); } else { file.exclusionRegExp = config.fileExclusionRegExp; } } else if (hasProp(config, 'dirExclusionRegExp')) { //Set file.dirExclusionRegExp if desired, this is the old //name for fileExclusionRegExp before 1.0.2. Support for backwards //compatibility file.exclusionRegExp = config.dirExclusionRegExp; } //Track the deps, but in a different key, so that they are not loaded //as part of config seeding before all config is in play (#648). Was //going to merge this in with "include", but include is added after //the "name" target. To preserve what r.js has done previously, make //sure "deps" comes before the "name". if (config.deps) { config._depsInclude = config.deps; } //Remove things that may cause problems in the build. //deps already merged above delete config.deps; delete config.jQuery; delete config.enforceDefine; delete config.urlArgs; return config; }; /** * finds the module being built/optimized with the given moduleName, * or returns null. * @param {String} moduleName * @param {Array} modules * @returns {Object} the module object from the build profile, or null. */ build.findBuildModule = function (moduleName, modules) { var i, module; for (i = 0; i < modules.length; i++) { module = modules[i]; if (module.name === moduleName) { return module; } } return null; }; /** * Removes a module name and path from a layer, if it is supposed to be * excluded from the layer. * @param {String} moduleName the name of the module * @param {String} path the file path for the module * @param {Object} layer the layer to remove the module/path from */ build.removeModulePath = function (module, path, layer) { var index = layer.buildFilePaths.indexOf(path); if (index !== -1) { layer.buildFilePaths.splice(index, 1); } }; /** * Uses the module build config object to trace the dependencies for the * given module. * * @param {Object} module the module object from the build config info. * @param {Object} config the build config object. * @param {Object} [baseLoaderConfig] the base loader config to use for env resets. * * @returns {Object} layer information about what paths and modules should * be in the flattened module. */ build.traceDependencies = function (module, config, baseLoaderConfig) { var include, override, layer, context, oldContext, rawTextByIds, syncChecks = { rhino: true, node: true, xpconnect: true }, deferred = prim(); //Reset some state set up in requirePatch.js, and clean up require's //current context. oldContext = require._buildReset(); //Grab the reset layer and context after the reset, but keep the //old config to reuse in the new context. layer = require._layer; context = layer.context; //Put back basic config, use a fresh object for it. if (baseLoaderConfig) { require(copyConfig(baseLoaderConfig)); } logger.trace("\nTracing dependencies for: " + (module.name || (typeof module.out === 'function' ? 'FUNCTION' : module.out))); include = config._depsInclude || []; include = include.concat(module.name && !module.create ? [module.name] : []); if (module.include) { include = include.concat(module.include); } //If there are overrides to basic config, set that up now.; if (module.override) { if (baseLoaderConfig) { override = build.createOverrideConfig(baseLoaderConfig, module.override); } else { override = copyConfig(module.override); } require(override); } //Now, populate the rawText cache with any values explicitly passed in //via config. rawTextByIds = require.s.contexts._.config.rawText; if (rawTextByIds) { lang.eachProp(rawTextByIds, function (contents, id) { var url = require.toUrl(id) + '.js'; require._cachedRawText[url] = contents; }); } //Configure the callbacks to be called. deferred.reject.__requireJsBuild = true; //Use a wrapping function so can check for errors. function includeFinished(value) { //If a sync build environment, check for errors here, instead of //in the then callback below, since some errors, like two IDs pointed //to same URL but only one anon ID will leave the loader in an //unresolved state since a setTimeout cannot be used to check for //timeout. var hasError = false; if (syncChecks[env.get()]) { try { build.checkForErrors(context, layer); } catch (e) { hasError = true; deferred.reject(e); } } if (!hasError) { deferred.resolve(value); } } includeFinished.__requireJsBuild = true; //Figure out module layer dependencies by calling require to do the work. require(include, includeFinished, deferred.reject); // If a sync env, then with the "two IDs to same anon module path" // issue, the require never completes, need to check for errors // here. if (syncChecks[env.get()]) { build.checkForErrors(context, layer); } return deferred.promise.then(function () { //Reset config if (module.override && baseLoaderConfig) { require(copyConfig(baseLoaderConfig)); } build.checkForErrors(context, layer); return layer; }); }; build.checkForErrors = function (context, layer) { //Check to see if it all loaded. If not, then throw, and give //a message on what is left. var id, prop, mod, idParts, pluginId, pluginResources, errMessage = '', failedPluginMap = {}, failedPluginIds = [], errIds = [], errUrlMap = {}, errUrlConflicts = {}, hasErrUrl = false, hasUndefined = false, defined = context.defined, registry = context.registry; function populateErrUrlMap(id, errUrl, skipNew) { // Loader plugins do not have an errUrl, so skip them. if (!errUrl) { return; } if (!skipNew) { errIds.push(id); } if (errUrlMap[errUrl]) { hasErrUrl = true; //This error module has the same URL as another //error module, could be misconfiguration. if (!errUrlConflicts[errUrl]) { errUrlConflicts[errUrl] = []; //Store the original module that had the same URL. errUrlConflicts[errUrl].push(errUrlMap[errUrl]); } errUrlConflicts[errUrl].push(id); } else if (!skipNew) { errUrlMap[errUrl] = id; } } for (id in registry) { if (hasProp(registry, id) && id.indexOf('_@r') !== 0) { hasUndefined = true; mod = getOwn(registry, id); idParts = id.split('!'); pluginId = idParts[0]; if (id.indexOf('_unnormalized') === -1 && mod && mod.enabled) { populateErrUrlMap(id, mod.map.url); } //Look for plugins that did not call load() //But skip plugin IDs that were already inlined and called //define() with a name. if (!hasProp(layer.modulesWithNames, id) && idParts.length > 1) { if (falseProp(failedPluginMap, pluginId)) { failedPluginIds.push(pluginId); } pluginResources = failedPluginMap[pluginId]; if (!pluginResources) { pluginResources = failedPluginMap[pluginId] = []; } pluginResources.push(id + (mod.error ? ': ' + mod.error : '')); } } } // If have some modules that are not defined/stuck in the registry, // then check defined modules for URL overlap. if (hasUndefined) { for (id in defined) { if (hasProp(defined, id) && id.indexOf('!') === -1) { populateErrUrlMap(id, require.toUrl(id) + '.js', true); } } } if (errIds.length || failedPluginIds.length) { if (failedPluginIds.length) { errMessage += 'Loader plugin' + (failedPluginIds.length === 1 ? '' : 's') + ' did not call ' + 'the load callback in the build:\n' + failedPluginIds.map(function (pluginId) { var pluginResources = failedPluginMap[pluginId]; return pluginId + ':\n ' + pluginResources.join('\n '); }).join('\n') + '\n'; } errMessage += 'Module loading did not complete for: ' + errIds.join(', '); if (hasErrUrl) { errMessage += '\nThe following modules share the same URL. This ' + 'could be a misconfiguration if that URL only has ' + 'one anonymous module in it:'; for (prop in errUrlConflicts) { if (hasProp(errUrlConflicts, prop)) { errMessage += '\n' + prop + ': ' + errUrlConflicts[prop].join(', '); } } } throw new Error(errMessage); } }; build.createOverrideConfig = function (config, override) { var cfg = copyConfig(config), oride = copyConfig(override); lang.eachProp(oride, function (value, prop) { if (hasProp(build.objProps, prop)) { //An object property, merge keys. Start a new object //so that source object in config does not get modified. cfg[prop] = {}; lang.mixin(cfg[prop], config[prop], true); lang.mixin(cfg[prop], override[prop], true); } else { cfg[prop] = override[prop]; } }); return cfg; }; /** * Uses the module build config object to create an flattened version * of the module, with deep dependencies included. * * @param {Object} module the module object from the build config info. * * @param {Object} layer the layer object returned from build.traceDependencies. * * @param {Object} the build config object. * * @returns {Object} with two properties: "text", the text of the flattened * module, and "buildText", a string of text representing which files were * included in the flattened module text. */ build.flattenModule = function (module, layer, config) { var fileContents, sourceMapGenerator, sourceMapBase, buildFileContents = ''; return prim().start(function () { var reqIndex, currContents, fileForSourceMap, moduleName, shim, packageName, parts, builder, writeApi, namespace, namespaceWithDot, stubModulesByName, context = layer.context, onLayerEnds = [], onLayerEndAdded = {}, pkgsMainMap = {}; //Use override settings, particularly for pragmas //Do this before the var readings since it reads config values. if (module.override) { config = build.createOverrideConfig(config, module.override); } namespace = config.namespace || ''; namespaceWithDot = namespace ? namespace + '.' : ''; stubModulesByName = (module.stubModules && module.stubModules._byName) || {}; //Start build output for the module. module.onCompleteData = { name: module.name, path: (config.dir ? module._buildPath.replace(config.dir, "") : module._buildPath), included: [] }; buildFileContents += "\n" + module.onCompleteData.path + "\n----------------\n"; //If there was an existing file with require in it, hoist to the top. if (layer.existingRequireUrl) { reqIndex = layer.buildFilePaths.indexOf(layer.existingRequireUrl); if (reqIndex !== -1) { layer.buildFilePaths.splice(reqIndex, 1); layer.buildFilePaths.unshift(layer.existingRequireUrl); } } if (config.generateSourceMaps) { sourceMapBase = config.dir || config.baseUrl; if (module._buildPath === 'FUNCTION') { fileForSourceMap = (module.name || module.include[0] || 'FUNCTION') + '.build.js'; } else if (config.out) { fileForSourceMap = module._buildPath.split('/').pop(); } else { fileForSourceMap = module._buildPath.replace(sourceMapBase, ''); } sourceMapGenerator = new SourceMapGenerator({ file: fileForSourceMap }); } //Create a reverse lookup for packages main module IDs to their package //names, useful for knowing when to write out define() package main ID //adapters. lang.eachProp(layer.context.config.pkgs, function(value, prop) { pkgsMainMap[value] = prop; }); //Write the built module to disk, and build up the build output. fileContents = ""; if (config.wrap && config.wrap.__startMap) { config.wrap.__startMap.forEach(function (wrapFunction) { fileContents = wrapFunction(fileContents, config, sourceMapGenerator); }); } return prim.serial(layer.buildFilePaths.map(function (path) { return function () { var singleContents = ''; moduleName = layer.buildFileToModule[path]; //If the moduleName is a package main, then hold on to the //packageName in case an adapter needs to be written. packageName = getOwn(pkgsMainMap, moduleName); return prim().start(function () { //Figure out if the module is a result of a build plugin, and if so, //then delegate to that plugin. parts = context.makeModuleMap(moduleName); builder = parts.prefix && getOwn(context.defined, parts.prefix); if (builder) { if (builder.onLayerEnd && falseProp(onLayerEndAdded, parts.prefix)) { onLayerEnds.push(builder); onLayerEndAdded[parts.prefix] = true; } if (builder.write) { writeApi = function (input) { singleContents += "\n" + addSemiColon(input, config); if (config.onBuildWrite) { singleContents = config.onBuildWrite(moduleName, path, singleContents); } }; writeApi.asModule = function (moduleName, input) { singleContents += "\n" + addSemiColon(build.toTransport(namespace, moduleName, path, input, layer, { useSourceUrl: layer.context.config.useSourceUrl }), config); if (config.onBuildWrite) { singleContents = config.onBuildWrite(moduleName, path, singleContents); } }; builder.write(parts.prefix, parts.name, writeApi); } return; } else { return prim().start(function () { if (hasProp(stubModulesByName, moduleName)) { //Just want to insert a simple module definition instead //of the source module. Useful for plugins that inline //all their resources. if (hasProp(layer.context.plugins, moduleName)) { //Slightly different content for plugins, to indicate //that dynamic loading will not work. return 'define({load: function(id){throw new Error("Dynamic load not allowed: " + id);}});'; } else { return 'define({});'; } } else { return require._cacheReadAsync(path); } }).then(function (text) { var hasPackageName; currContents = text; if (config.cjsTranslate && (!config.shim || !lang.hasProp(config.shim, moduleName))) { currContents = commonJs.convert(path, currContents); } if (config.onBuildRead) { currContents = config.onBuildRead(moduleName, path, currContents); } if (packageName) { hasPackageName = (packageName === parse.getNamedDefine(currContents)); } if (namespace) { currContents = pragma.namespace(currContents, namespace); } currContents = build.toTransport(namespace, moduleName, path, currContents, layer, { useSourceUrl: config.useSourceUrl }); if (packageName && !hasPackageName) { currContents = addSemiColon(currContents, config) + '\n'; currContents += namespaceWithDot + "define('" + packageName + "', ['" + moduleName + "'], function (main) { return main; });\n"; } if (config.onBuildWrite) { currContents = config.onBuildWrite(moduleName, path, currContents); } //Semicolon is for files that are not well formed when //concatenated with other content. singleContents += addSemiColon(currContents, config); }); } }).then(function () { var shimDeps, shortPath = path.replace(config.dir, ""); module.onCompleteData.included.push(shortPath); buildFileContents += shortPath + "\n"; //Some files may not have declared a require module, and if so, //put in a placeholder call so the require does not try to load them //after the module is processed. //If we have a name, but no defined module, then add in the placeholder. if (moduleName && falseProp(layer.modulesWithNames, moduleName) && !config.skipModuleInsertion) { shim = config.shim && (getOwn(config.shim, moduleName) || (packageName && getOwn(config.shim, packageName))); if (shim) { shimDeps = lang.isArray(shim) ? shim : shim.deps; if (config.wrapShim) { singleContents = '(function(root) {\n' + namespaceWithDot + 'define("' + moduleName + '", ' + (shimDeps && shimDeps.length ? build.makeJsArrayString(shimDeps) + ', ' : '[], ') + 'function() {\n' + ' return (function() {\n' + singleContents + // Start with a \n in case last line is a comment // in the singleContents, like a sourceURL comment. '\n' + (shim.exportsFn ? shim.exportsFn() : '') + '\n' + ' }).apply(root, arguments);\n' + '});\n' + '}(this));\n'; } else { singleContents += '\n' + namespaceWithDot + 'define("' + moduleName + '", ' + (shimDeps && shimDeps.length ? build.makeJsArrayString(shimDeps) + ', ' : '') + (shim.exportsFn ? shim.exportsFn() : 'function(){}') + ');\n'; } } else { singleContents += '\n' + namespaceWithDot + 'define("' + moduleName + '", function(){});\n'; } } //Add line break at end of file, instead of at beginning, //so source map line numbers stay correct, but still allow //for some space separation between files in case ASI issues //for concatenation would cause an error otherwise. singleContents += '\n'; //Add to the source map and to the final contents fileContents = appendToFileContents(fileContents, singleContents, path, config, module, sourceMapGenerator); }); }; })).then(function () { if (onLayerEnds.length) { onLayerEnds.forEach(function (builder, index) { var path; if (typeof module.out === 'string') { path = module.out; } else if (typeof module._buildPath === 'string') { path = module._buildPath; } builder.onLayerEnd(function (input) { fileContents = appendToFileContents(fileContents, "\n" + addSemiColon(input, config), 'onLayerEnd' + index + '.js', config, module, sourceMapGenerator); }, { name: module.name, path: path }); }); } if (module.create) { //The ID is for a created layer. Write out //a module definition for it in case the //built file is used with enforceDefine //(#432) fileContents = appendToFileContents(fileContents, '\n' + namespaceWithDot + 'define("' + module.name + '", function(){});\n', 'module-create.js', config, module, sourceMapGenerator); } //Add a require at the end to kick start module execution, if that //was desired. Usually this is only specified when using small shim //loaders like almond. if (module.insertRequire) { fileContents = appendToFileContents(fileContents, '\n' + namespaceWithDot + 'require(["' + module.insertRequire.join('", "') + '"]);\n', 'module-insertRequire.js', config, module, sourceMapGenerator); } }); }).then(function () { if (config.wrap && config.wrap.__endMap) { config.wrap.__endMap.forEach(function (wrapFunction) { fileContents = wrapFunction(fileContents, config, sourceMapGenerator); }); } return { text: fileContents, buildText: buildFileContents, sourceMap: sourceMapGenerator ? JSON.stringify(sourceMapGenerator.toJSON(), null, ' ') : undefined }; }); }; //Converts an JS array of strings to a string representation. //Not using JSON.stringify() for Rhino's sake. build.makeJsArrayString = function (ary) { return '["' + ary.map(function (item) { //Escape any double quotes, backslashes return lang.jsEscape(item); }).join('","') + '"]'; }; build.toTransport = function (namespace, moduleName, path, contents, layer, options) { var baseUrl = layer && layer.context.config.baseUrl; function onFound(info) { //Only mark this module as having a name if not a named module, //or if a named module and the name matches expectations. if (layer && (info.needsId || info.foundId === moduleName)) { layer.modulesWithNames[moduleName] = true; } } //Convert path to be a local one to the baseUrl, useful for //useSourceUrl. if (baseUrl) { path = path.replace(baseUrl, ''); } return transform.toTransport(namespace, moduleName, path, contents, onFound, options); }; return build; }); } /** * Sets the default baseUrl for requirejs to be directory of top level * script. */ function setBaseUrl(fileName) { //Use the file name's directory as the baseUrl if available. dir = fileName.replace(/\\/g, '/'); if (dir.indexOf('/') !== -1) { dir = dir.split('/'); dir.pop(); dir = dir.join('/'); //Make sure dir is JS-escaped, since it will be part of a JS string. exec("require({baseUrl: '" + dir.replace(/[\\"']/g, '\\$&') + "'});"); } } function createRjsApi() { //Create a method that will run the optimzer given an object //config. requirejs.optimize = function (config, callback, errback) { if (!loadedOptimizedLib) { loadLib(); loadedOptimizedLib = true; } //Create the function that will be called once build modules //have been loaded. var runBuild = function (build, logger, quit) { //Make sure config has a log level, and if not, //make it "silent" by default. config.logLevel = config.hasOwnProperty('logLevel') ? config.logLevel : logger.SILENT; //Reset build internals first in case this is part //of a long-running server process that could have //exceptioned out in a bad state. It is only defined //after the first call though. if (requirejs._buildReset) { requirejs._buildReset(); requirejs._cacheReset(); } function done(result) { //And clean up, in case something else triggers //a build in another pathway. if (requirejs._buildReset) { requirejs._buildReset(); requirejs._cacheReset(); } // Ensure errors get propagated to the errback if (result instanceof Error) { throw result; } return result; } errback = errback || function (err) { // Using console here since logger may have // turned off error logging. Since quit is // called want to be sure a message is printed. console.log(err); quit(1); }; build(config).then(done, done).then(callback, errback); }; requirejs({ context: 'build' }, ['build', 'logger', 'env!env/quit'], runBuild); }; requirejs.tools = { useLib: function (contextName, callback) { if (!callback) { callback = contextName; contextName = 'uselib'; } if (!useLibLoaded[contextName]) { loadLib(); useLibLoaded[contextName] = true; } var req = requirejs({ context: contextName }); req(['build'], function () { callback(req); }); } }; requirejs.define = define; } //If in Node, and included via a require('requirejs'), just export and //THROW IT ON THE GROUND! if (env === 'node' && reqMain !== module) { setBaseUrl(path.resolve(reqMain ? reqMain.filename : '.')); createRjsApi(); module.exports = requirejs; return; } else if (env === 'browser') { //Only option is to use the API. setBaseUrl(location.href); createRjsApi(); return; } else if ((env === 'rhino' || env === 'xpconnect') && //User sets up requirejsAsLib variable to indicate it is loaded //via load() to be used as a library. typeof requirejsAsLib !== 'undefined' && requirejsAsLib) { //This script is loaded via rhino's load() method, expose the //API and get out. setBaseUrl(fileName); createRjsApi(); return; } if (commandOption === 'o') { //Do the optimizer work. loadLib(); /* * Create a build.js file that has the build options you want and pass that * build file to this file to do the build. See example.build.js for more information. */ /*jslint strict: false, nomen: false */ /*global require: false */ require({ baseUrl: require.s.contexts._.config.baseUrl, //Use a separate context than the default context so that the //build can use the default context. context: 'build', catchError: { define: true } }, ['env!env/args', 'env!env/quit', 'logger', 'build'], function (args, quit, logger, build) { build(args).then(function () {}, function (err) { logger.error(err); quit(1); }); }); } else if (commandOption === 'v') { console.log('r.js: ' + version + ', RequireJS: ' + this.requirejsVars.require.version + ', UglifyJS: 2.6.1'); } else if (commandOption === 'convert') { loadLib(); this.requirejsVars.require(['env!env/args', 'commonJs', 'env!env/print'], function (args, commonJs, print) { var srcDir, outDir; srcDir = args[0]; outDir = args[1]; if (!srcDir || !outDir) { print('Usage: path/to/commonjs/modules output/dir'); return; } commonJs.convertDir(args[0], args[1]); }); } else { //Just run an app //Load the bundled libraries for use in the app. if (commandOption === 'lib') { loadLib(); } setBaseUrl(fileName); if (exists(fileName)) { exec(readFile(fileName), fileName); } else { showHelp(); } } }((typeof console !== 'undefined' ? console : undefined), (typeof Packages !== 'undefined' || (typeof window === 'undefined' && typeof Components !== 'undefined' && Components.interfaces) ? Array.prototype.slice.call(arguments, 0) : []), (typeof readFile !== 'undefined' ? readFile : undefined)));
/* =================================================== * bootstrap-transition.js v2.3.0 * http://twitter.github.com/bootstrap/javascript.html#transitions * =================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================== */ !function ($) { "use strict"; // jshint ;_; /* CSS TRANSITION SUPPORT (http://www.modernizr.com/) * ======================================================= */ $(function () { $.support.transition = (function () { var transitionEnd = (function () { var el = document.createElement('bootstrap') , transEndEventNames = { 'WebkitTransition' : 'webkitTransitionEnd' , 'MozTransition' : 'transitionend' , 'OTransition' : 'oTransitionEnd otransitionend' , 'transition' : 'transitionend' } , name for (name in transEndEventNames){ if (el.style[name] !== undefined) { return transEndEventNames[name] } } }()) return transitionEnd && { end: transitionEnd } })() }) }(window.jQuery); /* ========================================================= * bootstrap-modal.js v2.3.0 * http://twitter.github.com/bootstrap/javascript.html#modals * ========================================================= * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================= */ !function ($) { "use strict"; // jshint ;_; /* MODAL CLASS DEFINITION * ====================== */ var Modal = function (element, options) { this.options = options this.$element = $(element) .delegate('[data-dismiss="modal"]', 'click.dismiss.modal', $.proxy(this.hide, this)) this.options.remote && this.$element.find('.modal-body').load(this.options.remote) } Modal.prototype = { constructor: Modal , toggle: function () { return this[!this.isShown ? 'show' : 'hide']() } , show: function () { var that = this , e = $.Event('show') this.$element.trigger(e) if (this.isShown || e.isDefaultPrevented()) return this.isShown = true this.escape() this.backdrop(function () { var transition = $.support.transition && that.$element.hasClass('fade') if (!that.$element.parent().length) { that.$element.appendTo(document.body) //don't move modals dom position } that.$element.show() if (transition) { that.$element[0].offsetWidth // force reflow } that.$element .addClass('in') .attr('aria-hidden', false) that.enforceFocus() transition ? that.$element.one($.support.transition.end, function () { that.$element.focus().trigger('shown') }) : that.$element.focus().trigger('shown') }) } , hide: function (e) { e && e.preventDefault() var that = this e = $.Event('hide') this.$element.trigger(e) if (!this.isShown || e.isDefaultPrevented()) return this.isShown = false this.escape() $(document).off('focusin.modal') this.$element .removeClass('in') .attr('aria-hidden', true) $.support.transition && this.$element.hasClass('fade') ? this.hideWithTransition() : this.hideModal() } , enforceFocus: function () { var that = this $(document).on('focusin.modal', function (e) { if (that.$element[0] !== e.target && !that.$element.has(e.target).length) { that.$element.focus() } }) } , escape: function () { var that = this if (this.isShown && this.options.keyboard) { this.$element.on('keyup.dismiss.modal', function ( e ) { e.which == 27 && that.hide() }) } else if (!this.isShown) { this.$element.off('keyup.dismiss.modal') } } , hideWithTransition: function () { var that = this , timeout = setTimeout(function () { that.$element.off($.support.transition.end) that.hideModal() }, 500) this.$element.one($.support.transition.end, function () { clearTimeout(timeout) that.hideModal() }) } , hideModal: function () { var that = this this.$element.hide() this.backdrop(function () { that.removeBackdrop() that.$element.trigger('hidden') }) } , removeBackdrop: function () { this.$backdrop.remove() this.$backdrop = null } , backdrop: function (callback) { var that = this , animate = this.$element.hasClass('fade') ? 'fade' : '' if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />') .appendTo(document.body) this.$backdrop.click( this.options.backdrop == 'static' ? $.proxy(this.$element[0].focus, this.$element[0]) : $.proxy(this.hide, this) ) if (doAnimate) this.$backdrop[0].offsetWidth // force reflow this.$backdrop.addClass('in') if (!callback) return doAnimate ? this.$backdrop.one($.support.transition.end, callback) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in') $.support.transition && this.$element.hasClass('fade')? this.$backdrop.one($.support.transition.end, callback) : callback() } else if (callback) { callback() } } } /* MODAL PLUGIN DEFINITION * ======================= */ var old = $.fn.modal $.fn.modal = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('modal') , options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option) if (!data) $this.data('modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option]() else if (options.show) data.show() }) } $.fn.modal.defaults = { backdrop: true , keyboard: true , show: true } $.fn.modal.Constructor = Modal /* MODAL NO CONFLICT * ================= */ $.fn.modal.noConflict = function () { $.fn.modal = old return this } /* MODAL DATA-API * ============== */ $(document).on('click.modal.data-api', '[data-toggle="modal"]', function (e) { var $this = $(this) , href = $this.attr('href') , $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7 , option = $target.data('modal') ? 'toggle' : $.extend({ remote:!/#/.test(href) && href }, $target.data(), $this.data()) e.preventDefault() $target .modal(option) .one('hide', function () { $this.focus() }) }) }(window.jQuery); /* ============================================================ * bootstrap-dropdown.js v2.3.0 * http://twitter.github.com/bootstrap/javascript.html#dropdowns * ============================================================ * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================ */ !function ($) { "use strict"; // jshint ;_; /* DROPDOWN CLASS DEFINITION * ========================= */ var toggle = '[data-toggle=dropdown]' , Dropdown = function (element) { var $el = $(element).on('click.dropdown.data-api', this.toggle) $('html').on('click.dropdown.data-api', function () { $el.parent().removeClass('open') }) } Dropdown.prototype = { constructor: Dropdown , toggle: function (e) { var $this = $(this) , $parent , isActive if ($this.is('.disabled, :disabled')) return $parent = getParent($this) isActive = $parent.hasClass('open') clearMenus() if (!isActive) { $parent.toggleClass('open') } $this.focus() return false } , keydown: function (e) { var $this , $items , $active , $parent , isActive , index if (!/(38|40|27)/.test(e.keyCode)) return $this = $(this) e.preventDefault() e.stopPropagation() if ($this.is('.disabled, :disabled')) return $parent = getParent($this) isActive = $parent.hasClass('open') if (!isActive || (isActive && e.keyCode == 27)) { if (e.which == 27) $parent.find(toggle).focus() return $this.click() } $items = $('[role=menu] li:not(.divider):visible a', $parent) if (!$items.length) return index = $items.index($items.filter(':focus')) if (e.keyCode == 38 && index > 0) index-- // up if (e.keyCode == 40 && index < $items.length - 1) index++ // down if (!~index) index = 0 $items .eq(index) .focus() } } function clearMenus() { $(toggle).each(function () { getParent($(this)).removeClass('open') }) } function getParent($this) { var selector = $this.attr('data-target') , $parent if (!selector) { selector = $this.attr('href') selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } $parent = selector && $(selector) if (!$parent || !$parent.length) $parent = $this.parent() return $parent } /* DROPDOWN PLUGIN DEFINITION * ========================== */ var old = $.fn.dropdown $.fn.dropdown = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('dropdown') if (!data) $this.data('dropdown', (data = new Dropdown(this))) if (typeof option == 'string') data[option].call($this) }) } $.fn.dropdown.Constructor = Dropdown /* DROPDOWN NO CONFLICT * ==================== */ $.fn.dropdown.noConflict = function () { $.fn.dropdown = old return this } /* APPLY TO STANDARD DROPDOWN ELEMENTS * =================================== */ $(document) .on('click.dropdown.data-api', clearMenus) .on('click.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() }) .on('.dropdown-menu', function (e) { e.stopPropagation() }) .on('click.dropdown.data-api' , toggle, Dropdown.prototype.toggle) .on('keydown.dropdown.data-api', toggle + ', [role=menu]' , Dropdown.prototype.keydown) }(window.jQuery); /* ============================================================= * bootstrap-scrollspy.js v2.3.0 * http://twitter.github.com/bootstrap/javascript.html#scrollspy * ============================================================= * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================== */ !function ($) { "use strict"; // jshint ;_; /* SCROLLSPY CLASS DEFINITION * ========================== */ function ScrollSpy(element, options) { var process = $.proxy(this.process, this) , $element = $(element).is('body') ? $(window) : $(element) , href this.options = $.extend({}, $.fn.scrollspy.defaults, options) this.$scrollElement = $element.on('scroll.scroll-spy.data-api', process) this.selector = (this.options.target || ((href = $(element).attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 || '') + ' .nav li > a' this.$body = $('body') this.refresh() this.process() } ScrollSpy.prototype = { constructor: ScrollSpy , refresh: function () { var self = this , $targets this.offsets = $([]) this.targets = $([]) $targets = this.$body .find(this.selector) .map(function () { var $el = $(this) , href = $el.data('target') || $el.attr('href') , $href = /^#\w/.test(href) && $(href) return ( $href && $href.length && [[ $href.position().top + (!$.isWindow(self.$scrollElement.get(0)) && self.$scrollElement.scrollTop()), href ]] ) || null }) .sort(function (a, b) { return a[0] - b[0] }) .each(function () { self.offsets.push(this[0]) self.targets.push(this[1]) }) } , process: function () { var scrollTop = this.$scrollElement.scrollTop() + this.options.offset , scrollHeight = this.$scrollElement[0].scrollHeight || this.$body[0].scrollHeight , maxScroll = scrollHeight - this.$scrollElement.height() , offsets = this.offsets , targets = this.targets , activeTarget = this.activeTarget , i if (scrollTop >= maxScroll) { return activeTarget != (i = targets.last()[0]) && this.activate ( i ) } for (i = offsets.length; i--;) { activeTarget != targets[i] && scrollTop >= offsets[i] && (!offsets[i + 1] || scrollTop <= offsets[i + 1]) && this.activate( targets[i] ) } } , activate: function (target) { var active , selector this.activeTarget = target $(this.selector) .parent('.active') .removeClass('active') selector = this.selector + '[data-target="' + target + '"],' + this.selector + '[href="' + target + '"]' active = $(selector) .parent('li') .addClass('active') if (active.parent('.dropdown-menu').length) { active = active.closest('li.dropdown').addClass('active') } active.trigger('activate') } } /* SCROLLSPY PLUGIN DEFINITION * =========================== */ var old = $.fn.scrollspy $.fn.scrollspy = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('scrollspy') , options = typeof option == 'object' && option if (!data) $this.data('scrollspy', (data = new ScrollSpy(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.scrollspy.Constructor = ScrollSpy $.fn.scrollspy.defaults = { offset: 10 } /* SCROLLSPY NO CONFLICT * ===================== */ $.fn.scrollspy.noConflict = function () { $.fn.scrollspy = old return this } /* SCROLLSPY DATA-API * ================== */ $(window).on('load', function () { $('[data-spy="scroll"]').each(function () { var $spy = $(this) $spy.scrollspy($spy.data()) }) }) }(window.jQuery); /* ======================================================== * bootstrap-tab.js v2.3.0 * http://twitter.github.com/bootstrap/javascript.html#tabs * ======================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ======================================================== */ !function ($) { "use strict"; // jshint ;_; /* TAB CLASS DEFINITION * ==================== */ var Tab = function (element) { this.element = $(element) } Tab.prototype = { constructor: Tab , show: function () { var $this = this.element , $ul = $this.closest('ul:not(.dropdown-menu)') , selector = $this.attr('data-target') , previous , $target , e if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } if ( $this.parent('li').hasClass('active') ) return previous = $ul.find('.active:last a')[0] e = $.Event('show', { relatedTarget: previous }) $this.trigger(e) if (e.isDefaultPrevented()) return $target = $(selector) this.activate($this.parent('li'), $ul) this.activate($target, $target.parent(), function () { $this.trigger({ type: 'shown' , relatedTarget: previous }) }) } , activate: function ( element, container, callback) { var $active = container.find('> .active') , transition = callback && $.support.transition && $active.hasClass('fade') function next() { $active .removeClass('active') .find('> .dropdown-menu > .active') .removeClass('active') element.addClass('active') if (transition) { element[0].offsetWidth // reflow for transition element.addClass('in') } else { element.removeClass('fade') } if ( element.parent('.dropdown-menu') ) { element.closest('li.dropdown').addClass('active') } callback && callback() } transition ? $active.one($.support.transition.end, next) : next() $active.removeClass('in') } } /* TAB PLUGIN DEFINITION * ===================== */ var old = $.fn.tab $.fn.tab = function ( option ) { return this.each(function () { var $this = $(this) , data = $this.data('tab') if (!data) $this.data('tab', (data = new Tab(this))) if (typeof option == 'string') data[option]() }) } $.fn.tab.Constructor = Tab /* TAB NO CONFLICT * =============== */ $.fn.tab.noConflict = function () { $.fn.tab = old return this } /* TAB DATA-API * ============ */ $(document).on('click.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) { e.preventDefault() $(this).tab('show') }) }(window.jQuery); /* ========================================================== * bootstrap-affix.js v2.3.0 * http://twitter.github.com/bootstrap/javascript.html#affix * ========================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================== */ !function ($) { "use strict"; // jshint ;_; /* AFFIX CLASS DEFINITION * ====================== */ var Affix = function (element, options) { this.options = $.extend({}, $.fn.affix.defaults, options) this.$window = $(window) .on('scroll.affix.data-api', $.proxy(this.checkPosition, this)) .on('click.affix.data-api', $.proxy(function () { setTimeout($.proxy(this.checkPosition, this), 1) }, this)) this.$element = $(element) this.checkPosition() } Affix.prototype.checkPosition = function () { if (!this.$element.is(':visible')) return var scrollHeight = $(document).height() , scrollTop = this.$window.scrollTop() , position = this.$element.offset() , offset = this.options.offset , offsetBottom = offset.bottom , offsetTop = offset.top , reset = 'affix affix-top affix-bottom' , affix if (typeof offset != 'object') offsetBottom = offsetTop = offset if (typeof offsetTop == 'function') offsetTop = offset.top() if (typeof offsetBottom == 'function') offsetBottom = offset.bottom() affix = this.unpin != null && (scrollTop + this.unpin <= position.top) ? false : offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ? 'bottom' : offsetTop != null && scrollTop <= offsetTop ? 'top' : false if (this.affixed === affix) return this.affixed = affix this.unpin = affix == 'bottom' ? position.top - scrollTop : null this.$element.removeClass(reset).addClass('affix' + (affix ? '-' + affix : '')) } /* AFFIX PLUGIN DEFINITION * ======================= */ var old = $.fn.affix $.fn.affix = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('affix') , options = typeof option == 'object' && option if (!data) $this.data('affix', (data = new Affix(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.affix.Constructor = Affix $.fn.affix.defaults = { offset: 0 } /* AFFIX NO CONFLICT * ================= */ $.fn.affix.noConflict = function () { $.fn.affix = old return this } /* AFFIX DATA-API * ============== */ $(window).on('load', function () { $('[data-spy="affix"]').each(function () { var $spy = $(this) , data = $spy.data() data.offset = data.offset || {} data.offsetBottom && (data.offset.bottom = data.offsetBottom) data.offsetTop && (data.offset.top = data.offsetTop) $spy.affix(data) }) }) }(window.jQuery); /* ========================================================== * bootstrap-alert.js v2.3.0 * http://twitter.github.com/bootstrap/javascript.html#alerts * ========================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================== */ !function ($) { "use strict"; // jshint ;_; /* ALERT CLASS DEFINITION * ====================== */ var dismiss = '[data-dismiss="alert"]' , Alert = function (el) { $(el).on('click', dismiss, this.close) } Alert.prototype.close = function (e) { var $this = $(this) , selector = $this.attr('data-target') , $parent if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } $parent = $(selector) e && e.preventDefault() $parent.length || ($parent = $this.hasClass('alert') ? $this : $this.parent()) $parent.trigger(e = $.Event('close')) if (e.isDefaultPrevented()) return $parent.removeClass('in') function removeElement() { $parent .trigger('closed') .remove() } $.support.transition && $parent.hasClass('fade') ? $parent.on($.support.transition.end, removeElement) : removeElement() } /* ALERT PLUGIN DEFINITION * ======================= */ var old = $.fn.alert $.fn.alert = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('alert') if (!data) $this.data('alert', (data = new Alert(this))) if (typeof option == 'string') data[option].call($this) }) } $.fn.alert.Constructor = Alert /* ALERT NO CONFLICT * ================= */ $.fn.alert.noConflict = function () { $.fn.alert = old return this } /* ALERT DATA-API * ============== */ $(document).on('click.alert.data-api', dismiss, Alert.prototype.close) }(window.jQuery); /* ============================================================ * bootstrap-button.js v2.3.0 * http://twitter.github.com/bootstrap/javascript.html#buttons * ============================================================ * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================ */ !function ($) { "use strict"; // jshint ;_; /* BUTTON PUBLIC CLASS DEFINITION * ============================== */ var Button = function (element, options) { this.$element = $(element) this.options = $.extend({}, $.fn.button.defaults, options) } Button.prototype.setState = function (state) { var d = 'disabled' , $el = this.$element , data = $el.data() , val = $el.is('input') ? 'val' : 'html' state = state + 'Text' data.resetText || $el.data('resetText', $el[val]()) $el[val](data[state] || this.options[state]) // push to event loop to allow forms to submit setTimeout(function () { state == 'loadingText' ? $el.addClass(d).attr(d, d) : $el.removeClass(d).removeAttr(d) }, 0) } Button.prototype.toggle = function () { var $parent = this.$element.closest('[data-toggle="buttons-radio"]') $parent && $parent .find('.active') .removeClass('active') this.$element.toggleClass('active') } /* BUTTON PLUGIN DEFINITION * ======================== */ var old = $.fn.button $.fn.button = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('button') , options = typeof option == 'object' && option if (!data) $this.data('button', (data = new Button(this, options))) if (option == 'toggle') data.toggle() else if (option) data.setState(option) }) } $.fn.button.defaults = { loadingText: 'loading...' } $.fn.button.Constructor = Button /* BUTTON NO CONFLICT * ================== */ $.fn.button.noConflict = function () { $.fn.button = old return this } /* BUTTON DATA-API * =============== */ $(document).on('click.button.data-api', '[data-toggle^=button]', function (e) { var $btn = $(e.target) if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn') $btn.button('toggle') }) }(window.jQuery); /* ============================================================= * bootstrap-collapse.js v2.3.0 * http://twitter.github.com/bootstrap/javascript.html#collapse * ============================================================= * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================ */ !function ($) { "use strict"; // jshint ;_; /* COLLAPSE PUBLIC CLASS DEFINITION * ================================ */ var Collapse = function (element, options) { this.$element = $(element) this.options = $.extend({}, $.fn.collapse.defaults, options) if (this.options.parent) { this.$parent = $(this.options.parent) } this.options.toggle && this.toggle() } Collapse.prototype = { constructor: Collapse , dimension: function () { var hasWidth = this.$element.hasClass('width') return hasWidth ? 'width' : 'height' } , show: function () { var dimension , scroll , actives , hasData if (this.transitioning || this.$element.hasClass('in')) return dimension = this.dimension() scroll = $.camelCase(['scroll', dimension].join('-')) actives = this.$parent && this.$parent.find('> .accordion-group > .in') if (actives && actives.length) { hasData = actives.data('collapse') if (hasData && hasData.transitioning) return actives.collapse('hide') hasData || actives.data('collapse', null) } this.$element[dimension](0) this.transition('addClass', $.Event('show'), 'shown') $.support.transition && this.$element[dimension](this.$element[0][scroll]) } , hide: function () { var dimension if (this.transitioning || !this.$element.hasClass('in')) return dimension = this.dimension() this.reset(this.$element[dimension]()) this.transition('removeClass', $.Event('hide'), 'hidden') this.$element[dimension](0) } , reset: function (size) { var dimension = this.dimension() this.$element .removeClass('collapse') [dimension](size || 'auto') [0].offsetWidth this.$element[size !== null ? 'addClass' : 'removeClass']('collapse') return this } , transition: function (method, startEvent, completeEvent) { var that = this , complete = function () { if (startEvent.type == 'show') that.reset() that.transitioning = 0 that.$element.trigger(completeEvent) } this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return this.transitioning = 1 this.$element[method]('in') $.support.transition && this.$element.hasClass('collapse') ? this.$element.one($.support.transition.end, complete) : complete() } , toggle: function () { this[this.$element.hasClass('in') ? 'hide' : 'show']() } } /* COLLAPSE PLUGIN DEFINITION * ========================== */ var old = $.fn.collapse $.fn.collapse = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('collapse') , options = $.extend({}, $.fn.collapse.defaults, $this.data(), typeof option == 'object' && option) if (!data) $this.data('collapse', (data = new Collapse(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.collapse.defaults = { toggle: true } $.fn.collapse.Constructor = Collapse /* COLLAPSE NO CONFLICT * ==================== */ $.fn.collapse.noConflict = function () { $.fn.collapse = old return this } /* COLLAPSE DATA-API * ================= */ $(document).on('click.collapse.data-api', '[data-toggle=collapse]', function (e) { var $this = $(this), href , target = $this.attr('data-target') || e.preventDefault() || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7 , option = $(target).data('collapse') ? 'toggle' : $this.data() $this[$(target).hasClass('in') ? 'addClass' : 'removeClass']('collapsed') $(target).collapse(option) }) }(window.jQuery); /* ========================================================== * bootstrap-carousel.js v2.3.0 * http://twitter.github.com/bootstrap/javascript.html#carousel * ========================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================== */ !function ($) { "use strict"; // jshint ;_; /* CAROUSEL CLASS DEFINITION * ========================= */ var Carousel = function (element, options) { this.$element = $(element) this.$indicators = this.$element.find('.carousel-indicators') this.options = options this.options.pause == 'hover' && this.$element .on('mouseenter', $.proxy(this.pause, this)) .on('mouseleave', $.proxy(this.cycle, this)) } Carousel.prototype = { cycle: function (e) { if (!e) this.paused = false if (this.interval) clearInterval(this.interval); this.options.interval && !this.paused && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) return this } , getActiveIndex: function () { this.$active = this.$element.find('.item.active') this.$items = this.$active.parent().children() return this.$items.index(this.$active) } , to: function (pos) { var activeIndex = this.getActiveIndex() , that = this if (pos > (this.$items.length - 1) || pos < 0) return if (this.sliding) { return this.$element.one('slid', function () { that.to(pos) }) } if (activeIndex == pos) { return this.pause().cycle() } return this.slide(pos > activeIndex ? 'next' : 'prev', $(this.$items[pos])) } , pause: function (e) { if (!e) this.paused = true if (this.$element.find('.next, .prev').length && $.support.transition.end) { this.$element.trigger($.support.transition.end) this.cycle() } clearInterval(this.interval) this.interval = null return this } , next: function () { if (this.sliding) return return this.slide('next') } , prev: function () { if (this.sliding) return return this.slide('prev') } , slide: function (type, next) { var $active = this.$element.find('.item.active') , $next = next || $active[type]() , isCycling = this.interval , direction = type == 'next' ? 'left' : 'right' , fallback = type == 'next' ? 'first' : 'last' , that = this , e this.sliding = true isCycling && this.pause() $next = $next.length ? $next : this.$element.find('.item')[fallback]() e = $.Event('slide', { relatedTarget: $next[0] , direction: direction }) if ($next.hasClass('active')) return if (this.$indicators.length) { this.$indicators.find('.active').removeClass('active') this.$element.one('slid', function () { var $nextIndicator = $(that.$indicators.children()[that.getActiveIndex()]) $nextIndicator && $nextIndicator.addClass('active') }) } if ($.support.transition && this.$element.hasClass('slide')) { this.$element.trigger(e) if (e.isDefaultPrevented()) return $next.addClass(type) $next[0].offsetWidth // force reflow $active.addClass(direction) $next.addClass(direction) this.$element.one($.support.transition.end, function () { $next.removeClass([type, direction].join(' ')).addClass('active') $active.removeClass(['active', direction].join(' ')) that.sliding = false setTimeout(function () { that.$element.trigger('slid') }, 0) }) } else { this.$element.trigger(e) if (e.isDefaultPrevented()) return $active.removeClass('active') $next.addClass('active') this.sliding = false this.$element.trigger('slid') } isCycling && this.cycle() return this } } /* CAROUSEL PLUGIN DEFINITION * ========================== */ var old = $.fn.carousel $.fn.carousel = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('carousel') , options = $.extend({}, $.fn.carousel.defaults, typeof option == 'object' && option) , action = typeof option == 'string' ? option : options.slide if (!data) $this.data('carousel', (data = new Carousel(this, options))) if (typeof option == 'number') data.to(option) else if (action) data[action]() else if (options.interval) data.pause().cycle() }) } $.fn.carousel.defaults = { interval: 5000 , pause: 'hover' } $.fn.carousel.Constructor = Carousel /* CAROUSEL NO CONFLICT * ==================== */ $.fn.carousel.noConflict = function () { $.fn.carousel = old return this } /* CAROUSEL DATA-API * ================= */ $(document).on('click.carousel.data-api', '[data-slide], [data-slide-to]', function (e) { var $this = $(this), href , $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 , options = $.extend({}, $target.data(), $this.data()) , slideIndex $target.carousel(options) if (slideIndex = $this.attr('data-slide-to')) { $target.data('carousel').pause().to(slideIndex).cycle() } e.preventDefault() }) }(window.jQuery); /* ============================================================= * bootstrap-typeahead.js v2.3.0 * http://twitter.github.com/bootstrap/javascript.html#typeahead * ============================================================= * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================ */ !function($){ "use strict"; // jshint ;_; /* TYPEAHEAD PUBLIC CLASS DEFINITION * ================================= */ var Typeahead = function (element, options) { this.$element = $(element) this.options = $.extend({}, $.fn.typeahead.defaults, options) this.matcher = this.options.matcher || this.matcher this.sorter = this.options.sorter || this.sorter this.highlighter = this.options.highlighter || this.highlighter this.updater = this.options.updater || this.updater this.source = this.options.source this.$menu = $(this.options.menu) this.shown = false this.listen() } Typeahead.prototype = { constructor: Typeahead , select: function () { var val = this.$menu.find('.active').attr('data-value') this.$element .val(this.updater(val)) .change() return this.hide() } , updater: function (item) { return item } , show: function () { var pos = $.extend({}, this.$element.position(), { height: this.$element[0].offsetHeight }) this.$menu .insertAfter(this.$element) .css({ top: pos.top + pos.height , left: pos.left }) .show() this.shown = true return this } , hide: function () { this.$menu.hide() this.shown = false return this } , lookup: function (event) { var items this.query = this.$element.val() if (!this.query || this.query.length < this.options.minLength) { return this.shown ? this.hide() : this } items = $.isFunction(this.source) ? this.source(this.query, $.proxy(this.process, this)) : this.source return items ? this.process(items) : this } , process: function (items) { var that = this items = $.grep(items, function (item) { return that.matcher(item) }) items = this.sorter(items) if (!items.length) { return this.shown ? this.hide() : this } return this.render(items.slice(0, this.options.items)).show() } , matcher: function (item) { return ~item.toLowerCase().indexOf(this.query.toLowerCase()) } , sorter: function (items) { var beginswith = [] , caseSensitive = [] , caseInsensitive = [] , item while (item = items.shift()) { if (!item.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(item) else if (~item.indexOf(this.query)) caseSensitive.push(item) else caseInsensitive.push(item) } return beginswith.concat(caseSensitive, caseInsensitive) } , highlighter: function (item) { var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&') return item.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) { return '<strong>' + match + '</strong>' }) } , render: function (items) { var that = this items = $(items).map(function (i, item) { i = $(that.options.item).attr('data-value', item) i.find('a').html(that.highlighter(item)) return i[0] }) items.first().addClass('active') this.$menu.html(items) return this } , next: function (event) { var active = this.$menu.find('.active').removeClass('active') , next = active.next() if (!next.length) { next = $(this.$menu.find('li')[0]) } next.addClass('active') } , prev: function (event) { var active = this.$menu.find('.active').removeClass('active') , prev = active.prev() if (!prev.length) { prev = this.$menu.find('li').last() } prev.addClass('active') } , listen: function () { this.$element .on('focus', $.proxy(this.focus, this)) .on('blur', $.proxy(this.blur, this)) .on('keypress', $.proxy(this.keypress, this)) .on('keyup', $.proxy(this.keyup, this)) if (this.eventSupported('keydown')) { this.$element.on('keydown', $.proxy(this.keydown, this)) } this.$menu .on('click', $.proxy(this.click, this)) .on('mouseenter', 'li', $.proxy(this.mouseenter, this)) .on('mouseleave', 'li', $.proxy(this.mouseleave, this)) } , eventSupported: function(eventName) { var isSupported = eventName in this.$element if (!isSupported) { this.$element.setAttribute(eventName, 'return;') isSupported = typeof this.$element[eventName] === 'function' } return isSupported } , move: function (e) { if (!this.shown) return switch(e.keyCode) { case 9: // tab case 13: // enter case 27: // escape e.preventDefault() break case 38: // up arrow e.preventDefault() this.prev() break case 40: // down arrow e.preventDefault() this.next() break } e.stopPropagation() } , keydown: function (e) { this.suppressKeyPressRepeat = ~$.inArray(e.keyCode, [40,38,9,13,27]) this.move(e) } , keypress: function (e) { if (this.suppressKeyPressRepeat) return this.move(e) } , keyup: function (e) { switch(e.keyCode) { case 40: // down arrow case 38: // up arrow case 16: // shift case 17: // ctrl case 18: // alt break case 9: // tab case 13: // enter if (!this.shown) return this.select() break case 27: // escape if (!this.shown) return this.hide() break default: this.lookup() } e.stopPropagation() e.preventDefault() } , focus: function (e) { this.focused = true } , blur: function (e) { this.focused = false if (!this.mousedover && this.shown) this.hide() } , click: function (e) { e.stopPropagation() e.preventDefault() this.select() this.$element.focus() } , mouseenter: function (e) { this.mousedover = true this.$menu.find('.active').removeClass('active') $(e.currentTarget).addClass('active') } , mouseleave: function (e) { this.mousedover = false if (!this.focused && this.shown) this.hide() } } /* TYPEAHEAD PLUGIN DEFINITION * =========================== */ var old = $.fn.typeahead $.fn.typeahead = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('typeahead') , options = typeof option == 'object' && option if (!data) $this.data('typeahead', (data = new Typeahead(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.typeahead.defaults = { source: [] , items: 8 , menu: '<ul class="typeahead dropdown-menu"></ul>' , item: '<li><a href="#"></a></li>' , minLength: 1 } $.fn.typeahead.Constructor = Typeahead /* TYPEAHEAD NO CONFLICT * =================== */ $.fn.typeahead.noConflict = function () { $.fn.typeahead = old return this } /* TYPEAHEAD DATA-API * ================== */ $(document).on('focus.typeahead.data-api', '[data-provide="typeahead"]', function (e) { var $this = $(this) if ($this.data('typeahead')) return $this.typeahead($this.data()) }) }(window.jQuery);
/* * Notice: Chris Sidi (hashtagchris) changed this file to remove the api-version parameter, * as a workaround for * https://github.com/AzureAD/azure-activedirectory-library-for-nodejs/issues/128 */ /* * @copyright * Copyright © Microsoft Open Technologies, Inc. * * All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http: *www.apache.org/licenses/LICENSE-2.0 * * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT. * * See the Apache License, Version 2.0 for the specific language * governing permissions and limitations under the License. */ 'use strict'; var _ = require('underscore'); require('date-utils'); // Adds a number of convenience methods to the builtin Date object. var querystring = require('querystring'); var uuid = require('uuid'); var request = require('request'); var url = require('url'); var async = require('async'); var constants = require('./constants'); var Logger = require('./log').Logger; var util = require('./util'); var OAuth2Parameters = constants.OAuth2.Parameters; var OAuth2ResponseParameters = constants.OAuth2.ResponseParameters; var DeviceCodeResponseParameters = constants.OAuth2.DeviceCodeResponseParameters; var IdTokenMap = constants.OAuth2.IdTokenMap; var TokenResponseFields = constants.TokenResponseFields; var UserCodeResponseFields = constants.UserCodeResponseFields; var IdTokenFields = constants.IdTokenFields; var TOKEN_RESPONSE_MAP = {}; TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.TOKEN_TYPE] = TokenResponseFields.TOKEN_TYPE; TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.ACCESS_TOKEN] = TokenResponseFields.ACCESS_TOKEN; TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.REFRESH_TOKEN] = TokenResponseFields.REFRESH_TOKEN; TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.CREATED_ON] = TokenResponseFields.CREATED_ON; TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.EXPIRES_ON] = TokenResponseFields.EXPIRES_ON; TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.EXPIRES_IN] = TokenResponseFields.EXPIRES_IN; TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.RESOURCE] = TokenResponseFields.RESOURCE; TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.ERROR] = TokenResponseFields.ERROR; TOKEN_RESPONSE_MAP[OAuth2ResponseParameters.ERROR_DESCRIPTION] = TokenResponseFields.ERROR_DESCRIPTION; var DEVICE_CODE_RESPONSE_MAP = {}; DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.DEVICE_CODE] = UserCodeResponseFields.DEVICE_CODE; DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.USER_CODE] = UserCodeResponseFields.USER_CODE; DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.VERIFICATION_URL] = UserCodeResponseFields.VERIFICATION_URL; DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.INTERVAL] = UserCodeResponseFields.INTERVAL; DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.EXPIRES_IN] = UserCodeResponseFields.EXPIRES_IN; DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.MESSAGE] = UserCodeResponseFields.MESSAGE; DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.ERROR] = UserCodeResponseFields.ERROR; DEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.ERROR_DESCRIPTION] = UserCodeResponseFields.ERROR_DESCRIPTION; /** * Constructs an instances of OAuth2Client * @constructor * @private * @param {object} callContext Contains any context information that applies to the request. * @param {string|url} authority An url that points to an authority. */ function OAuth2Client(callContext, authority) { this._tokenEndpoint = authority.tokenEndpoint; this._deviceCodeEndpoint = authority.deviceCodeEndpoint; this._log = new Logger('OAuth2Client', callContext._logContext); this._callContext = callContext; this._cancelPollingRequest = false; } /** * Constructs an OAuth 2.0 token request url. * @private * @return {URL} */ OAuth2Client.prototype._createTokenUrl = function () { var tokenUrl = url.parse(this._tokenEndpoint); var parameters = {}; tokenUrl.search = querystring.stringify(parameters); return tokenUrl; }; /** * Constructs the user code info request url. * @private * @return {URL} */ OAuth2Client.prototype._createDeviceCodeUrl = function () { var deviceCodeUrl = url.parse(this._deviceCodeEndpoint); var parameters = {}; deviceCodeUrl.search = querystring.stringify(parameters); return deviceCodeUrl; }; /** * @private * @param {object} obj An object in which integer values may reside. * @param {array} keys An array of strings that specify keys in which integers may need parsing. */ OAuth2Client.prototype._parseOptionalInts = function (obj, keys) { var self = this; keys.forEach(function(element) { if (_.has(obj, element)) { obj[element] = parseInt(obj[element], 10); if (isNaN(obj[element])) { throw self._log.createError(element + ' could not be parsed as an int.'); } } }); }; /** * Parses a JWS encoded JWT into it's three parts. * @param {string} jwtToken The token to parse. * @return {object} The three JWS parts, header, JWSPayload, and JWSSig, or undefined. */ OAuth2Client.prototype._crackJwt = function(jwtToken) { var idTokenPartsRegex = /^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$/; var matches = idTokenPartsRegex.exec(jwtToken); if (!matches || matches.length < 4) { this._log.warn('The returned id_token is not parseable.'); return; } var crackedToken = { header : matches[1], JWSPayload : matches[2], JWSSig : matches[3] }; return crackedToken; }; /** * Finds the value that should be used as the userId value. * @param {object} idToken The id token that parsed. * @returns {object} An object with a userId field and maybe a userIdIsDisplayable field. */ OAuth2Client.prototype._getUserId = function(idToken) { var userId; var isDisplayable; if (idToken.upn) { userId = idToken.upn; isDisplayable = true; } else if (idToken.email) { userId = idToken.email; isDisplayable = true; } else if (idToken.sub) { userId = idToken.sub; } if (!userId) { // generate a random GUID. userId = uuid.v4(); } var userIdVals = {}; userIdVals[IdTokenFields.USER_ID] = userId; if (isDisplayable) { userIdVals[IdTokenFields.IS_USER_ID_DISPLAYABLE] = true; } return userIdVals; }; function mapFields(inObj, outObj, map) { for (var key in inObj) { if (map[key]) { var mappedKey = map[key]; outObj[mappedKey] = inObj[key]; } } } /** * Given a decoded id token off the wire, this function extracts the values that * ADAL commonly returns to callers and translates the names to more user * friendly names. * @param {Object} idToken A decoded id token. * @return {Object} The set of extracted values with their new names. */ OAuth2Client.prototype._extractIdTokenValues = function(idToken) { var extractedValues = {}; _.extend(extractedValues, this._getUserId(idToken)); mapFields(idToken, extractedValues, IdTokenMap); return extractedValues; }; /** * Parses the value of the id_token OAuth 2 Reponse. * @param {string} encodedIdToken An unencrypted JWT token. * @return {object} returns the decoded id_token or undefined. */ OAuth2Client.prototype._parseIdToken = function(encodedIdToken) { var crackedToken = this._crackJwt(encodedIdToken); if (!crackedToken) { return; } var idToken; try { var base64IdToken = crackedToken.JWSPayload; var base64Decoded = util.base64DecodeStringUrlSafe(base64IdToken); if (!base64Decoded) { this._log.warn('The returned id_token could not be base64 url safe decoded.'); return; } idToken = JSON.parse(base64Decoded); } catch (err) { this._log.warn('the returned id_token could not be decoded'); this._log.warn('The returned id_token could not be decoded: ' + err.stack, true); return; } return this._extractIdTokenValues(idToken); }; /** * Validates the response returned from an OAuth 2.0 token request. * @private * @param {string} body The response as a string encoded JSON object. * @return {object} The parsed response. */ OAuth2Client.prototype._validateTokenResponse = function(body) { var wireResponse; var tokenResponse = {}; try { wireResponse = JSON.parse(body); } catch(e) { throw new Error('The token response returned from the server is unparseable as JSON'); } var intKeys = [ OAuth2ResponseParameters.EXPIRES_ON, OAuth2ResponseParameters.EXPIRES_IN, OAuth2ResponseParameters.CREATED_ON ]; this._parseOptionalInts(wireResponse, intKeys); if (wireResponse[OAuth2ResponseParameters.EXPIRES_IN]) { var expiresIn = wireResponse[OAuth2ResponseParameters.EXPIRES_IN]; var now = new Date(); wireResponse[OAuth2ResponseParameters.EXPIRES_ON] = now.add( { seconds : expiresIn }); } if (wireResponse[OAuth2ResponseParameters.CREATED_ON]) { var tempDate = new Date(); var createdOn = wireResponse[OAuth2ResponseParameters.CREATED_ON]; tempDate.setTime(createdOn); wireResponse[OAuth2ResponseParameters.CREATED_ON] = tempDate; } if (!wireResponse[OAuth2ResponseParameters.TOKEN_TYPE]) { throw this._log.createError('wireResponse is missing token_type'); } if (!wireResponse[OAuth2ResponseParameters.ACCESS_TOKEN]) { throw this._log.createError('wireResponse missing access_token'); } mapFields(wireResponse, tokenResponse, TOKEN_RESPONSE_MAP); if (wireResponse[OAuth2ResponseParameters.ID_TOKEN]) { var idToken = this._parseIdToken(wireResponse[OAuth2ResponseParameters.ID_TOKEN]); if (idToken) { _.extend(tokenResponse, idToken); } } return tokenResponse; }; /** * Validates the response returned from an OAuth 2.0 device code request. * @private * @param {string} body The response as a string encoded JSON object. * @return {object} The parsed response. */ OAuth2Client.prototype._validateDeviceCodeResponse = function(body) { var wireResponse; var deviceCodeResponse = {}; try { wireResponse = JSON.parse(body); } catch(e) { throw new Error('The device code response returned from the server is unparseable as JSON.'); } var intKeys = [ DeviceCodeResponseParameters.EXPIRES_IN, DeviceCodeResponseParameters.INTERVAL ]; this._parseOptionalInts(wireResponse, intKeys); if (!wireResponse[DeviceCodeResponseParameters.EXPIRES_IN]){ throw this._log.createError('wireResponse is missing expires_in'); } if (!wireResponse[DeviceCodeResponseParameters.DEVICE_CODE]) { throw this._log.createError('wireResponse is missing device code'); } if (!wireResponse[DeviceCodeResponseParameters.USER_CODE]) { throw this._log.createError('wireResponse is missing user code'); } mapFields(wireResponse, deviceCodeResponse, DEVICE_CODE_RESPONSE_MAP); return deviceCodeResponse; }; /** * @private * @param {string} body The body of a http token response. */ OAuth2Client.prototype._handlePollingResponse = function(body) { //handle token error response var tokenResponse = this._handlePollingRequestErrorResponse(body); if (_.isEmpty(tokenResponse)){ tokenResponse = this._validateTokenResponse(body); } return tokenResponse; }; /** * @private * @param {string} body The body of a http token response. */ OAuth2Client.prototype._handlePollingRequestErrorResponse = function(body) { var wireResponse; var tokenResponse = {}; try { wireResponse = JSON.parse(body); } catch (e) { throw new Error ('The token response returned from the server is unparsable as JSON'); } if (wireResponse[OAuth2ResponseParameters.ERROR]) { mapFields(wireResponse, tokenResponse, TOKEN_RESPONSE_MAP); } return tokenResponse; }; /** * @private * @param {object} response An http response object. * @param {string} body The body of a http token response. * @param {OAuth2Client.GetTokenCallback} callback A call back function. The body parameter is the body parameter passed * into this function. */ OAuth2Client.prototype._handleGetTokenResponse = function(response, body, callback) { var tokenResponse; try { tokenResponse = this._validateTokenResponse(body); } catch (e) { this._log.error('Error validating get token response', e, true); callback(e); return; } callback(null, tokenResponse); }; OAuth2Client.prototype._handleGetDeviceCodeResponse = function(response, body, callback) { var deviceCodeResponse; try { deviceCodeResponse = this._validateDeviceCodeResponse(body); } catch (e) { this._log.error('Error validating get user code response', e, true); callback(e); return; } callback(null, deviceCodeResponse); }; OAuth2Client.prototype._getTokenWithPolling = function (postOptions, callback) { var self = this; if (self._cancelPollingRequest === true) { callback(null, new Error('Polling_Request_Cancelled')); return; } request.post(postOptions, util.createRequestHandler('Get Token', this._log, function(response, body) { //error response callback, for error response, it's already parsed as Json. if (body && body.hasOwnProperty(TokenResponseFields.ERROR) && body[TokenResponseFields.ERROR] === 'authorization_pending') { callback(new Error(body[TokenResponseFields.ERROR]), body); } else { callback(null, body); } }, // success response callback function (response, body) { var tokenResponse; try { tokenResponse = self._handlePollingResponse(body); } catch (e) { self._log.error('Error validating get token response', e, true); callback(null, e); return; } callback(null, tokenResponse); }) ); }; OAuth2Client.prototype._createPostOption = function (postUrl, urlEncodedRequestForm) { var postOptions = util.createRequestOptions( this, { 'url' : url.format(postUrl), body : urlEncodedRequestForm, headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, followRedirect : false, encoding : 'utf8' } ); return postOptions; }; /** * @callback GetTokenCallback * @memberOf OAuth2Client * @param {Error} [error] In case of an error this will hold the associated Error object. * @param {TokenResponse} tokenResponse Contains the parsed result of a get token request. */ /** * @param {object} oauthParameters An object whose keys come from * Constants.OAuth2.Parameters * @param {OAuth2Client.GetTokenCallback} callback The callback function. */ OAuth2Client.prototype.getToken = function(oauthParameters, callback) { var self = this; var tokenUrl = self._createTokenUrl(); var urlEncodedTokenRequestForm = querystring.stringify(oauthParameters); var postOptions = self._createPostOption(tokenUrl, urlEncodedTokenRequestForm); request.post(postOptions, util.createRequestHandler('Get Token', this._log, callback, function (response, body) { self._handleGetTokenResponse(response, body, callback); }) ); }; /** * @param {object} oauthParameters An object whose keys come from * Constants.OAuth2.Parameters * @param {integer} refresh_interval The interval for polling request. * @param {integer} exipres_in The timeout for polling request. * @param {OAuth2Client.GetTokenCallback} callback The callback function. */ OAuth2Client.prototype.getTokenWithPolling = function(oauthParameters, refresh_interval, expires_in, callback){ var self = this; var maxTimesForRetry = Math.floor(expires_in / refresh_interval); var tokenUrl = self._createTokenUrl(); var urlEncodedTokenRequestForm = querystring.stringify(oauthParameters); var postOptions = self._createPostOption(tokenUrl, urlEncodedTokenRequestForm); var optionsForRetry = {times: maxTimesForRetry, interval: refresh_interval * 1000}; async.retry(optionsForRetry, function(retryCallback, response) { self._getTokenWithPolling(postOptions, retryCallback); }, function(err, response) { if (response && response instanceof Error) { callback(response); return; } else if (response && response.hasOwnProperty(DeviceCodeResponseParameters.ERROR)) { callback(response); return; } callback(err, response); }); }; OAuth2Client.prototype.getUserCodeInfo = function(oauthParameters, callback) { // for now make it as a post request var self = this; var deviceCodeUrl = self._createDeviceCodeUrl(); var urlEncodedDeviceCodeRequestForm = querystring.stringify(oauthParameters); var postOptions = self._createPostOption(deviceCodeUrl, urlEncodedDeviceCodeRequestForm); request.post(postOptions, util.createRequestHandler('Get Device Code ', this._log, callback, function (response, body) { self._handleGetDeviceCodeResponse(response, body, callback); }) ); }; /** * Cancel the polling request made for acquiring token by device code. */ OAuth2Client.prototype.cancelPollingRequest = function() { this._cancelPollingRequest = true; }; module.exports = OAuth2Client;
const electron = require('electron') // Module to control application life. const app = electron.app const Menu = electron.Menu // Module to create native browser window. const BrowserWindow = electron.BrowserWindow const path = require('path') const url = require('url') const ipc = require('electron').ipcMain // let autoUpdater = require('electron').autoUpdater // const appVersion = require('./package.json').version; // const os = require('os').platform(); // var updateFeed = 'https://prophecyupdateserver.herokuapp.com/updates/latest'; // if (process.env.NODE_ENV !== 'development') { // updateFeed = os === 'darwin' ? // 'https://prophecyupdateserver.herokuapp.com/updates/latest' : // 'http://download.mysite.com/releases/win32'; // } // console.log(autoUpdater.setFeedURL); // autoUpdater.setFeedURL('https://prophecyupdateserver.herokuapp.com/updates/latest?v=' + appVersion); // autoUpdater.setFeedURL('http://localhost:5000/updates/latest?v=' + appVersion); // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is garbage collected. let mainWindow function createWindow () { // Create the browser window. // mainWindow = new BrowserWindow({width: 1200, height: 1000, titleBarStyle: 'hidden'}) mainWindow = new BrowserWindow({ width: 1000, height: 600, // title: "Prophecy of the Fallen", backgroundColor: '#000000', titleBarStyle: 'hidden' }) global.contents = mainWindow.webContents mainWindow.setFullScreen(true) // mainWindow.maximize(); const menu = Menu.buildFromTemplate(template) Menu.setApplicationMenu(menu) // and load the index.html of the app. mainWindow.loadURL(url.format({ pathname: path.join(__dirname, 'index.html'), protocol: 'file:', slashes: true })) // Open the DevTools. // mainWindow.webContents.openDevTools() // Emitted when the window is closed. mainWindow.on('closed', function () { // Dereference the window object, usually you would store windows // in an array if your app supports multi windows, this is the time // when you should delete the corresponding element. mainWindow = null }) } app.on('ready', createWindow) app.on('window-all-closed', function () { // On OS X it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() } }) app.on('activate', function () { // On OS X it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (mainWindow === null) { createWindow() } }) // app.on('browser-window-created', function () { // let reopenMenuItem = findReopenMenuItem() // if (reopenMenuItem) reopenMenuItem.enabled = false // }) // app.on('window-all-closed', function () { // let reopenMenuItem = findReopenMenuItem() // if (reopenMenuItem) reopenMenuItem.enabled = true // }) // ipc.on('asynchronous-message', function (event, arg) { // // event.sender.send('asynchronous-reply', 'pong') // console.log('GOT IT') // }) let template = [{ label: 'Edit', submenu: [{ label: 'Undo', accelerator: 'CmdOrCtrl+Z', role: 'undo' }, { label: 'Redo', accelerator: 'Shift+CmdOrCtrl+Z', role: 'redo' }, { type: 'separator' }, { label: 'Cut', accelerator: 'CmdOrCtrl+X', role: 'cut' }, { label: 'Copy', accelerator: 'CmdOrCtrl+C', role: 'copy' }, { label: 'Paste', accelerator: 'CmdOrCtrl+V', role: 'paste' }, { label: 'Select All', accelerator: 'CmdOrCtrl+A', role: 'selectall' }] }, { label: 'View', submenu: [{ label: 'Reload', accelerator: 'CmdOrCtrl+R', click: function (item, focusedWindow) { if (focusedWindow) { // on reload, start fresh and close any old // open secondary windows if (focusedWindow.id === 1) { BrowserWindow.getAllWindows().forEach(function (win) { if (win.id > 1) { win.close() } }) } focusedWindow.reload() } } }, { label: 'Toggle Full Screen', accelerator: (function () { if (process.platform === 'darwin') { return 'Ctrl+Command+F' } else { return 'F11' } })(), click: function (item, focusedWindow) { if (focusedWindow) { focusedWindow.setFullScreen(!focusedWindow.isFullScreen()) } } }, { label: 'Toggle Developer Tools', accelerator: (function () { if (process.platform === 'darwin') { return 'Alt+Command+I' } else { return 'Ctrl+Shift+I' } })(), click: function (item, focusedWindow) { if (focusedWindow) { focusedWindow.toggleDevTools() } } }, { type: 'separator' }, { label: 'App Menu Demo', click: function (item, focusedWindow) { if (focusedWindow) { const options = { type: 'info', title: 'Application Menu Demo', buttons: ['Ok'], message: 'This demo is for the Menu section, showing how to create a clickable menu item in the application menu.' } electron.dialog.showMessageBox(focusedWindow, options, function () {}) } } }] }, { label: 'Audio', role: 'Audio', submenu: [{ label: 'Mute Audio', accelerator: 'CmdOrCtrl+Shift+M', enabled: true, key: 'muteAudio', click: () => { (mainWindow.webContents.isAudioMuted()) ? mainWindow.webContents.setAudioMuted(false) : mainWindow.webContents.setAudioMuted(true) } }] } , { label: 'Window', role: 'window', submenu: [{ label: 'Minimize', accelerator: 'CmdOrCtrl+M', role: 'minimize' }, { label: 'Close', accelerator: 'CmdOrCtrl+W', role: 'close' }, { type: 'separator' }, { label: 'Reopen Window', accelerator: 'CmdOrCtrl+Shift+T', enabled: false, key: 'reopenMenuItem', click: function () { app.emit('activate') } }] }, { label: 'About Us', submenu: [{ label: 'Audio', submenu: [{ label: 'Roland Köstler', click: function () { electron.shell.openExternal('https://www.instagram.com/roland_koestler/') } } ] }, { type: 'separator' }, { label: 'Development', submenu: [{ label: 'Michael Dorn', click: function () { electron.shell.openExternal('http://michaeldorn.at') } } ] }, { type: 'separator' }, { label: 'Game Art', submenu: [{ label: 'Isabella Griessenberger', click: function () { electron.shell.openExternal('http://michaeldorn.at') } }, { label: 'Kang Wang', click: function () { electron.shell.openExternal('https://www.artstation.com/desaturateful') } }, { label: 'Lia Lembacher', click: function () { electron.shell.openExternal('http://michaeldorn.at') } }, { label: 'Nina Leinwatter', click: function () { electron.shell.openExternal('http://michaeldorn.at') } }, { label: 'Sabine Rimmer', click: function () { electron.shell.openExternal('http://michaeldorn.at') } } ] }, { type: 'separator' }, { label: 'Project Management', submenu: [{ label: 'Manuela Abdalla', click: function () { electron.shell.openExternal('https://www.instagram.com/livevie_/') } } ] }, { type: 'separator' }, { label: 'Video', submenu: [{ label: 'Jan Rogner', click: function () { electron.shell.openExternal('http://michaeldorn.at') } } ] } ] }, { label: 'Help', role: 'help', submenu: [{ label: 'FAQ', click: function () { electron.shell.openExternal('http://michaeldorn.at') } }] } ] function addUpdateMenuItems (items, position) { if (process.mas) return const version = electron.app.getVersion() let updateItems = [{ label: `Version ${version}`, enabled: false }, { label: 'Checking for Update', enabled: false, key: 'checkingForUpdate' }, { label: 'Check for Update', visible: true, key: 'checkForUpdate', click: function () { require('electron').autoUpdater.checkForUpdates() } }, { label: 'Restart and Install Update', enabled: true, visible: false, key: 'restartToUpdate', click: function () { require('electron').autoUpdater.quitAndInstall() } }] items.splice.apply(items, [position, 0].concat(updateItems)) } function findReopenMenuItem () { const menu = Menu.getApplicationMenu() if (!menu) return let reopenMenuItem menu.items.forEach(function (item) { if (item.submenu) { item.submenu.items.forEach(function (item) { if (item.key === 'reopenMenuItem') { reopenMenuItem = item } }) } }) return reopenMenuItem } if (process.platform === 'darwin') { const name = electron.app.getName() template.unshift({ label: name, submenu: [{ label: `About ${name}`, role: 'about' }, { type: 'separator' }, { label: 'Services', role: 'services', submenu: [] }, { type: 'separator' }, { label: `Hide ${name}`, accelerator: 'Command+H', role: 'hide' }, { label: 'Hide Others', accelerator: 'Command+Alt+H', role: 'hideothers' }, { label: 'Show All', role: 'unhide' }, { type: 'separator' }, { label: 'Quit', accelerator: 'Command+Q', click: function () { app.quit() } }] }) // Window menu. template[2].submenu.push({ type: 'separator' }, { label: 'Bring All to Front', role: 'front' }) addUpdateMenuItems(template[0].submenu, 1) } if (process.platform === 'win32') { const helpMenu = template[template.length - 1].submenu addUpdateMenuItems(helpMenu, 0) }
/*! jQuery v1.10.2 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license*/ (function (e, t) { var n, r, i = typeof t, o = e.location, a = e.document, s = a.documentElement, l = e.jQuery, u = e.$, c = {}, p = [], f = "1.10.2", d = p.concat, h = p.push, g = p.slice, m = p.indexOf, y = c.toString, v = c.hasOwnProperty, b = f.trim, x = function (e, t) { return new x.fn.init(e, t, r) }, w = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, T = /\S+/g, C = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, N = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, k = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, E = /^[\],:{}\s]*$/, S = /(?:^|:|,)(?:\s*\[)+/g, A = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, j = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g, D = /^-ms-/, L = /-([\da-z])/gi, H = function (e, t) { return t.toUpperCase() }, q = function (e) { (a.addEventListener || "load" === e.type || "complete" === a.readyState) && (_(), x.ready()) }, _ = function () { a.addEventListener ? (a.removeEventListener("DOMContentLoaded", q, !1), e.removeEventListener("load", q, !1)) : (a.detachEvent("onreadystatechange", q), e.detachEvent("onload", q)) }; x.fn = x.prototype = {jquery: f, constructor: x, init: function (e, n, r) { var i, o; if (!e)return this; if ("string" == typeof e) { if (i = "<" === e.charAt(0) && ">" === e.charAt(e.length - 1) && e.length >= 3 ? [null, e, null] : N.exec(e), !i || !i[1] && n)return!n || n.jquery ? (n || r).find(e) : this.constructor(n).find(e); if (i[1]) { if (n = n instanceof x ? n[0] : n, x.merge(this, x.parseHTML(i[1], n && n.nodeType ? n.ownerDocument || n : a, !0)), k.test(i[1]) && x.isPlainObject(n))for (i in n)x.isFunction(this[i]) ? this[i](n[i]) : this.attr(i, n[i]); return this } if (o = a.getElementById(i[2]), o && o.parentNode) { if (o.id !== i[2])return r.find(e); this.length = 1, this[0] = o } return this.context = a, this.selector = e, this } return e.nodeType ? (this.context = this[0] = e, this.length = 1, this) : x.isFunction(e) ? r.ready(e) : (e.selector !== t && (this.selector = e.selector, this.context = e.context), x.makeArray(e, this)) }, selector: "", length: 0, toArray: function () { return g.call(this) }, get: function (e) { return null == e ? this.toArray() : 0 > e ? this[this.length + e] : this[e] }, pushStack: function (e) { var t = x.merge(this.constructor(), e); return t.prevObject = this, t.context = this.context, t }, each: function (e, t) { return x.each(this, e, t) }, ready: function (e) { return x.ready.promise().done(e), this }, slice: function () { return this.pushStack(g.apply(this, arguments)) }, first: function () { return this.eq(0) }, last: function () { return this.eq(-1) }, eq: function (e) { var t = this.length, n = +e + (0 > e ? t : 0); return this.pushStack(n >= 0 && t > n ? [this[n]] : []) }, map: function (e) { return this.pushStack(x.map(this, function (t, n) { return e.call(t, n, t) })) }, end: function () { return this.prevObject || this.constructor(null) }, push: h, sort: [].sort, splice: [].splice}, x.fn.init.prototype = x.fn, x.extend = x.fn.extend = function () { var e, n, r, i, o, a, s = arguments[0] || {}, l = 1, u = arguments.length, c = !1; for ("boolean" == typeof s && (c = s, s = arguments[1] || {}, l = 2), "object" == typeof s || x.isFunction(s) || (s = {}), u === l && (s = this, --l); u > l; l++)if (null != (o = arguments[l]))for (i in o)e = s[i], r = o[i], s !== r && (c && r && (x.isPlainObject(r) || (n = x.isArray(r))) ? (n ? (n = !1, a = e && x.isArray(e) ? e : []) : a = e && x.isPlainObject(e) ? e : {}, s[i] = x.extend(c, a, r)) : r !== t && (s[i] = r)); return s }, x.extend({expando: "jQuery" + (f + Math.random()).replace(/\D/g, ""), noConflict: function (t) { return e.$ === x && (e.$ = u), t && e.jQuery === x && (e.jQuery = l), x }, isReady: !1, readyWait: 1, holdReady: function (e) { e ? x.readyWait++ : x.ready(!0) }, ready: function (e) { if (e === !0 ? !--x.readyWait : !x.isReady) { if (!a.body)return setTimeout(x.ready); x.isReady = !0, e !== !0 && --x.readyWait > 0 || (n.resolveWith(a, [x]), x.fn.trigger && x(a).trigger("ready").off("ready")) } }, isFunction: function (e) { return"function" === x.type(e) }, isArray: Array.isArray || function (e) { return"array" === x.type(e) }, isWindow: function (e) { return null != e && e == e.window }, isNumeric: function (e) { return!isNaN(parseFloat(e)) && isFinite(e) }, type: function (e) { return null == e ? e + "" : "object" == typeof e || "function" == typeof e ? c[y.call(e)] || "object" : typeof e }, isPlainObject: function (e) { var n; if (!e || "object" !== x.type(e) || e.nodeType || x.isWindow(e))return!1; try { if (e.constructor && !v.call(e, "constructor") && !v.call(e.constructor.prototype, "isPrototypeOf"))return!1 } catch (r) { return!1 } if (x.support.ownLast)for (n in e)return v.call(e, n); for (n in e); return n === t || v.call(e, n) }, isEmptyObject: function (e) { var t; for (t in e)return!1; return!0 }, error: function (e) { throw Error(e) }, parseHTML: function (e, t, n) { if (!e || "string" != typeof e)return null; "boolean" == typeof t && (n = t, t = !1), t = t || a; var r = k.exec(e), i = !n && []; return r ? [t.createElement(r[1])] : (r = x.buildFragment([e], t, i), i && x(i).remove(), x.merge([], r.childNodes)) }, parseJSON: function (n) { return e.JSON && e.JSON.parse ? e.JSON.parse(n) : null === n ? n : "string" == typeof n && (n = x.trim(n), n && E.test(n.replace(A, "@").replace(j, "]").replace(S, ""))) ? Function("return " + n)() : (x.error("Invalid JSON: " + n), t) }, parseXML: function (n) { var r, i; if (!n || "string" != typeof n)return null; try { e.DOMParser ? (i = new DOMParser, r = i.parseFromString(n, "text/xml")) : (r = new ActiveXObject("Microsoft.XMLDOM"), r.async = "false", r.loadXML(n)) } catch (o) { r = t } return r && r.documentElement && !r.getElementsByTagName("parsererror").length || x.error("Invalid XML: " + n), r }, noop: function () { }, globalEval: function (t) { t && x.trim(t) && (e.execScript || function (t) { e.eval.call(e, t) })(t) }, camelCase: function (e) { return e.replace(D, "ms-").replace(L, H) }, nodeName: function (e, t) { return e.nodeName && e.nodeName.toLowerCase() === t.toLowerCase() }, each: function (e, t, n) { var r, i = 0, o = e.length, a = M(e); if (n) { if (a) { for (; o > i; i++)if (r = t.apply(e[i], n), r === !1)break } else for (i in e)if (r = t.apply(e[i], n), r === !1)break } else if (a) { for (; o > i; i++)if (r = t.call(e[i], i, e[i]), r === !1)break } else for (i in e)if (r = t.call(e[i], i, e[i]), r === !1)break; return e }, trim: b && !b.call("\ufeff\u00a0") ? function (e) { return null == e ? "" : b.call(e) } : function (e) { return null == e ? "" : (e + "").replace(C, "") }, makeArray: function (e, t) { var n = t || []; return null != e && (M(Object(e)) ? x.merge(n, "string" == typeof e ? [e] : e) : h.call(n, e)), n }, inArray: function (e, t, n) { var r; if (t) { if (m)return m.call(t, e, n); for (r = t.length, n = n ? 0 > n ? Math.max(0, r + n) : n : 0; r > n; n++)if (n in t && t[n] === e)return n } return-1 }, merge: function (e, n) { var r = n.length, i = e.length, o = 0; if ("number" == typeof r)for (; r > o; o++)e[i++] = n[o]; else while (n[o] !== t)e[i++] = n[o++]; return e.length = i, e }, grep: function (e, t, n) { var r, i = [], o = 0, a = e.length; for (n = !!n; a > o; o++)r = !!t(e[o], o), n !== r && i.push(e[o]); return i }, map: function (e, t, n) { var r, i = 0, o = e.length, a = M(e), s = []; if (a)for (; o > i; i++)r = t(e[i], i, n), null != r && (s[s.length] = r); else for (i in e)r = t(e[i], i, n), null != r && (s[s.length] = r); return d.apply([], s) }, guid: 1, proxy: function (e, n) { var r, i, o; return"string" == typeof n && (o = e[n], n = e, e = o), x.isFunction(e) ? (r = g.call(arguments, 2), i = function () { return e.apply(n || this, r.concat(g.call(arguments))) }, i.guid = e.guid = e.guid || x.guid++, i) : t }, access: function (e, n, r, i, o, a, s) { var l = 0, u = e.length, c = null == r; if ("object" === x.type(r)) { o = !0; for (l in r)x.access(e, n, l, r[l], !0, a, s) } else if (i !== t && (o = !0, x.isFunction(i) || (s = !0), c && (s ? (n.call(e, i), n = null) : (c = n, n = function (e, t, n) { return c.call(x(e), n) })), n))for (; u > l; l++)n(e[l], r, s ? i : i.call(e[l], l, n(e[l], r))); return o ? e : c ? n.call(e) : u ? n(e[0], r) : a }, now: function () { return(new Date).getTime() }, swap: function (e, t, n, r) { var i, o, a = {}; for (o in t)a[o] = e.style[o], e.style[o] = t[o]; i = n.apply(e, r || []); for (o in t)e.style[o] = a[o]; return i }}), x.ready.promise = function (t) { if (!n)if (n = x.Deferred(), "complete" === a.readyState)setTimeout(x.ready); else if (a.addEventListener)a.addEventListener("DOMContentLoaded", q, !1), e.addEventListener("load", q, !1); else { a.attachEvent("onreadystatechange", q), e.attachEvent("onload", q); var r = !1; try { r = null == e.frameElement && a.documentElement } catch (i) { } r && r.doScroll && function o() { if (!x.isReady) { try { r.doScroll("left") } catch (e) { return setTimeout(o, 50) } _(), x.ready() } }() } return n.promise(t) }, x.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function (e, t) { c["[object " + t + "]"] = t.toLowerCase() }); function M(e) { var t = e.length, n = x.type(e); return x.isWindow(e) ? !1 : 1 === e.nodeType && t ? !0 : "array" === n || "function" !== n && (0 === t || "number" == typeof t && t > 0 && t - 1 in e) } r = x(a), function (e, t) { var n, r, i, o, a, s, l, u, c, p, f, d, h, g, m, y, v, b = "sizzle" + -new Date, w = e.document, T = 0, C = 0, N = st(), k = st(), E = st(), S = !1, A = function (e, t) { return e === t ? (S = !0, 0) : 0 }, j = typeof t, D = 1 << 31, L = {}.hasOwnProperty, H = [], q = H.pop, _ = H.push, M = H.push, O = H.slice, F = H.indexOf || function (e) { var t = 0, n = this.length; for (; n > t; t++)if (this[t] === e)return t; return-1 }, B = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", P = "[\\x20\\t\\r\\n\\f]", R = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", W = R.replace("w", "w#"), $ = "\\[" + P + "*(" + R + ")" + P + "*(?:([*^$|!~]?=)" + P + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + W + ")|)|)" + P + "*\\]", I = ":(" + R + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + $.replace(3, 8) + ")*)|.*)\\)|)", z = RegExp("^" + P + "+|((?:^|[^\\\\])(?:\\\\.)*)" + P + "+$", "g"), X = RegExp("^" + P + "*," + P + "*"), U = RegExp("^" + P + "*([>+~]|" + P + ")" + P + "*"), V = RegExp(P + "*[+~]"), Y = RegExp("=" + P + "*([^\\]'\"]*)" + P + "*\\]", "g"), J = RegExp(I), G = RegExp("^" + W + "$"), Q = {ID: RegExp("^#(" + R + ")"), CLASS: RegExp("^\\.(" + R + ")"), TAG: RegExp("^(" + R.replace("w", "w*") + ")"), ATTR: RegExp("^" + $), PSEUDO: RegExp("^" + I), CHILD: RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + P + "*(even|odd|(([+-]|)(\\d*)n|)" + P + "*(?:([+-]|)" + P + "*(\\d+)|))" + P + "*\\)|)", "i"), bool: RegExp("^(?:" + B + ")$", "i"), needsContext: RegExp("^" + P + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + P + "*((?:-\\d)?\\d*)" + P + "*\\)|)(?=[^-]|$)", "i")}, K = /^[^{]+\{\s*\[native \w/, Z = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, et = /^(?:input|select|textarea|button)$/i, tt = /^h\d$/i, nt = /'|\\/g, rt = RegExp("\\\\([\\da-f]{1,6}" + P + "?|(" + P + ")|.)", "ig"), it = function (e, t, n) { var r = "0x" + t - 65536; return r !== r || n ? t : 0 > r ? String.fromCharCode(r + 65536) : String.fromCharCode(55296 | r >> 10, 56320 | 1023 & r) }; try { M.apply(H = O.call(w.childNodes), w.childNodes), H[w.childNodes.length].nodeType } catch (ot) { M = {apply: H.length ? function (e, t) { _.apply(e, O.call(t)) } : function (e, t) { var n = e.length, r = 0; while (e[n++] = t[r++]); e.length = n - 1 }} } function at(e, t, n, i) { var o, a, s, l, u, c, d, m, y, x; if ((t ? t.ownerDocument || t : w) !== f && p(t), t = t || f, n = n || [], !e || "string" != typeof e)return n; if (1 !== (l = t.nodeType) && 9 !== l)return[]; if (h && !i) { if (o = Z.exec(e))if (s = o[1]) { if (9 === l) { if (a = t.getElementById(s), !a || !a.parentNode)return n; if (a.id === s)return n.push(a), n } else if (t.ownerDocument && (a = t.ownerDocument.getElementById(s)) && v(t, a) && a.id === s)return n.push(a), n } else { if (o[2])return M.apply(n, t.getElementsByTagName(e)), n; if ((s = o[3]) && r.getElementsByClassName && t.getElementsByClassName)return M.apply(n, t.getElementsByClassName(s)), n } if (r.qsa && (!g || !g.test(e))) { if (m = d = b, y = t, x = 9 === l && e, 1 === l && "object" !== t.nodeName.toLowerCase()) { c = mt(e), (d = t.getAttribute("id")) ? m = d.replace(nt, "\\$&") : t.setAttribute("id", m), m = "[id='" + m + "'] ", u = c.length; while (u--)c[u] = m + yt(c[u]); y = V.test(e) && t.parentNode || t, x = c.join(",") } if (x)try { return M.apply(n, y.querySelectorAll(x)), n } catch (T) { } finally { d || t.removeAttribute("id") } } } return kt(e.replace(z, "$1"), t, n, i) } function st() { var e = []; function t(n, r) { return e.push(n += " ") > o.cacheLength && delete t[e.shift()], t[n] = r } return t } function lt(e) { return e[b] = !0, e } function ut(e) { var t = f.createElement("div"); try { return!!e(t) } catch (n) { return!1 } finally { t.parentNode && t.parentNode.removeChild(t), t = null } } function ct(e, t) { var n = e.split("|"), r = e.length; while (r--)o.attrHandle[n[r]] = t } function pt(e, t) { var n = t && e, r = n && 1 === e.nodeType && 1 === t.nodeType && (~t.sourceIndex || D) - (~e.sourceIndex || D); if (r)return r; if (n)while (n = n.nextSibling)if (n === t)return-1; return e ? 1 : -1 } function ft(e) { return function (t) { var n = t.nodeName.toLowerCase(); return"input" === n && t.type === e } } function dt(e) { return function (t) { var n = t.nodeName.toLowerCase(); return("input" === n || "button" === n) && t.type === e } } function ht(e) { return lt(function (t) { return t = +t, lt(function (n, r) { var i, o = e([], n.length, t), a = o.length; while (a--)n[i = o[a]] && (n[i] = !(r[i] = n[i])) }) }) } s = at.isXML = function (e) { var t = e && (e.ownerDocument || e).documentElement; return t ? "HTML" !== t.nodeName : !1 }, r = at.support = {}, p = at.setDocument = function (e) { var n = e ? e.ownerDocument || e : w, i = n.defaultView; return n !== f && 9 === n.nodeType && n.documentElement ? (f = n, d = n.documentElement, h = !s(n), i && i.attachEvent && i !== i.top && i.attachEvent("onbeforeunload", function () { p() }), r.attributes = ut(function (e) { return e.className = "i", !e.getAttribute("className") }), r.getElementsByTagName = ut(function (e) { return e.appendChild(n.createComment("")), !e.getElementsByTagName("*").length }), r.getElementsByClassName = ut(function (e) { return e.innerHTML = "<div class='a'></div><div class='a i'></div>", e.firstChild.className = "i", 2 === e.getElementsByClassName("i").length }), r.getById = ut(function (e) { return d.appendChild(e).id = b, !n.getElementsByName || !n.getElementsByName(b).length }), r.getById ? (o.find.ID = function (e, t) { if (typeof t.getElementById !== j && h) { var n = t.getElementById(e); return n && n.parentNode ? [n] : [] } }, o.filter.ID = function (e) { var t = e.replace(rt, it); return function (e) { return e.getAttribute("id") === t } }) : (delete o.find.ID, o.filter.ID = function (e) { var t = e.replace(rt, it); return function (e) { var n = typeof e.getAttributeNode !== j && e.getAttributeNode("id"); return n && n.value === t } }), o.find.TAG = r.getElementsByTagName ? function (e, n) { return typeof n.getElementsByTagName !== j ? n.getElementsByTagName(e) : t } : function (e, t) { var n, r = [], i = 0, o = t.getElementsByTagName(e); if ("*" === e) { while (n = o[i++])1 === n.nodeType && r.push(n); return r } return o }, o.find.CLASS = r.getElementsByClassName && function (e, n) { return typeof n.getElementsByClassName !== j && h ? n.getElementsByClassName(e) : t }, m = [], g = [], (r.qsa = K.test(n.querySelectorAll)) && (ut(function (e) { e.innerHTML = "<select><option selected=''></option></select>", e.querySelectorAll("[selected]").length || g.push("\\[" + P + "*(?:value|" + B + ")"), e.querySelectorAll(":checked").length || g.push(":checked") }), ut(function (e) { var t = n.createElement("input"); t.setAttribute("type", "hidden"), e.appendChild(t).setAttribute("t", ""), e.querySelectorAll("[t^='']").length && g.push("[*^$]=" + P + "*(?:''|\"\")"), e.querySelectorAll(":enabled").length || g.push(":enabled", ":disabled"), e.querySelectorAll("*,:x"), g.push(",.*:") })), (r.matchesSelector = K.test(y = d.webkitMatchesSelector || d.mozMatchesSelector || d.oMatchesSelector || d.msMatchesSelector)) && ut(function (e) { r.disconnectedMatch = y.call(e, "div"), y.call(e, "[s!='']:x"), m.push("!=", I) }), g = g.length && RegExp(g.join("|")), m = m.length && RegExp(m.join("|")), v = K.test(d.contains) || d.compareDocumentPosition ? function (e, t) { var n = 9 === e.nodeType ? e.documentElement : e, r = t && t.parentNode; return e === r || !(!r || 1 !== r.nodeType || !(n.contains ? n.contains(r) : e.compareDocumentPosition && 16 & e.compareDocumentPosition(r))) } : function (e, t) { if (t)while (t = t.parentNode)if (t === e)return!0; return!1 }, A = d.compareDocumentPosition ? function (e, t) { if (e === t)return S = !0, 0; var i = t.compareDocumentPosition && e.compareDocumentPosition && e.compareDocumentPosition(t); return i ? 1 & i || !r.sortDetached && t.compareDocumentPosition(e) === i ? e === n || v(w, e) ? -1 : t === n || v(w, t) ? 1 : c ? F.call(c, e) - F.call(c, t) : 0 : 4 & i ? -1 : 1 : e.compareDocumentPosition ? -1 : 1 } : function (e, t) { var r, i = 0, o = e.parentNode, a = t.parentNode, s = [e], l = [t]; if (e === t)return S = !0, 0; if (!o || !a)return e === n ? -1 : t === n ? 1 : o ? -1 : a ? 1 : c ? F.call(c, e) - F.call(c, t) : 0; if (o === a)return pt(e, t); r = e; while (r = r.parentNode)s.unshift(r); r = t; while (r = r.parentNode)l.unshift(r); while (s[i] === l[i])i++; return i ? pt(s[i], l[i]) : s[i] === w ? -1 : l[i] === w ? 1 : 0 }, n) : f }, at.matches = function (e, t) { return at(e, null, null, t) }, at.matchesSelector = function (e, t) { if ((e.ownerDocument || e) !== f && p(e), t = t.replace(Y, "='$1']"), !(!r.matchesSelector || !h || m && m.test(t) || g && g.test(t)))try { var n = y.call(e, t); if (n || r.disconnectedMatch || e.document && 11 !== e.document.nodeType)return n } catch (i) { } return at(t, f, null, [e]).length > 0 }, at.contains = function (e, t) { return(e.ownerDocument || e) !== f && p(e), v(e, t) }, at.attr = function (e, n) { (e.ownerDocument || e) !== f && p(e); var i = o.attrHandle[n.toLowerCase()], a = i && L.call(o.attrHandle, n.toLowerCase()) ? i(e, n, !h) : t; return a === t ? r.attributes || !h ? e.getAttribute(n) : (a = e.getAttributeNode(n)) && a.specified ? a.value : null : a }, at.error = function (e) { throw Error("Syntax error, unrecognized expression: " + e) }, at.uniqueSort = function (e) { var t, n = [], i = 0, o = 0; if (S = !r.detectDuplicates, c = !r.sortStable && e.slice(0), e.sort(A), S) { while (t = e[o++])t === e[o] && (i = n.push(o)); while (i--)e.splice(n[i], 1) } return e }, a = at.getText = function (e) { var t, n = "", r = 0, i = e.nodeType; if (i) { if (1 === i || 9 === i || 11 === i) { if ("string" == typeof e.textContent)return e.textContent; for (e = e.firstChild; e; e = e.nextSibling)n += a(e) } else if (3 === i || 4 === i)return e.nodeValue } else for (; t = e[r]; r++)n += a(t); return n }, o = at.selectors = {cacheLength: 50, createPseudo: lt, match: Q, attrHandle: {}, find: {}, relative: {">": {dir: "parentNode", first: !0}, " ": {dir: "parentNode"}, "+": {dir: "previousSibling", first: !0}, "~": {dir: "previousSibling"}}, preFilter: {ATTR: function (e) { return e[1] = e[1].replace(rt, it), e[3] = (e[4] || e[5] || "").replace(rt, it), "~=" === e[2] && (e[3] = " " + e[3] + " "), e.slice(0, 4) }, CHILD: function (e) { return e[1] = e[1].toLowerCase(), "nth" === e[1].slice(0, 3) ? (e[3] || at.error(e[0]), e[4] = +(e[4] ? e[5] + (e[6] || 1) : 2 * ("even" === e[3] || "odd" === e[3])), e[5] = +(e[7] + e[8] || "odd" === e[3])) : e[3] && at.error(e[0]), e }, PSEUDO: function (e) { var n, r = !e[5] && e[2]; return Q.CHILD.test(e[0]) ? null : (e[3] && e[4] !== t ? e[2] = e[4] : r && J.test(r) && (n = mt(r, !0)) && (n = r.indexOf(")", r.length - n) - r.length) && (e[0] = e[0].slice(0, n), e[2] = r.slice(0, n)), e.slice(0, 3)) }}, filter: {TAG: function (e) { var t = e.replace(rt, it).toLowerCase(); return"*" === e ? function () { return!0 } : function (e) { return e.nodeName && e.nodeName.toLowerCase() === t } }, CLASS: function (e) { var t = N[e + " "]; return t || (t = RegExp("(^|" + P + ")" + e + "(" + P + "|$)")) && N(e, function (e) { return t.test("string" == typeof e.className && e.className || typeof e.getAttribute !== j && e.getAttribute("class") || "") }) }, ATTR: function (e, t, n) { return function (r) { var i = at.attr(r, e); return null == i ? "!=" === t : t ? (i += "", "=" === t ? i === n : "!=" === t ? i !== n : "^=" === t ? n && 0 === i.indexOf(n) : "*=" === t ? n && i.indexOf(n) > -1 : "$=" === t ? n && i.slice(-n.length) === n : "~=" === t ? (" " + i + " ").indexOf(n) > -1 : "|=" === t ? i === n || i.slice(0, n.length + 1) === n + "-" : !1) : !0 } }, CHILD: function (e, t, n, r, i) { var o = "nth" !== e.slice(0, 3), a = "last" !== e.slice(-4), s = "of-type" === t; return 1 === r && 0 === i ? function (e) { return!!e.parentNode } : function (t, n, l) { var u, c, p, f, d, h, g = o !== a ? "nextSibling" : "previousSibling", m = t.parentNode, y = s && t.nodeName.toLowerCase(), v = !l && !s; if (m) { if (o) { while (g) { p = t; while (p = p[g])if (s ? p.nodeName.toLowerCase() === y : 1 === p.nodeType)return!1; h = g = "only" === e && !h && "nextSibling" } return!0 } if (h = [a ? m.firstChild : m.lastChild], a && v) { c = m[b] || (m[b] = {}), u = c[e] || [], d = u[0] === T && u[1], f = u[0] === T && u[2], p = d && m.childNodes[d]; while (p = ++d && p && p[g] || (f = d = 0) || h.pop())if (1 === p.nodeType && ++f && p === t) { c[e] = [T, d, f]; break } } else if (v && (u = (t[b] || (t[b] = {}))[e]) && u[0] === T)f = u[1]; else while (p = ++d && p && p[g] || (f = d = 0) || h.pop())if ((s ? p.nodeName.toLowerCase() === y : 1 === p.nodeType) && ++f && (v && ((p[b] || (p[b] = {}))[e] = [T, f]), p === t))break; return f -= i, f === r || 0 === f % r && f / r >= 0 } } }, PSEUDO: function (e, t) { var n, r = o.pseudos[e] || o.setFilters[e.toLowerCase()] || at.error("unsupported pseudo: " + e); return r[b] ? r(t) : r.length > 1 ? (n = [e, e, "", t], o.setFilters.hasOwnProperty(e.toLowerCase()) ? lt(function (e, n) { var i, o = r(e, t), a = o.length; while (a--)i = F.call(e, o[a]), e[i] = !(n[i] = o[a]) }) : function (e) { return r(e, 0, n) }) : r }}, pseudos: {not: lt(function (e) { var t = [], n = [], r = l(e.replace(z, "$1")); return r[b] ? lt(function (e, t, n, i) { var o, a = r(e, null, i, []), s = e.length; while (s--)(o = a[s]) && (e[s] = !(t[s] = o)) }) : function (e, i, o) { return t[0] = e, r(t, null, o, n), !n.pop() } }), has: lt(function (e) { return function (t) { return at(e, t).length > 0 } }), contains: lt(function (e) { return function (t) { return(t.textContent || t.innerText || a(t)).indexOf(e) > -1 } }), lang: lt(function (e) { return G.test(e || "") || at.error("unsupported lang: " + e), e = e.replace(rt, it).toLowerCase(), function (t) { var n; do if (n = h ? t.lang : t.getAttribute("xml:lang") || t.getAttribute("lang"))return n = n.toLowerCase(), n === e || 0 === n.indexOf(e + "-"); while ((t = t.parentNode) && 1 === t.nodeType); return!1 } }), target: function (t) { var n = e.location && e.location.hash; return n && n.slice(1) === t.id }, root: function (e) { return e === d }, focus: function (e) { return e === f.activeElement && (!f.hasFocus || f.hasFocus()) && !!(e.type || e.href || ~e.tabIndex) }, enabled: function (e) { return e.disabled === !1 }, disabled: function (e) { return e.disabled === !0 }, checked: function (e) { var t = e.nodeName.toLowerCase(); return"input" === t && !!e.checked || "option" === t && !!e.selected }, selected: function (e) { return e.parentNode && e.parentNode.selectedIndex, e.selected === !0 }, empty: function (e) { for (e = e.firstChild; e; e = e.nextSibling)if (e.nodeName > "@" || 3 === e.nodeType || 4 === e.nodeType)return!1; return!0 }, parent: function (e) { return!o.pseudos.empty(e) }, header: function (e) { return tt.test(e.nodeName) }, input: function (e) { return et.test(e.nodeName) }, button: function (e) { var t = e.nodeName.toLowerCase(); return"input" === t && "button" === e.type || "button" === t }, text: function (e) { var t; return"input" === e.nodeName.toLowerCase() && "text" === e.type && (null == (t = e.getAttribute("type")) || t.toLowerCase() === e.type) }, first: ht(function () { return[0] }), last: ht(function (e, t) { return[t - 1] }), eq: ht(function (e, t, n) { return[0 > n ? n + t : n] }), even: ht(function (e, t) { var n = 0; for (; t > n; n += 2)e.push(n); return e }), odd: ht(function (e, t) { var n = 1; for (; t > n; n += 2)e.push(n); return e }), lt: ht(function (e, t, n) { var r = 0 > n ? n + t : n; for (; --r >= 0;)e.push(r); return e }), gt: ht(function (e, t, n) { var r = 0 > n ? n + t : n; for (; t > ++r;)e.push(r); return e })}}, o.pseudos.nth = o.pseudos.eq; for (n in{radio: !0, checkbox: !0, file: !0, password: !0, image: !0})o.pseudos[n] = ft(n); for (n in{submit: !0, reset: !0})o.pseudos[n] = dt(n); function gt() { } gt.prototype = o.filters = o.pseudos, o.setFilters = new gt; function mt(e, t) { var n, r, i, a, s, l, u, c = k[e + " "]; if (c)return t ? 0 : c.slice(0); s = e, l = [], u = o.preFilter; while (s) { (!n || (r = X.exec(s))) && (r && (s = s.slice(r[0].length) || s), l.push(i = [])), n = !1, (r = U.exec(s)) && (n = r.shift(), i.push({value: n, type: r[0].replace(z, " ")}), s = s.slice(n.length)); for (a in o.filter)!(r = Q[a].exec(s)) || u[a] && !(r = u[a](r)) || (n = r.shift(), i.push({value: n, type: a, matches: r}), s = s.slice(n.length)); if (!n)break } return t ? s.length : s ? at.error(e) : k(e, l).slice(0) } function yt(e) { var t = 0, n = e.length, r = ""; for (; n > t; t++)r += e[t].value; return r } function vt(e, t, n) { var r = t.dir, o = n && "parentNode" === r, a = C++; return t.first ? function (t, n, i) { while (t = t[r])if (1 === t.nodeType || o)return e(t, n, i) } : function (t, n, s) { var l, u, c, p = T + " " + a; if (s) { while (t = t[r])if ((1 === t.nodeType || o) && e(t, n, s))return!0 } else while (t = t[r])if (1 === t.nodeType || o)if (c = t[b] || (t[b] = {}), (u = c[r]) && u[0] === p) { if ((l = u[1]) === !0 || l === i)return l === !0 } else if (u = c[r] = [p], u[1] = e(t, n, s) || i, u[1] === !0)return!0 } } function bt(e) { return e.length > 1 ? function (t, n, r) { var i = e.length; while (i--)if (!e[i](t, n, r))return!1; return!0 } : e[0] } function xt(e, t, n, r, i) { var o, a = [], s = 0, l = e.length, u = null != t; for (; l > s; s++)(o = e[s]) && (!n || n(o, r, i)) && (a.push(o), u && t.push(s)); return a } function wt(e, t, n, r, i, o) { return r && !r[b] && (r = wt(r)), i && !i[b] && (i = wt(i, o)), lt(function (o, a, s, l) { var u, c, p, f = [], d = [], h = a.length, g = o || Nt(t || "*", s.nodeType ? [s] : s, []), m = !e || !o && t ? g : xt(g, f, e, s, l), y = n ? i || (o ? e : h || r) ? [] : a : m; if (n && n(m, y, s, l), r) { u = xt(y, d), r(u, [], s, l), c = u.length; while (c--)(p = u[c]) && (y[d[c]] = !(m[d[c]] = p)) } if (o) { if (i || e) { if (i) { u = [], c = y.length; while (c--)(p = y[c]) && u.push(m[c] = p); i(null, y = [], u, l) } c = y.length; while (c--)(p = y[c]) && (u = i ? F.call(o, p) : f[c]) > -1 && (o[u] = !(a[u] = p)) } } else y = xt(y === a ? y.splice(h, y.length) : y), i ? i(null, a, y, l) : M.apply(a, y) }) } function Tt(e) { var t, n, r, i = e.length, a = o.relative[e[0].type], s = a || o.relative[" "], l = a ? 1 : 0, c = vt(function (e) { return e === t }, s, !0), p = vt(function (e) { return F.call(t, e) > -1 }, s, !0), f = [function (e, n, r) { return!a && (r || n !== u) || ((t = n).nodeType ? c(e, n, r) : p(e, n, r)) }]; for (; i > l; l++)if (n = o.relative[e[l].type])f = [vt(bt(f), n)]; else { if (n = o.filter[e[l].type].apply(null, e[l].matches), n[b]) { for (r = ++l; i > r; r++)if (o.relative[e[r].type])break; return wt(l > 1 && bt(f), l > 1 && yt(e.slice(0, l - 1).concat({value: " " === e[l - 2].type ? "*" : ""})).replace(z, "$1"), n, r > l && Tt(e.slice(l, r)), i > r && Tt(e = e.slice(r)), i > r && yt(e)) } f.push(n) } return bt(f) } function Ct(e, t) { var n = 0, r = t.length > 0, a = e.length > 0, s = function (s, l, c, p, d) { var h, g, m, y = [], v = 0, b = "0", x = s && [], w = null != d, C = u, N = s || a && o.find.TAG("*", d && l.parentNode || l), k = T += null == C ? 1 : Math.random() || .1; for (w && (u = l !== f && l, i = n); null != (h = N[b]); b++) { if (a && h) { g = 0; while (m = e[g++])if (m(h, l, c)) { p.push(h); break } w && (T = k, i = ++n) } r && ((h = !m && h) && v--, s && x.push(h)) } if (v += b, r && b !== v) { g = 0; while (m = t[g++])m(x, y, l, c); if (s) { if (v > 0)while (b--)x[b] || y[b] || (y[b] = q.call(p)); y = xt(y) } M.apply(p, y), w && !s && y.length > 0 && v + t.length > 1 && at.uniqueSort(p) } return w && (T = k, u = C), x }; return r ? lt(s) : s } l = at.compile = function (e, t) { var n, r = [], i = [], o = E[e + " "]; if (!o) { t || (t = mt(e)), n = t.length; while (n--)o = Tt(t[n]), o[b] ? r.push(o) : i.push(o); o = E(e, Ct(i, r)) } return o }; function Nt(e, t, n) { var r = 0, i = t.length; for (; i > r; r++)at(e, t[r], n); return n } function kt(e, t, n, i) { var a, s, u, c, p, f = mt(e); if (!i && 1 === f.length) { if (s = f[0] = f[0].slice(0), s.length > 2 && "ID" === (u = s[0]).type && r.getById && 9 === t.nodeType && h && o.relative[s[1].type]) { if (t = (o.find.ID(u.matches[0].replace(rt, it), t) || [])[0], !t)return n; e = e.slice(s.shift().value.length) } a = Q.needsContext.test(e) ? 0 : s.length; while (a--) { if (u = s[a], o.relative[c = u.type])break; if ((p = o.find[c]) && (i = p(u.matches[0].replace(rt, it), V.test(s[0].type) && t.parentNode || t))) { if (s.splice(a, 1), e = i.length && yt(s), !e)return M.apply(n, i), n; break } } } return l(e, f)(i, t, !h, n, V.test(e)), n } r.sortStable = b.split("").sort(A).join("") === b, r.detectDuplicates = S, p(), r.sortDetached = ut(function (e) { return 1 & e.compareDocumentPosition(f.createElement("div")) }), ut(function (e) { return e.innerHTML = "<a href='#'></a>", "#" === e.firstChild.getAttribute("href") }) || ct("type|href|height|width", function (e, n, r) { return r ? t : e.getAttribute(n, "type" === n.toLowerCase() ? 1 : 2) }), r.attributes && ut(function (e) { return e.innerHTML = "<input/>", e.firstChild.setAttribute("value", ""), "" === e.firstChild.getAttribute("value") }) || ct("value", function (e, n, r) { return r || "input" !== e.nodeName.toLowerCase() ? t : e.defaultValue }), ut(function (e) { return null == e.getAttribute("disabled") }) || ct(B, function (e, n, r) { var i; return r ? t : (i = e.getAttributeNode(n)) && i.specified ? i.value : e[n] === !0 ? n.toLowerCase() : null }), x.find = at, x.expr = at.selectors, x.expr[":"] = x.expr.pseudos, x.unique = at.uniqueSort, x.text = at.getText, x.isXMLDoc = at.isXML, x.contains = at.contains }(e); var O = {}; function F(e) { var t = O[e] = {}; return x.each(e.match(T) || [], function (e, n) { t[n] = !0 }), t } x.Callbacks = function (e) { e = "string" == typeof e ? O[e] || F(e) : x.extend({}, e); var n, r, i, o, a, s, l = [], u = !e.once && [], c = function (t) { for (r = e.memory && t, i = !0, a = s || 0, s = 0, o = l.length, n = !0; l && o > a; a++)if (l[a].apply(t[0], t[1]) === !1 && e.stopOnFalse) { r = !1; break } n = !1, l && (u ? u.length && c(u.shift()) : r ? l = [] : p.disable()) }, p = {add: function () { if (l) { var t = l.length; (function i(t) { x.each(t, function (t, n) { var r = x.type(n); "function" === r ? e.unique && p.has(n) || l.push(n) : n && n.length && "string" !== r && i(n) }) })(arguments), n ? o = l.length : r && (s = t, c(r)) } return this }, remove: function () { return l && x.each(arguments, function (e, t) { var r; while ((r = x.inArray(t, l, r)) > -1)l.splice(r, 1), n && (o >= r && o--, a >= r && a--) }), this }, has: function (e) { return e ? x.inArray(e, l) > -1 : !(!l || !l.length) }, empty: function () { return l = [], o = 0, this }, disable: function () { return l = u = r = t, this }, disabled: function () { return!l }, lock: function () { return u = t, r || p.disable(), this }, locked: function () { return!u }, fireWith: function (e, t) { return!l || i && !u || (t = t || [], t = [e, t.slice ? t.slice() : t], n ? u.push(t) : c(t)), this }, fire: function () { return p.fireWith(this, arguments), this }, fired: function () { return!!i }}; return p }, x.extend({Deferred: function (e) { var t = [ ["resolve", "done", x.Callbacks("once memory"), "resolved"], ["reject", "fail", x.Callbacks("once memory"), "rejected"], ["notify", "progress", x.Callbacks("memory")] ], n = "pending", r = {state: function () { return n }, always: function () { return i.done(arguments).fail(arguments), this }, then: function () { var e = arguments; return x.Deferred(function (n) { x.each(t, function (t, o) { var a = o[0], s = x.isFunction(e[t]) && e[t]; i[o[1]](function () { var e = s && s.apply(this, arguments); e && x.isFunction(e.promise) ? e.promise().done(n.resolve).fail(n.reject).progress(n.notify) : n[a + "With"](this === r ? n.promise() : this, s ? [e] : arguments) }) }), e = null }).promise() }, promise: function (e) { return null != e ? x.extend(e, r) : r }}, i = {}; return r.pipe = r.then, x.each(t, function (e, o) { var a = o[2], s = o[3]; r[o[1]] = a.add, s && a.add(function () { n = s }, t[1 ^ e][2].disable, t[2][2].lock), i[o[0]] = function () { return i[o[0] + "With"](this === i ? r : this, arguments), this }, i[o[0] + "With"] = a.fireWith }), r.promise(i), e && e.call(i, i), i }, when: function (e) { var t = 0, n = g.call(arguments), r = n.length, i = 1 !== r || e && x.isFunction(e.promise) ? r : 0, o = 1 === i ? e : x.Deferred(), a = function (e, t, n) { return function (r) { t[e] = this, n[e] = arguments.length > 1 ? g.call(arguments) : r, n === s ? o.notifyWith(t, n) : --i || o.resolveWith(t, n) } }, s, l, u; if (r > 1)for (s = Array(r), l = Array(r), u = Array(r); r > t; t++)n[t] && x.isFunction(n[t].promise) ? n[t].promise().done(a(t, u, n)).fail(o.reject).progress(a(t, l, s)) : --i; return i || o.resolveWith(u, n), o.promise() }}), x.support = function (t) { var n, r, o, s, l, u, c, p, f, d = a.createElement("div"); if (d.setAttribute("className", "t"), d.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>", n = d.getElementsByTagName("*") || [], r = d.getElementsByTagName("a")[0], !r || !r.style || !n.length)return t; s = a.createElement("select"), u = s.appendChild(a.createElement("option")), o = d.getElementsByTagName("input")[0], r.style.cssText = "top:1px;float:left;opacity:.5", t.getSetAttribute = "t" !== d.className, t.leadingWhitespace = 3 === d.firstChild.nodeType, t.tbody = !d.getElementsByTagName("tbody").length, t.htmlSerialize = !!d.getElementsByTagName("link").length, t.style = /top/.test(r.getAttribute("style")), t.hrefNormalized = "/a" === r.getAttribute("href"), t.opacity = /^0.5/.test(r.style.opacity), t.cssFloat = !!r.style.cssFloat, t.checkOn = !!o.value, t.optSelected = u.selected, t.enctype = !!a.createElement("form").enctype, t.html5Clone = "<:nav></:nav>" !== a.createElement("nav").cloneNode(!0).outerHTML, t.inlineBlockNeedsLayout = !1, t.shrinkWrapBlocks = !1, t.pixelPosition = !1, t.deleteExpando = !0, t.noCloneEvent = !0, t.reliableMarginRight = !0, t.boxSizingReliable = !0, o.checked = !0, t.noCloneChecked = o.cloneNode(!0).checked, s.disabled = !0, t.optDisabled = !u.disabled; try { delete d.test } catch (h) { t.deleteExpando = !1 } o = a.createElement("input"), o.setAttribute("value", ""), t.input = "" === o.getAttribute("value"), o.value = "t", o.setAttribute("type", "radio"), t.radioValue = "t" === o.value, o.setAttribute("checked", "t"), o.setAttribute("name", "t"), l = a.createDocumentFragment(), l.appendChild(o), t.appendChecked = o.checked, t.checkClone = l.cloneNode(!0).cloneNode(!0).lastChild.checked, d.attachEvent && (d.attachEvent("onclick", function () { t.noCloneEvent = !1 }), d.cloneNode(!0).click()); for (f in{submit: !0, change: !0, focusin: !0})d.setAttribute(c = "on" + f, "t"), t[f + "Bubbles"] = c in e || d.attributes[c].expando === !1; d.style.backgroundClip = "content-box", d.cloneNode(!0).style.backgroundClip = "", t.clearCloneStyle = "content-box" === d.style.backgroundClip; for (f in x(t))break; return t.ownLast = "0" !== f, x(function () { var n, r, o, s = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;", l = a.getElementsByTagName("body")[0]; l && (n = a.createElement("div"), n.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px", l.appendChild(n).appendChild(d), d.innerHTML = "<table><tr><td></td><td>t</td></tr></table>", o = d.getElementsByTagName("td"), o[0].style.cssText = "padding:0;margin:0;border:0;display:none", p = 0 === o[0].offsetHeight, o[0].style.display = "", o[1].style.display = "none", t.reliableHiddenOffsets = p && 0 === o[0].offsetHeight, d.innerHTML = "", d.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;", x.swap(l, null != l.style.zoom ? {zoom: 1} : {}, function () { t.boxSizing = 4 === d.offsetWidth }), e.getComputedStyle && (t.pixelPosition = "1%" !== (e.getComputedStyle(d, null) || {}).top, t.boxSizingReliable = "4px" === (e.getComputedStyle(d, null) || {width: "4px"}).width, r = d.appendChild(a.createElement("div")), r.style.cssText = d.style.cssText = s, r.style.marginRight = r.style.width = "0", d.style.width = "1px", t.reliableMarginRight = !parseFloat((e.getComputedStyle(r, null) || {}).marginRight)), typeof d.style.zoom !== i && (d.innerHTML = "", d.style.cssText = s + "width:1px;padding:1px;display:inline;zoom:1", t.inlineBlockNeedsLayout = 3 === d.offsetWidth, d.style.display = "block", d.innerHTML = "<div></div>", d.firstChild.style.width = "5px", t.shrinkWrapBlocks = 3 !== d.offsetWidth, t.inlineBlockNeedsLayout && (l.style.zoom = 1)), l.removeChild(n), n = d = o = r = null) }), n = s = l = u = r = o = null, t }({}); var B = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, P = /([A-Z])/g; function R(e, n, r, i) { if (x.acceptData(e)) { var o, a, s = x.expando, l = e.nodeType, u = l ? x.cache : e, c = l ? e[s] : e[s] && s; if (c && u[c] && (i || u[c].data) || r !== t || "string" != typeof n)return c || (c = l ? e[s] = p.pop() || x.guid++ : s), u[c] || (u[c] = l ? {} : {toJSON: x.noop}), ("object" == typeof n || "function" == typeof n) && (i ? u[c] = x.extend(u[c], n) : u[c].data = x.extend(u[c].data, n)), a = u[c], i || (a.data || (a.data = {}), a = a.data), r !== t && (a[x.camelCase(n)] = r), "string" == typeof n ? (o = a[n], null == o && (o = a[x.camelCase(n)])) : o = a, o } } function W(e, t, n) { if (x.acceptData(e)) { var r, i, o = e.nodeType, a = o ? x.cache : e, s = o ? e[x.expando] : x.expando; if (a[s]) { if (t && (r = n ? a[s] : a[s].data)) { x.isArray(t) ? t = t.concat(x.map(t, x.camelCase)) : t in r ? t = [t] : (t = x.camelCase(t), t = t in r ? [t] : t.split(" ")), i = t.length; while (i--)delete r[t[i]]; if (n ? !I(r) : !x.isEmptyObject(r))return } (n || (delete a[s].data, I(a[s]))) && (o ? x.cleanData([e], !0) : x.support.deleteExpando || a != a.window ? delete a[s] : a[s] = null) } } } x.extend({cache: {}, noData: {applet: !0, embed: !0, object: "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"}, hasData: function (e) { return e = e.nodeType ? x.cache[e[x.expando]] : e[x.expando], !!e && !I(e) }, data: function (e, t, n) { return R(e, t, n) }, removeData: function (e, t) { return W(e, t) }, _data: function (e, t, n) { return R(e, t, n, !0) }, _removeData: function (e, t) { return W(e, t, !0) }, acceptData: function (e) { if (e.nodeType && 1 !== e.nodeType && 9 !== e.nodeType)return!1; var t = e.nodeName && x.noData[e.nodeName.toLowerCase()]; return!t || t !== !0 && e.getAttribute("classid") === t }}), x.fn.extend({data: function (e, n) { var r, i, o = null, a = 0, s = this[0]; if (e === t) { if (this.length && (o = x.data(s), 1 === s.nodeType && !x._data(s, "parsedAttrs"))) { for (r = s.attributes; r.length > a; a++)i = r[a].name, 0 === i.indexOf("data-") && (i = x.camelCase(i.slice(5)), $(s, i, o[i])); x._data(s, "parsedAttrs", !0) } return o } return"object" == typeof e ? this.each(function () { x.data(this, e) }) : arguments.length > 1 ? this.each(function () { x.data(this, e, n) }) : s ? $(s, e, x.data(s, e)) : null }, removeData: function (e) { return this.each(function () { x.removeData(this, e) }) }}); function $(e, n, r) { if (r === t && 1 === e.nodeType) { var i = "data-" + n.replace(P, "-$1").toLowerCase(); if (r = e.getAttribute(i), "string" == typeof r) { try { r = "true" === r ? !0 : "false" === r ? !1 : "null" === r ? null : +r + "" === r ? +r : B.test(r) ? x.parseJSON(r) : r } catch (o) { } x.data(e, n, r) } else r = t } return r } function I(e) { var t; for (t in e)if (("data" !== t || !x.isEmptyObject(e[t])) && "toJSON" !== t)return!1; return!0 } x.extend({queue: function (e, n, r) { var i; return e ? (n = (n || "fx") + "queue", i = x._data(e, n), r && (!i || x.isArray(r) ? i = x._data(e, n, x.makeArray(r)) : i.push(r)), i || []) : t }, dequeue: function (e, t) { t = t || "fx"; var n = x.queue(e, t), r = n.length, i = n.shift(), o = x._queueHooks(e, t), a = function () { x.dequeue(e, t) }; "inprogress" === i && (i = n.shift(), r--), i && ("fx" === t && n.unshift("inprogress"), delete o.stop, i.call(e, a, o)), !r && o && o.empty.fire() }, _queueHooks: function (e, t) { var n = t + "queueHooks"; return x._data(e, n) || x._data(e, n, {empty: x.Callbacks("once memory").add(function () { x._removeData(e, t + "queue"), x._removeData(e, n) })}) }}), x.fn.extend({queue: function (e, n) { var r = 2; return"string" != typeof e && (n = e, e = "fx", r--), r > arguments.length ? x.queue(this[0], e) : n === t ? this : this.each(function () { var t = x.queue(this, e, n); x._queueHooks(this, e), "fx" === e && "inprogress" !== t[0] && x.dequeue(this, e) }) }, dequeue: function (e) { return this.each(function () { x.dequeue(this, e) }) }, delay: function (e, t) { return e = x.fx ? x.fx.speeds[e] || e : e, t = t || "fx", this.queue(t, function (t, n) { var r = setTimeout(t, e); n.stop = function () { clearTimeout(r) } }) }, clearQueue: function (e) { return this.queue(e || "fx", []) }, promise: function (e, n) { var r, i = 1, o = x.Deferred(), a = this, s = this.length, l = function () { --i || o.resolveWith(a, [a]) }; "string" != typeof e && (n = e, e = t), e = e || "fx"; while (s--)r = x._data(a[s], e + "queueHooks"), r && r.empty && (i++, r.empty.add(l)); return l(), o.promise(n) }}); var z, X, U = /[\t\r\n\f]/g, V = /\r/g, Y = /^(?:input|select|textarea|button|object)$/i, J = /^(?:a|area)$/i, G = /^(?:checked|selected)$/i, Q = x.support.getSetAttribute, K = x.support.input; x.fn.extend({attr: function (e, t) { return x.access(this, x.attr, e, t, arguments.length > 1) }, removeAttr: function (e) { return this.each(function () { x.removeAttr(this, e) }) }, prop: function (e, t) { return x.access(this, x.prop, e, t, arguments.length > 1) }, removeProp: function (e) { return e = x.propFix[e] || e, this.each(function () { try { this[e] = t, delete this[e] } catch (n) { } }) }, addClass: function (e) { var t, n, r, i, o, a = 0, s = this.length, l = "string" == typeof e && e; if (x.isFunction(e))return this.each(function (t) { x(this).addClass(e.call(this, t, this.className)) }); if (l)for (t = (e || "").match(T) || []; s > a; a++)if (n = this[a], r = 1 === n.nodeType && (n.className ? (" " + n.className + " ").replace(U, " ") : " ")) { o = 0; while (i = t[o++])0 > r.indexOf(" " + i + " ") && (r += i + " "); n.className = x.trim(r) } return this }, removeClass: function (e) { var t, n, r, i, o, a = 0, s = this.length, l = 0 === arguments.length || "string" == typeof e && e; if (x.isFunction(e))return this.each(function (t) { x(this).removeClass(e.call(this, t, this.className)) }); if (l)for (t = (e || "").match(T) || []; s > a; a++)if (n = this[a], r = 1 === n.nodeType && (n.className ? (" " + n.className + " ").replace(U, " ") : "")) { o = 0; while (i = t[o++])while (r.indexOf(" " + i + " ") >= 0)r = r.replace(" " + i + " ", " "); n.className = e ? x.trim(r) : "" } return this }, toggleClass: function (e, t) { var n = typeof e; return"boolean" == typeof t && "string" === n ? t ? this.addClass(e) : this.removeClass(e) : x.isFunction(e) ? this.each(function (n) { x(this).toggleClass(e.call(this, n, this.className, t), t) }) : this.each(function () { if ("string" === n) { var t, r = 0, o = x(this), a = e.match(T) || []; while (t = a[r++])o.hasClass(t) ? o.removeClass(t) : o.addClass(t) } else(n === i || "boolean" === n) && (this.className && x._data(this, "__className__", this.className), this.className = this.className || e === !1 ? "" : x._data(this, "__className__") || "") }) }, hasClass: function (e) { var t = " " + e + " ", n = 0, r = this.length; for (; r > n; n++)if (1 === this[n].nodeType && (" " + this[n].className + " ").replace(U, " ").indexOf(t) >= 0)return!0; return!1 }, val: function (e) { var n, r, i, o = this[0]; { if (arguments.length)return i = x.isFunction(e), this.each(function (n) { var o; 1 === this.nodeType && (o = i ? e.call(this, n, x(this).val()) : e, null == o ? o = "" : "number" == typeof o ? o += "" : x.isArray(o) && (o = x.map(o, function (e) { return null == e ? "" : e + "" })), r = x.valHooks[this.type] || x.valHooks[this.nodeName.toLowerCase()], r && "set"in r && r.set(this, o, "value") !== t || (this.value = o)) }); if (o)return r = x.valHooks[o.type] || x.valHooks[o.nodeName.toLowerCase()], r && "get"in r && (n = r.get(o, "value")) !== t ? n : (n = o.value, "string" == typeof n ? n.replace(V, "") : null == n ? "" : n) } }}), x.extend({valHooks: {option: {get: function (e) { var t = x.find.attr(e, "value"); return null != t ? t : e.text }}, select: {get: function (e) { var t, n, r = e.options, i = e.selectedIndex, o = "select-one" === e.type || 0 > i, a = o ? null : [], s = o ? i + 1 : r.length, l = 0 > i ? s : o ? i : 0; for (; s > l; l++)if (n = r[l], !(!n.selected && l !== i || (x.support.optDisabled ? n.disabled : null !== n.getAttribute("disabled")) || n.parentNode.disabled && x.nodeName(n.parentNode, "optgroup"))) { if (t = x(n).val(), o)return t; a.push(t) } return a }, set: function (e, t) { var n, r, i = e.options, o = x.makeArray(t), a = i.length; while (a--)r = i[a], (r.selected = x.inArray(x(r).val(), o) >= 0) && (n = !0); return n || (e.selectedIndex = -1), o }}}, attr: function (e, n, r) { var o, a, s = e.nodeType; if (e && 3 !== s && 8 !== s && 2 !== s)return typeof e.getAttribute === i ? x.prop(e, n, r) : (1 === s && x.isXMLDoc(e) || (n = n.toLowerCase(), o = x.attrHooks[n] || (x.expr.match.bool.test(n) ? X : z)), r === t ? o && "get"in o && null !== (a = o.get(e, n)) ? a : (a = x.find.attr(e, n), null == a ? t : a) : null !== r ? o && "set"in o && (a = o.set(e, r, n)) !== t ? a : (e.setAttribute(n, r + ""), r) : (x.removeAttr(e, n), t)) }, removeAttr: function (e, t) { var n, r, i = 0, o = t && t.match(T); if (o && 1 === e.nodeType)while (n = o[i++])r = x.propFix[n] || n, x.expr.match.bool.test(n) ? K && Q || !G.test(n) ? e[r] = !1 : e[x.camelCase("default-" + n)] = e[r] = !1 : x.attr(e, n, ""), e.removeAttribute(Q ? n : r) }, attrHooks: {type: {set: function (e, t) { if (!x.support.radioValue && "radio" === t && x.nodeName(e, "input")) { var n = e.value; return e.setAttribute("type", t), n && (e.value = n), t } }}}, propFix: {"for": "htmlFor", "class": "className"}, prop: function (e, n, r) { var i, o, a, s = e.nodeType; if (e && 3 !== s && 8 !== s && 2 !== s)return a = 1 !== s || !x.isXMLDoc(e), a && (n = x.propFix[n] || n, o = x.propHooks[n]), r !== t ? o && "set"in o && (i = o.set(e, r, n)) !== t ? i : e[n] = r : o && "get"in o && null !== (i = o.get(e, n)) ? i : e[n] }, propHooks: {tabIndex: {get: function (e) { var t = x.find.attr(e, "tabindex"); return t ? parseInt(t, 10) : Y.test(e.nodeName) || J.test(e.nodeName) && e.href ? 0 : -1 }}}}), X = {set: function (e, t, n) { return t === !1 ? x.removeAttr(e, n) : K && Q || !G.test(n) ? e.setAttribute(!Q && x.propFix[n] || n, n) : e[x.camelCase("default-" + n)] = e[n] = !0, n }}, x.each(x.expr.match.bool.source.match(/\w+/g), function (e, n) { var r = x.expr.attrHandle[n] || x.find.attr; x.expr.attrHandle[n] = K && Q || !G.test(n) ? function (e, n, i) { var o = x.expr.attrHandle[n], a = i ? t : (x.expr.attrHandle[n] = t) != r(e, n, i) ? n.toLowerCase() : null; return x.expr.attrHandle[n] = o, a } : function (e, n, r) { return r ? t : e[x.camelCase("default-" + n)] ? n.toLowerCase() : null } }), K && Q || (x.attrHooks.value = {set: function (e, n, r) { return x.nodeName(e, "input") ? (e.defaultValue = n, t) : z && z.set(e, n, r) }}), Q || (z = {set: function (e, n, r) { var i = e.getAttributeNode(r); return i || e.setAttributeNode(i = e.ownerDocument.createAttribute(r)), i.value = n += "", "value" === r || n === e.getAttribute(r) ? n : t }}, x.expr.attrHandle.id = x.expr.attrHandle.name = x.expr.attrHandle.coords = function (e, n, r) { var i; return r ? t : (i = e.getAttributeNode(n)) && "" !== i.value ? i.value : null }, x.valHooks.button = {get: function (e, n) { var r = e.getAttributeNode(n); return r && r.specified ? r.value : t }, set: z.set}, x.attrHooks.contenteditable = {set: function (e, t, n) { z.set(e, "" === t ? !1 : t, n) }}, x.each(["width", "height"], function (e, n) { x.attrHooks[n] = {set: function (e, r) { return"" === r ? (e.setAttribute(n, "auto"), r) : t }} })), x.support.hrefNormalized || x.each(["href", "src"], function (e, t) { x.propHooks[t] = {get: function (e) { return e.getAttribute(t, 4) }} }), x.support.style || (x.attrHooks.style = {get: function (e) { return e.style.cssText || t }, set: function (e, t) { return e.style.cssText = t + "" }}), x.support.optSelected || (x.propHooks.selected = {get: function (e) { var t = e.parentNode; return t && (t.selectedIndex, t.parentNode && t.parentNode.selectedIndex), null }}), x.each(["tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable"], function () { x.propFix[this.toLowerCase()] = this }), x.support.enctype || (x.propFix.enctype = "encoding"), x.each(["radio", "checkbox"], function () { x.valHooks[this] = {set: function (e, n) { return x.isArray(n) ? e.checked = x.inArray(x(e).val(), n) >= 0 : t }}, x.support.checkOn || (x.valHooks[this].get = function (e) { return null === e.getAttribute("value") ? "on" : e.value }) }); var Z = /^(?:input|select|textarea)$/i, et = /^key/, tt = /^(?:mouse|contextmenu)|click/, nt = /^(?:focusinfocus|focusoutblur)$/, rt = /^([^.]*)(?:\.(.+)|)$/; function it() { return!0 } function ot() { return!1 } function at() { try { return a.activeElement } catch (e) { } } x.event = {global: {}, add: function (e, n, r, o, a) { var s, l, u, c, p, f, d, h, g, m, y, v = x._data(e); if (v) { r.handler && (c = r, r = c.handler, a = c.selector), r.guid || (r.guid = x.guid++), (l = v.events) || (l = v.events = {}), (f = v.handle) || (f = v.handle = function (e) { return typeof x === i || e && x.event.triggered === e.type ? t : x.event.dispatch.apply(f.elem, arguments) }, f.elem = e), n = (n || "").match(T) || [""], u = n.length; while (u--)s = rt.exec(n[u]) || [], g = y = s[1], m = (s[2] || "").split(".").sort(), g && (p = x.event.special[g] || {}, g = (a ? p.delegateType : p.bindType) || g, p = x.event.special[g] || {}, d = x.extend({type: g, origType: y, data: o, handler: r, guid: r.guid, selector: a, needsContext: a && x.expr.match.needsContext.test(a), namespace: m.join(".")}, c), (h = l[g]) || (h = l[g] = [], h.delegateCount = 0, p.setup && p.setup.call(e, o, m, f) !== !1 || (e.addEventListener ? e.addEventListener(g, f, !1) : e.attachEvent && e.attachEvent("on" + g, f))), p.add && (p.add.call(e, d), d.handler.guid || (d.handler.guid = r.guid)), a ? h.splice(h.delegateCount++, 0, d) : h.push(d), x.event.global[g] = !0); e = null } }, remove: function (e, t, n, r, i) { var o, a, s, l, u, c, p, f, d, h, g, m = x.hasData(e) && x._data(e); if (m && (c = m.events)) { t = (t || "").match(T) || [""], u = t.length; while (u--)if (s = rt.exec(t[u]) || [], d = g = s[1], h = (s[2] || "").split(".").sort(), d) { p = x.event.special[d] || {}, d = (r ? p.delegateType : p.bindType) || d, f = c[d] || [], s = s[2] && RegExp("(^|\\.)" + h.join("\\.(?:.*\\.|)") + "(\\.|$)"), l = o = f.length; while (o--)a = f[o], !i && g !== a.origType || n && n.guid !== a.guid || s && !s.test(a.namespace) || r && r !== a.selector && ("**" !== r || !a.selector) || (f.splice(o, 1), a.selector && f.delegateCount--, p.remove && p.remove.call(e, a)); l && !f.length && (p.teardown && p.teardown.call(e, h, m.handle) !== !1 || x.removeEvent(e, d, m.handle), delete c[d]) } else for (d in c)x.event.remove(e, d + t[u], n, r, !0); x.isEmptyObject(c) && (delete m.handle, x._removeData(e, "events")) } }, trigger: function (n, r, i, o) { var s, l, u, c, p, f, d, h = [i || a], g = v.call(n, "type") ? n.type : n, m = v.call(n, "namespace") ? n.namespace.split(".") : []; if (u = f = i = i || a, 3 !== i.nodeType && 8 !== i.nodeType && !nt.test(g + x.event.triggered) && (g.indexOf(".") >= 0 && (m = g.split("."), g = m.shift(), m.sort()), l = 0 > g.indexOf(":") && "on" + g, n = n[x.expando] ? n : new x.Event(g, "object" == typeof n && n), n.isTrigger = o ? 2 : 3, n.namespace = m.join("."), n.namespace_re = n.namespace ? RegExp("(^|\\.)" + m.join("\\.(?:.*\\.|)") + "(\\.|$)") : null, n.result = t, n.target || (n.target = i), r = null == r ? [n] : x.makeArray(r, [n]), p = x.event.special[g] || {}, o || !p.trigger || p.trigger.apply(i, r) !== !1)) { if (!o && !p.noBubble && !x.isWindow(i)) { for (c = p.delegateType || g, nt.test(c + g) || (u = u.parentNode); u; u = u.parentNode)h.push(u), f = u; f === (i.ownerDocument || a) && h.push(f.defaultView || f.parentWindow || e) } d = 0; while ((u = h[d++]) && !n.isPropagationStopped())n.type = d > 1 ? c : p.bindType || g, s = (x._data(u, "events") || {})[n.type] && x._data(u, "handle"), s && s.apply(u, r), s = l && u[l], s && x.acceptData(u) && s.apply && s.apply(u, r) === !1 && n.preventDefault(); if (n.type = g, !o && !n.isDefaultPrevented() && (!p._default || p._default.apply(h.pop(), r) === !1) && x.acceptData(i) && l && i[g] && !x.isWindow(i)) { f = i[l], f && (i[l] = null), x.event.triggered = g; try { i[g]() } catch (y) { } x.event.triggered = t, f && (i[l] = f) } return n.result } }, dispatch: function (e) { e = x.event.fix(e); var n, r, i, o, a, s = [], l = g.call(arguments), u = (x._data(this, "events") || {})[e.type] || [], c = x.event.special[e.type] || {}; if (l[0] = e, e.delegateTarget = this, !c.preDispatch || c.preDispatch.call(this, e) !== !1) { s = x.event.handlers.call(this, e, u), n = 0; while ((o = s[n++]) && !e.isPropagationStopped()) { e.currentTarget = o.elem, a = 0; while ((i = o.handlers[a++]) && !e.isImmediatePropagationStopped())(!e.namespace_re || e.namespace_re.test(i.namespace)) && (e.handleObj = i, e.data = i.data, r = ((x.event.special[i.origType] || {}).handle || i.handler).apply(o.elem, l), r !== t && (e.result = r) === !1 && (e.preventDefault(), e.stopPropagation())) } return c.postDispatch && c.postDispatch.call(this, e), e.result } }, handlers: function (e, n) { var r, i, o, a, s = [], l = n.delegateCount, u = e.target; if (l && u.nodeType && (!e.button || "click" !== e.type))for (; u != this; u = u.parentNode || this)if (1 === u.nodeType && (u.disabled !== !0 || "click" !== e.type)) { for (o = [], a = 0; l > a; a++)i = n[a], r = i.selector + " ", o[r] === t && (o[r] = i.needsContext ? x(r, this).index(u) >= 0 : x.find(r, this, null, [u]).length), o[r] && o.push(i); o.length && s.push({elem: u, handlers: o}) } return n.length > l && s.push({elem: this, handlers: n.slice(l)}), s }, fix: function (e) { if (e[x.expando])return e; var t, n, r, i = e.type, o = e, s = this.fixHooks[i]; s || (this.fixHooks[i] = s = tt.test(i) ? this.mouseHooks : et.test(i) ? this.keyHooks : {}), r = s.props ? this.props.concat(s.props) : this.props, e = new x.Event(o), t = r.length; while (t--)n = r[t], e[n] = o[n]; return e.target || (e.target = o.srcElement || a), 3 === e.target.nodeType && (e.target = e.target.parentNode), e.metaKey = !!e.metaKey, s.filter ? s.filter(e, o) : e }, props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: {props: "char charCode key keyCode".split(" "), filter: function (e, t) { return null == e.which && (e.which = null != t.charCode ? t.charCode : t.keyCode), e }}, mouseHooks: {props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function (e, n) { var r, i, o, s = n.button, l = n.fromElement; return null == e.pageX && null != n.clientX && (i = e.target.ownerDocument || a, o = i.documentElement, r = i.body, e.pageX = n.clientX + (o && o.scrollLeft || r && r.scrollLeft || 0) - (o && o.clientLeft || r && r.clientLeft || 0), e.pageY = n.clientY + (o && o.scrollTop || r && r.scrollTop || 0) - (o && o.clientTop || r && r.clientTop || 0)), !e.relatedTarget && l && (e.relatedTarget = l === e.target ? n.toElement : l), e.which || s === t || (e.which = 1 & s ? 1 : 2 & s ? 3 : 4 & s ? 2 : 0), e }}, special: {load: {noBubble: !0}, focus: {trigger: function () { if (this !== at() && this.focus)try { return this.focus(), !1 } catch (e) { } }, delegateType: "focusin"}, blur: {trigger: function () { return this === at() && this.blur ? (this.blur(), !1) : t }, delegateType: "focusout"}, click: {trigger: function () { return x.nodeName(this, "input") && "checkbox" === this.type && this.click ? (this.click(), !1) : t }, _default: function (e) { return x.nodeName(e.target, "a") }}, beforeunload: {postDispatch: function (e) { e.result !== t && (e.originalEvent.returnValue = e.result) }}}, simulate: function (e, t, n, r) { var i = x.extend(new x.Event, n, {type: e, isSimulated: !0, originalEvent: {}}); r ? x.event.trigger(i, null, t) : x.event.dispatch.call(t, i), i.isDefaultPrevented() && n.preventDefault() }}, x.removeEvent = a.removeEventListener ? function (e, t, n) { e.removeEventListener && e.removeEventListener(t, n, !1) } : function (e, t, n) { var r = "on" + t; e.detachEvent && (typeof e[r] === i && (e[r] = null), e.detachEvent(r, n)) }, x.Event = function (e, n) { return this instanceof x.Event ? (e && e.type ? (this.originalEvent = e, this.type = e.type, this.isDefaultPrevented = e.defaultPrevented || e.returnValue === !1 || e.getPreventDefault && e.getPreventDefault() ? it : ot) : this.type = e, n && x.extend(this, n), this.timeStamp = e && e.timeStamp || x.now(), this[x.expando] = !0, t) : new x.Event(e, n) }, x.Event.prototype = {isDefaultPrevented: ot, isPropagationStopped: ot, isImmediatePropagationStopped: ot, preventDefault: function () { var e = this.originalEvent; this.isDefaultPrevented = it, e && (e.preventDefault ? e.preventDefault() : e.returnValue = !1) }, stopPropagation: function () { var e = this.originalEvent; this.isPropagationStopped = it, e && (e.stopPropagation && e.stopPropagation(), e.cancelBubble = !0) }, stopImmediatePropagation: function () { this.isImmediatePropagationStopped = it, this.stopPropagation() }}, x.each({mouseenter: "mouseover", mouseleave: "mouseout"}, function (e, t) { x.event.special[e] = {delegateType: t, bindType: t, handle: function (e) { var n, r = this, i = e.relatedTarget, o = e.handleObj; return(!i || i !== r && !x.contains(r, i)) && (e.type = o.origType, n = o.handler.apply(this, arguments), e.type = t), n }} }), x.support.submitBubbles || (x.event.special.submit = {setup: function () { return x.nodeName(this, "form") ? !1 : (x.event.add(this, "click._submit keypress._submit", function (e) { var n = e.target, r = x.nodeName(n, "input") || x.nodeName(n, "button") ? n.form : t; r && !x._data(r, "submitBubbles") && (x.event.add(r, "submit._submit", function (e) { e._submit_bubble = !0 }), x._data(r, "submitBubbles", !0)) }), t) }, postDispatch: function (e) { e._submit_bubble && (delete e._submit_bubble, this.parentNode && !e.isTrigger && x.event.simulate("submit", this.parentNode, e, !0)) }, teardown: function () { return x.nodeName(this, "form") ? !1 : (x.event.remove(this, "._submit"), t) }}), x.support.changeBubbles || (x.event.special.change = {setup: function () { return Z.test(this.nodeName) ? (("checkbox" === this.type || "radio" === this.type) && (x.event.add(this, "propertychange._change", function (e) { "checked" === e.originalEvent.propertyName && (this._just_changed = !0) }), x.event.add(this, "click._change", function (e) { this._just_changed && !e.isTrigger && (this._just_changed = !1), x.event.simulate("change", this, e, !0) })), !1) : (x.event.add(this, "beforeactivate._change", function (e) { var t = e.target; Z.test(t.nodeName) && !x._data(t, "changeBubbles") && (x.event.add(t, "change._change", function (e) { !this.parentNode || e.isSimulated || e.isTrigger || x.event.simulate("change", this.parentNode, e, !0) }), x._data(t, "changeBubbles", !0)) }), t) }, handle: function (e) { var n = e.target; return this !== n || e.isSimulated || e.isTrigger || "radio" !== n.type && "checkbox" !== n.type ? e.handleObj.handler.apply(this, arguments) : t }, teardown: function () { return x.event.remove(this, "._change"), !Z.test(this.nodeName) }}), x.support.focusinBubbles || x.each({focus: "focusin", blur: "focusout"}, function (e, t) { var n = 0, r = function (e) { x.event.simulate(t, e.target, x.event.fix(e), !0) }; x.event.special[t] = {setup: function () { 0 === n++ && a.addEventListener(e, r, !0) }, teardown: function () { 0 === --n && a.removeEventListener(e, r, !0) }} }), x.fn.extend({on: function (e, n, r, i, o) { var a, s; if ("object" == typeof e) { "string" != typeof n && (r = r || n, n = t); for (a in e)this.on(a, n, r, e[a], o); return this } if (null == r && null == i ? (i = n, r = n = t) : null == i && ("string" == typeof n ? (i = r, r = t) : (i = r, r = n, n = t)), i === !1)i = ot; else if (!i)return this; return 1 === o && (s = i, i = function (e) { return x().off(e), s.apply(this, arguments) }, i.guid = s.guid || (s.guid = x.guid++)), this.each(function () { x.event.add(this, e, i, r, n) }) }, one: function (e, t, n, r) { return this.on(e, t, n, r, 1) }, off: function (e, n, r) { var i, o; if (e && e.preventDefault && e.handleObj)return i = e.handleObj, x(e.delegateTarget).off(i.namespace ? i.origType + "." + i.namespace : i.origType, i.selector, i.handler), this; if ("object" == typeof e) { for (o in e)this.off(o, n, e[o]); return this } return(n === !1 || "function" == typeof n) && (r = n, n = t), r === !1 && (r = ot), this.each(function () { x.event.remove(this, e, r, n) }) }, trigger: function (e, t) { return this.each(function () { x.event.trigger(e, t, this) }) }, triggerHandler: function (e, n) { var r = this[0]; return r ? x.event.trigger(e, n, r, !0) : t }}); var st = /^.[^:#\[\.,]*$/, lt = /^(?:parents|prev(?:Until|All))/, ut = x.expr.match.needsContext, ct = {children: !0, contents: !0, next: !0, prev: !0}; x.fn.extend({find: function (e) { var t, n = [], r = this, i = r.length; if ("string" != typeof e)return this.pushStack(x(e).filter(function () { for (t = 0; i > t; t++)if (x.contains(r[t], this))return!0 })); for (t = 0; i > t; t++)x.find(e, r[t], n); return n = this.pushStack(i > 1 ? x.unique(n) : n), n.selector = this.selector ? this.selector + " " + e : e, n }, has: function (e) { var t, n = x(e, this), r = n.length; return this.filter(function () { for (t = 0; r > t; t++)if (x.contains(this, n[t]))return!0 }) }, not: function (e) { return this.pushStack(ft(this, e || [], !0)) }, filter: function (e) { return this.pushStack(ft(this, e || [], !1)) }, is: function (e) { return!!ft(this, "string" == typeof e && ut.test(e) ? x(e) : e || [], !1).length }, closest: function (e, t) { var n, r = 0, i = this.length, o = [], a = ut.test(e) || "string" != typeof e ? x(e, t || this.context) : 0; for (; i > r; r++)for (n = this[r]; n && n !== t; n = n.parentNode)if (11 > n.nodeType && (a ? a.index(n) > -1 : 1 === n.nodeType && x.find.matchesSelector(n, e))) { n = o.push(n); break } return this.pushStack(o.length > 1 ? x.unique(o) : o) }, index: function (e) { return e ? "string" == typeof e ? x.inArray(this[0], x(e)) : x.inArray(e.jquery ? e[0] : e, this) : this[0] && this[0].parentNode ? this.first().prevAll().length : -1 }, add: function (e, t) { var n = "string" == typeof e ? x(e, t) : x.makeArray(e && e.nodeType ? [e] : e), r = x.merge(this.get(), n); return this.pushStack(x.unique(r)) }, addBack: function (e) { return this.add(null == e ? this.prevObject : this.prevObject.filter(e)) }}); function pt(e, t) { do e = e[t]; while (e && 1 !== e.nodeType); return e } x.each({parent: function (e) { var t = e.parentNode; return t && 11 !== t.nodeType ? t : null }, parents: function (e) { return x.dir(e, "parentNode") }, parentsUntil: function (e, t, n) { return x.dir(e, "parentNode", n) }, next: function (e) { return pt(e, "nextSibling") }, prev: function (e) { return pt(e, "previousSibling") }, nextAll: function (e) { return x.dir(e, "nextSibling") }, prevAll: function (e) { return x.dir(e, "previousSibling") }, nextUntil: function (e, t, n) { return x.dir(e, "nextSibling", n) }, prevUntil: function (e, t, n) { return x.dir(e, "previousSibling", n) }, siblings: function (e) { return x.sibling((e.parentNode || {}).firstChild, e) }, children: function (e) { return x.sibling(e.firstChild) }, contents: function (e) { return x.nodeName(e, "iframe") ? e.contentDocument || e.contentWindow.document : x.merge([], e.childNodes) }}, function (e, t) { x.fn[e] = function (n, r) { var i = x.map(this, t, n); return"Until" !== e.slice(-5) && (r = n), r && "string" == typeof r && (i = x.filter(r, i)), this.length > 1 && (ct[e] || (i = x.unique(i)), lt.test(e) && (i = i.reverse())), this.pushStack(i) } }), x.extend({filter: function (e, t, n) { var r = t[0]; return n && (e = ":not(" + e + ")"), 1 === t.length && 1 === r.nodeType ? x.find.matchesSelector(r, e) ? [r] : [] : x.find.matches(e, x.grep(t, function (e) { return 1 === e.nodeType })) }, dir: function (e, n, r) { var i = [], o = e[n]; while (o && 9 !== o.nodeType && (r === t || 1 !== o.nodeType || !x(o).is(r)))1 === o.nodeType && i.push(o), o = o[n]; return i }, sibling: function (e, t) { var n = []; for (; e; e = e.nextSibling)1 === e.nodeType && e !== t && n.push(e); return n }}); function ft(e, t, n) { if (x.isFunction(t))return x.grep(e, function (e, r) { return!!t.call(e, r, e) !== n }); if (t.nodeType)return x.grep(e, function (e) { return e === t !== n }); if ("string" == typeof t) { if (st.test(t))return x.filter(t, e, n); t = x.filter(t, e) } return x.grep(e, function (e) { return x.inArray(e, t) >= 0 !== n }) } function dt(e) { var t = ht.split("|"), n = e.createDocumentFragment(); if (n.createElement)while (t.length)n.createElement(t.pop()); return n } var ht = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", gt = / jQuery\d+="(?:null|\d+)"/g, mt = RegExp("<(?:" + ht + ")[\\s/>]", "i"), yt = /^\s+/, vt = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, bt = /<([\w:]+)/, xt = /<tbody/i, wt = /<|&#?\w+;/, Tt = /<(?:script|style|link)/i, Ct = /^(?:checkbox|radio)$/i, Nt = /checked\s*(?:[^=]|=\s*.checked.)/i, kt = /^$|\/(?:java|ecma)script/i, Et = /^true\/(.*)/, St = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, At = {option: [1, "<select multiple='multiple'>", "</select>"], legend: [1, "<fieldset>", "</fieldset>"], area: [1, "<map>", "</map>"], param: [1, "<object>", "</object>"], thead: [1, "<table>", "</table>"], tr: [2, "<table><tbody>", "</tbody></table>"], col: [2, "<table><tbody></tbody><colgroup>", "</colgroup></table>"], td: [3, "<table><tbody><tr>", "</tr></tbody></table>"], _default: x.support.htmlSerialize ? [0, "", ""] : [1, "X<div>", "</div>"]}, jt = dt(a), Dt = jt.appendChild(a.createElement("div")); At.optgroup = At.option, At.tbody = At.tfoot = At.colgroup = At.caption = At.thead, At.th = At.td, x.fn.extend({text: function (e) { return x.access(this, function (e) { return e === t ? x.text(this) : this.empty().append((this[0] && this[0].ownerDocument || a).createTextNode(e)) }, null, e, arguments.length) }, append: function () { return this.domManip(arguments, function (e) { if (1 === this.nodeType || 11 === this.nodeType || 9 === this.nodeType) { var t = Lt(this, e); t.appendChild(e) } }) }, prepend: function () { return this.domManip(arguments, function (e) { if (1 === this.nodeType || 11 === this.nodeType || 9 === this.nodeType) { var t = Lt(this, e); t.insertBefore(e, t.firstChild) } }) }, before: function () { return this.domManip(arguments, function (e) { this.parentNode && this.parentNode.insertBefore(e, this) }) }, after: function () { return this.domManip(arguments, function (e) { this.parentNode && this.parentNode.insertBefore(e, this.nextSibling) }) }, remove: function (e, t) { var n, r = e ? x.filter(e, this) : this, i = 0; for (; null != (n = r[i]); i++)t || 1 !== n.nodeType || x.cleanData(Ft(n)), n.parentNode && (t && x.contains(n.ownerDocument, n) && _t(Ft(n, "script")), n.parentNode.removeChild(n)); return this }, empty: function () { var e, t = 0; for (; null != (e = this[t]); t++) { 1 === e.nodeType && x.cleanData(Ft(e, !1)); while (e.firstChild)e.removeChild(e.firstChild); e.options && x.nodeName(e, "select") && (e.options.length = 0) } return this }, clone: function (e, t) { return e = null == e ? !1 : e, t = null == t ? e : t, this.map(function () { return x.clone(this, e, t) }) }, html: function (e) { return x.access(this, function (e) { var n = this[0] || {}, r = 0, i = this.length; if (e === t)return 1 === n.nodeType ? n.innerHTML.replace(gt, "") : t; if (!("string" != typeof e || Tt.test(e) || !x.support.htmlSerialize && mt.test(e) || !x.support.leadingWhitespace && yt.test(e) || At[(bt.exec(e) || ["", ""])[1].toLowerCase()])) { e = e.replace(vt, "<$1></$2>"); try { for (; i > r; r++)n = this[r] || {}, 1 === n.nodeType && (x.cleanData(Ft(n, !1)), n.innerHTML = e); n = 0 } catch (o) { } } n && this.empty().append(e) }, null, e, arguments.length) }, replaceWith: function () { var e = x.map(this, function (e) { return[e.nextSibling, e.parentNode] }), t = 0; return this.domManip(arguments, function (n) { var r = e[t++], i = e[t++]; i && (r && r.parentNode !== i && (r = this.nextSibling), x(this).remove(), i.insertBefore(n, r)) }, !0), t ? this : this.remove() }, detach: function (e) { return this.remove(e, !0) }, domManip: function (e, t, n) { e = d.apply([], e); var r, i, o, a, s, l, u = 0, c = this.length, p = this, f = c - 1, h = e[0], g = x.isFunction(h); if (g || !(1 >= c || "string" != typeof h || x.support.checkClone) && Nt.test(h))return this.each(function (r) { var i = p.eq(r); g && (e[0] = h.call(this, r, i.html())), i.domManip(e, t, n) }); if (c && (l = x.buildFragment(e, this[0].ownerDocument, !1, !n && this), r = l.firstChild, 1 === l.childNodes.length && (l = r), r)) { for (a = x.map(Ft(l, "script"), Ht), o = a.length; c > u; u++)i = l, u !== f && (i = x.clone(i, !0, !0), o && x.merge(a, Ft(i, "script"))), t.call(this[u], i, u); if (o)for (s = a[a.length - 1].ownerDocument, x.map(a, qt), u = 0; o > u; u++)i = a[u], kt.test(i.type || "") && !x._data(i, "globalEval") && x.contains(s, i) && (i.src ? x._evalUrl(i.src) : x.globalEval((i.text || i.textContent || i.innerHTML || "").replace(St, ""))); l = r = null } return this }}); function Lt(e, t) { return x.nodeName(e, "table") && x.nodeName(1 === t.nodeType ? t : t.firstChild, "tr") ? e.getElementsByTagName("tbody")[0] || e.appendChild(e.ownerDocument.createElement("tbody")) : e } function Ht(e) { return e.type = (null !== x.find.attr(e, "type")) + "/" + e.type, e } function qt(e) { var t = Et.exec(e.type); return t ? e.type = t[1] : e.removeAttribute("type"), e } function _t(e, t) { var n, r = 0; for (; null != (n = e[r]); r++)x._data(n, "globalEval", !t || x._data(t[r], "globalEval")) } function Mt(e, t) { if (1 === t.nodeType && x.hasData(e)) { var n, r, i, o = x._data(e), a = x._data(t, o), s = o.events; if (s) { delete a.handle, a.events = {}; for (n in s)for (r = 0, i = s[n].length; i > r; r++)x.event.add(t, n, s[n][r]) } a.data && (a.data = x.extend({}, a.data)) } } function Ot(e, t) { var n, r, i; if (1 === t.nodeType) { if (n = t.nodeName.toLowerCase(), !x.support.noCloneEvent && t[x.expando]) { i = x._data(t); for (r in i.events)x.removeEvent(t, r, i.handle); t.removeAttribute(x.expando) } "script" === n && t.text !== e.text ? (Ht(t).text = e.text, qt(t)) : "object" === n ? (t.parentNode && (t.outerHTML = e.outerHTML), x.support.html5Clone && e.innerHTML && !x.trim(t.innerHTML) && (t.innerHTML = e.innerHTML)) : "input" === n && Ct.test(e.type) ? (t.defaultChecked = t.checked = e.checked, t.value !== e.value && (t.value = e.value)) : "option" === n ? t.defaultSelected = t.selected = e.defaultSelected : ("input" === n || "textarea" === n) && (t.defaultValue = e.defaultValue) } } x.each({appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith"}, function (e, t) { x.fn[e] = function (e) { var n, r = 0, i = [], o = x(e), a = o.length - 1; for (; a >= r; r++)n = r === a ? this : this.clone(!0), x(o[r])[t](n), h.apply(i, n.get()); return this.pushStack(i) } }); function Ft(e, n) { var r, o, a = 0, s = typeof e.getElementsByTagName !== i ? e.getElementsByTagName(n || "*") : typeof e.querySelectorAll !== i ? e.querySelectorAll(n || "*") : t; if (!s)for (s = [], r = e.childNodes || e; null != (o = r[a]); a++)!n || x.nodeName(o, n) ? s.push(o) : x.merge(s, Ft(o, n)); return n === t || n && x.nodeName(e, n) ? x.merge([e], s) : s } function Bt(e) { Ct.test(e.type) && (e.defaultChecked = e.checked) } x.extend({clone: function (e, t, n) { var r, i, o, a, s, l = x.contains(e.ownerDocument, e); if (x.support.html5Clone || x.isXMLDoc(e) || !mt.test("<" + e.nodeName + ">") ? o = e.cloneNode(!0) : (Dt.innerHTML = e.outerHTML, Dt.removeChild(o = Dt.firstChild)), !(x.support.noCloneEvent && x.support.noCloneChecked || 1 !== e.nodeType && 11 !== e.nodeType || x.isXMLDoc(e)))for (r = Ft(o), s = Ft(e), a = 0; null != (i = s[a]); ++a)r[a] && Ot(i, r[a]); if (t)if (n)for (s = s || Ft(e), r = r || Ft(o), a = 0; null != (i = s[a]); a++)Mt(i, r[a]); else Mt(e, o); return r = Ft(o, "script"), r.length > 0 && _t(r, !l && Ft(e, "script")), r = s = i = null, o }, buildFragment: function (e, t, n, r) { var i, o, a, s, l, u, c, p = e.length, f = dt(t), d = [], h = 0; for (; p > h; h++)if (o = e[h], o || 0 === o)if ("object" === x.type(o))x.merge(d, o.nodeType ? [o] : o); else if (wt.test(o)) { s = s || f.appendChild(t.createElement("div")), l = (bt.exec(o) || ["", ""])[1].toLowerCase(), c = At[l] || At._default, s.innerHTML = c[1] + o.replace(vt, "<$1></$2>") + c[2], i = c[0]; while (i--)s = s.lastChild; if (!x.support.leadingWhitespace && yt.test(o) && d.push(t.createTextNode(yt.exec(o)[0])), !x.support.tbody) { o = "table" !== l || xt.test(o) ? "<table>" !== c[1] || xt.test(o) ? 0 : s : s.firstChild, i = o && o.childNodes.length; while (i--)x.nodeName(u = o.childNodes[i], "tbody") && !u.childNodes.length && o.removeChild(u) } x.merge(d, s.childNodes), s.textContent = ""; while (s.firstChild)s.removeChild(s.firstChild); s = f.lastChild } else d.push(t.createTextNode(o)); s && f.removeChild(s), x.support.appendChecked || x.grep(Ft(d, "input"), Bt), h = 0; while (o = d[h++])if ((!r || -1 === x.inArray(o, r)) && (a = x.contains(o.ownerDocument, o), s = Ft(f.appendChild(o), "script"), a && _t(s), n)) { i = 0; while (o = s[i++])kt.test(o.type || "") && n.push(o) } return s = null, f }, cleanData: function (e, t) { var n, r, o, a, s = 0, l = x.expando, u = x.cache, c = x.support.deleteExpando, f = x.event.special; for (; null != (n = e[s]); s++)if ((t || x.acceptData(n)) && (o = n[l], a = o && u[o])) { if (a.events)for (r in a.events)f[r] ? x.event.remove(n, r) : x.removeEvent(n, r, a.handle); u[o] && (delete u[o], c ? delete n[l] : typeof n.removeAttribute !== i ? n.removeAttribute(l) : n[l] = null, p.push(o)) } }, _evalUrl: function (e) { return x.ajax({url: e, type: "GET", dataType: "script", async: !1, global: !1, "throws": !0}) }}), x.fn.extend({wrapAll: function (e) { if (x.isFunction(e))return this.each(function (t) { x(this).wrapAll(e.call(this, t)) }); if (this[0]) { var t = x(e, this[0].ownerDocument).eq(0).clone(!0); this[0].parentNode && t.insertBefore(this[0]), t.map(function () { var e = this; while (e.firstChild && 1 === e.firstChild.nodeType)e = e.firstChild; return e }).append(this) } return this }, wrapInner: function (e) { return x.isFunction(e) ? this.each(function (t) { x(this).wrapInner(e.call(this, t)) }) : this.each(function () { var t = x(this), n = t.contents(); n.length ? n.wrapAll(e) : t.append(e) }) }, wrap: function (e) { var t = x.isFunction(e); return this.each(function (n) { x(this).wrapAll(t ? e.call(this, n) : e) }) }, unwrap: function () { return this.parent().each(function () { x.nodeName(this, "body") || x(this).replaceWith(this.childNodes) }).end() }}); var Pt, Rt, Wt, $t = /alpha\([^)]*\)/i, It = /opacity\s*=\s*([^)]*)/, zt = /^(top|right|bottom|left)$/, Xt = /^(none|table(?!-c[ea]).+)/, Ut = /^margin/, Vt = RegExp("^(" + w + ")(.*)$", "i"), Yt = RegExp("^(" + w + ")(?!px)[a-z%]+$", "i"), Jt = RegExp("^([+-])=(" + w + ")", "i"), Gt = {BODY: "block"}, Qt = {position: "absolute", visibility: "hidden", display: "block"}, Kt = {letterSpacing: 0, fontWeight: 400}, Zt = ["Top", "Right", "Bottom", "Left"], en = ["Webkit", "O", "Moz", "ms"]; function tn(e, t) { if (t in e)return t; var n = t.charAt(0).toUpperCase() + t.slice(1), r = t, i = en.length; while (i--)if (t = en[i] + n, t in e)return t; return r } function nn(e, t) { return e = t || e, "none" === x.css(e, "display") || !x.contains(e.ownerDocument, e) } function rn(e, t) { var n, r, i, o = [], a = 0, s = e.length; for (; s > a; a++)r = e[a], r.style && (o[a] = x._data(r, "olddisplay"), n = r.style.display, t ? (o[a] || "none" !== n || (r.style.display = ""), "" === r.style.display && nn(r) && (o[a] = x._data(r, "olddisplay", ln(r.nodeName)))) : o[a] || (i = nn(r), (n && "none" !== n || !i) && x._data(r, "olddisplay", i ? n : x.css(r, "display")))); for (a = 0; s > a; a++)r = e[a], r.style && (t && "none" !== r.style.display && "" !== r.style.display || (r.style.display = t ? o[a] || "" : "none")); return e } x.fn.extend({css: function (e, n) { return x.access(this, function (e, n, r) { var i, o, a = {}, s = 0; if (x.isArray(n)) { for (o = Rt(e), i = n.length; i > s; s++)a[n[s]] = x.css(e, n[s], !1, o); return a } return r !== t ? x.style(e, n, r) : x.css(e, n) }, e, n, arguments.length > 1) }, show: function () { return rn(this, !0) }, hide: function () { return rn(this) }, toggle: function (e) { return"boolean" == typeof e ? e ? this.show() : this.hide() : this.each(function () { nn(this) ? x(this).show() : x(this).hide() }) }}), x.extend({cssHooks: {opacity: {get: function (e, t) { if (t) { var n = Wt(e, "opacity"); return"" === n ? "1" : n } }}}, cssNumber: {columnCount: !0, fillOpacity: !0, fontWeight: !0, lineHeight: !0, opacity: !0, order: !0, orphans: !0, widows: !0, zIndex: !0, zoom: !0}, cssProps: {"float": x.support.cssFloat ? "cssFloat" : "styleFloat"}, style: function (e, n, r, i) { if (e && 3 !== e.nodeType && 8 !== e.nodeType && e.style) { var o, a, s, l = x.camelCase(n), u = e.style; if (n = x.cssProps[l] || (x.cssProps[l] = tn(u, l)), s = x.cssHooks[n] || x.cssHooks[l], r === t)return s && "get"in s && (o = s.get(e, !1, i)) !== t ? o : u[n]; if (a = typeof r, "string" === a && (o = Jt.exec(r)) && (r = (o[1] + 1) * o[2] + parseFloat(x.css(e, n)), a = "number"), !(null == r || "number" === a && isNaN(r) || ("number" !== a || x.cssNumber[l] || (r += "px"), x.support.clearCloneStyle || "" !== r || 0 !== n.indexOf("background") || (u[n] = "inherit"), s && "set"in s && (r = s.set(e, r, i)) === t)))try { u[n] = r } catch (c) { } } }, css: function (e, n, r, i) { var o, a, s, l = x.camelCase(n); return n = x.cssProps[l] || (x.cssProps[l] = tn(e.style, l)), s = x.cssHooks[n] || x.cssHooks[l], s && "get"in s && (a = s.get(e, !0, r)), a === t && (a = Wt(e, n, i)), "normal" === a && n in Kt && (a = Kt[n]), "" === r || r ? (o = parseFloat(a), r === !0 || x.isNumeric(o) ? o || 0 : a) : a }}), e.getComputedStyle ? (Rt = function (t) { return e.getComputedStyle(t, null) }, Wt = function (e, n, r) { var i, o, a, s = r || Rt(e), l = s ? s.getPropertyValue(n) || s[n] : t, u = e.style; return s && ("" !== l || x.contains(e.ownerDocument, e) || (l = x.style(e, n)), Yt.test(l) && Ut.test(n) && (i = u.width, o = u.minWidth, a = u.maxWidth, u.minWidth = u.maxWidth = u.width = l, l = s.width, u.width = i, u.minWidth = o, u.maxWidth = a)), l }) : a.documentElement.currentStyle && (Rt = function (e) { return e.currentStyle }, Wt = function (e, n, r) { var i, o, a, s = r || Rt(e), l = s ? s[n] : t, u = e.style; return null == l && u && u[n] && (l = u[n]), Yt.test(l) && !zt.test(n) && (i = u.left, o = e.runtimeStyle, a = o && o.left, a && (o.left = e.currentStyle.left), u.left = "fontSize" === n ? "1em" : l, l = u.pixelLeft + "px", u.left = i, a && (o.left = a)), "" === l ? "auto" : l }); function on(e, t, n) { var r = Vt.exec(t); return r ? Math.max(0, r[1] - (n || 0)) + (r[2] || "px") : t } function an(e, t, n, r, i) { var o = n === (r ? "border" : "content") ? 4 : "width" === t ? 1 : 0, a = 0; for (; 4 > o; o += 2)"margin" === n && (a += x.css(e, n + Zt[o], !0, i)), r ? ("content" === n && (a -= x.css(e, "padding" + Zt[o], !0, i)), "margin" !== n && (a -= x.css(e, "border" + Zt[o] + "Width", !0, i))) : (a += x.css(e, "padding" + Zt[o], !0, i), "padding" !== n && (a += x.css(e, "border" + Zt[o] + "Width", !0, i))); return a } function sn(e, t, n) { var r = !0, i = "width" === t ? e.offsetWidth : e.offsetHeight, o = Rt(e), a = x.support.boxSizing && "border-box" === x.css(e, "boxSizing", !1, o); if (0 >= i || null == i) { if (i = Wt(e, t, o), (0 > i || null == i) && (i = e.style[t]), Yt.test(i))return i; r = a && (x.support.boxSizingReliable || i === e.style[t]), i = parseFloat(i) || 0 } return i + an(e, t, n || (a ? "border" : "content"), r, o) + "px" } function ln(e) { var t = a, n = Gt[e]; return n || (n = un(e, t), "none" !== n && n || (Pt = (Pt || x("<iframe frameborder='0' width='0' height='0'/>").css("cssText", "display:block !important")).appendTo(t.documentElement), t = (Pt[0].contentWindow || Pt[0].contentDocument).document, t.write("<!doctype html><html><body>"), t.close(), n = un(e, t), Pt.detach()), Gt[e] = n), n } function un(e, t) { var n = x(t.createElement(e)).appendTo(t.body), r = x.css(n[0], "display"); return n.remove(), r } x.each(["height", "width"], function (e, n) { x.cssHooks[n] = {get: function (e, r, i) { return r ? 0 === e.offsetWidth && Xt.test(x.css(e, "display")) ? x.swap(e, Qt, function () { return sn(e, n, i) }) : sn(e, n, i) : t }, set: function (e, t, r) { var i = r && Rt(e); return on(e, t, r ? an(e, n, r, x.support.boxSizing && "border-box" === x.css(e, "boxSizing", !1, i), i) : 0) }} }), x.support.opacity || (x.cssHooks.opacity = {get: function (e, t) { return It.test((t && e.currentStyle ? e.currentStyle.filter : e.style.filter) || "") ? .01 * parseFloat(RegExp.$1) + "" : t ? "1" : "" }, set: function (e, t) { var n = e.style, r = e.currentStyle, i = x.isNumeric(t) ? "alpha(opacity=" + 100 * t + ")" : "", o = r && r.filter || n.filter || ""; n.zoom = 1, (t >= 1 || "" === t) && "" === x.trim(o.replace($t, "")) && n.removeAttribute && (n.removeAttribute("filter"), "" === t || r && !r.filter) || (n.filter = $t.test(o) ? o.replace($t, i) : o + " " + i) }}), x(function () { x.support.reliableMarginRight || (x.cssHooks.marginRight = {get: function (e, n) { return n ? x.swap(e, {display: "inline-block"}, Wt, [e, "marginRight"]) : t }}), !x.support.pixelPosition && x.fn.position && x.each(["top", "left"], function (e, n) { x.cssHooks[n] = {get: function (e, r) { return r ? (r = Wt(e, n), Yt.test(r) ? x(e).position()[n] + "px" : r) : t }} }) }), x.expr && x.expr.filters && (x.expr.filters.hidden = function (e) { return 0 >= e.offsetWidth && 0 >= e.offsetHeight || !x.support.reliableHiddenOffsets && "none" === (e.style && e.style.display || x.css(e, "display")) }, x.expr.filters.visible = function (e) { return!x.expr.filters.hidden(e) }), x.each({margin: "", padding: "", border: "Width"}, function (e, t) { x.cssHooks[e + t] = {expand: function (n) { var r = 0, i = {}, o = "string" == typeof n ? n.split(" ") : [n]; for (; 4 > r; r++)i[e + Zt[r] + t] = o[r] || o[r - 2] || o[0]; return i }}, Ut.test(e) || (x.cssHooks[e + t].set = on) }); var cn = /%20/g, pn = /\[\]$/, fn = /\r?\n/g, dn = /^(?:submit|button|image|reset|file)$/i, hn = /^(?:input|select|textarea|keygen)/i; x.fn.extend({serialize: function () { return x.param(this.serializeArray()) }, serializeArray: function () { return this.map(function () { var e = x.prop(this, "elements"); return e ? x.makeArray(e) : this }).filter(function () { var e = this.type; return this.name && !x(this).is(":disabled") && hn.test(this.nodeName) && !dn.test(e) && (this.checked || !Ct.test(e)) }).map(function (e, t) { var n = x(this).val(); return null == n ? null : x.isArray(n) ? x.map(n, function (e) { return{name: t.name, value: e.replace(fn, "\r\n")} }) : {name: t.name, value: n.replace(fn, "\r\n")} }).get() }}), x.param = function (e, n) { var r, i = [], o = function (e, t) { t = x.isFunction(t) ? t() : null == t ? "" : t, i[i.length] = encodeURIComponent(e) + "=" + encodeURIComponent(t) }; if (n === t && (n = x.ajaxSettings && x.ajaxSettings.traditional), x.isArray(e) || e.jquery && !x.isPlainObject(e))x.each(e, function () { o(this.name, this.value) }); else for (r in e)gn(r, e[r], n, o); return i.join("&").replace(cn, "+") }; function gn(e, t, n, r) { var i; if (x.isArray(t))x.each(t, function (t, i) { n || pn.test(e) ? r(e, i) : gn(e + "[" + ("object" == typeof i ? t : "") + "]", i, n, r) }); else if (n || "object" !== x.type(t))r(e, t); else for (i in t)gn(e + "[" + i + "]", t[i], n, r) } x.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "), function (e, t) { x.fn[t] = function (e, n) { return arguments.length > 0 ? this.on(t, null, e, n) : this.trigger(t) } }), x.fn.extend({hover: function (e, t) { return this.mouseenter(e).mouseleave(t || e) }, bind: function (e, t, n) { return this.on(e, null, t, n) }, unbind: function (e, t) { return this.off(e, null, t) }, delegate: function (e, t, n, r) { return this.on(t, e, n, r) }, undelegate: function (e, t, n) { return 1 === arguments.length ? this.off(e, "**") : this.off(t, e || "**", n) }}); var mn, yn, vn = x.now(), bn = /\?/, xn = /#.*$/, wn = /([?&])_=[^&]*/, Tn = /^(.*?):[ \t]*([^\r\n]*)\r?$/gm, Cn = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, Nn = /^(?:GET|HEAD)$/, kn = /^\/\//, En = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, Sn = x.fn.load, An = {}, jn = {}, Dn = "*/".concat("*"); try { yn = o.href } catch (Ln) { yn = a.createElement("a"), yn.href = "", yn = yn.href } mn = En.exec(yn.toLowerCase()) || []; function Hn(e) { return function (t, n) { "string" != typeof t && (n = t, t = "*"); var r, i = 0, o = t.toLowerCase().match(T) || []; if (x.isFunction(n))while (r = o[i++])"+" === r[0] ? (r = r.slice(1) || "*", (e[r] = e[r] || []).unshift(n)) : (e[r] = e[r] || []).push(n) } } function qn(e, n, r, i) { var o = {}, a = e === jn; function s(l) { var u; return o[l] = !0, x.each(e[l] || [], function (e, l) { var c = l(n, r, i); return"string" != typeof c || a || o[c] ? a ? !(u = c) : t : (n.dataTypes.unshift(c), s(c), !1) }), u } return s(n.dataTypes[0]) || !o["*"] && s("*") } function _n(e, n) { var r, i, o = x.ajaxSettings.flatOptions || {}; for (i in n)n[i] !== t && ((o[i] ? e : r || (r = {}))[i] = n[i]); return r && x.extend(!0, e, r), e } x.fn.load = function (e, n, r) { if ("string" != typeof e && Sn)return Sn.apply(this, arguments); var i, o, a, s = this, l = e.indexOf(" "); return l >= 0 && (i = e.slice(l, e.length), e = e.slice(0, l)), x.isFunction(n) ? (r = n, n = t) : n && "object" == typeof n && (a = "POST"), s.length > 0 && x.ajax({url: e, type: a, dataType: "html", data: n}).done(function (e) { o = arguments, s.html(i ? x("<div>").append(x.parseHTML(e)).find(i) : e) }).complete(r && function (e, t) { s.each(r, o || [e.responseText, t, e]) }), this }, x.each(["ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend"], function (e, t) { x.fn[t] = function (e) { return this.on(t, e) } }), x.extend({active: 0, lastModified: {}, etag: {}, ajaxSettings: {url: yn, type: "GET", isLocal: Cn.test(mn[1]), global: !0, processData: !0, async: !0, contentType: "application/x-www-form-urlencoded; charset=UTF-8", accepts: {"*": Dn, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript"}, contents: {xml: /xml/, html: /html/, json: /json/}, responseFields: {xml: "responseXML", text: "responseText", json: "responseJSON"}, converters: {"* text": String, "text html": !0, "text json": x.parseJSON, "text xml": x.parseXML}, flatOptions: {url: !0, context: !0}}, ajaxSetup: function (e, t) { return t ? _n(_n(e, x.ajaxSettings), t) : _n(x.ajaxSettings, e) }, ajaxPrefilter: Hn(An), ajaxTransport: Hn(jn), ajax: function (e, n) { "object" == typeof e && (n = e, e = t), n = n || {}; var r, i, o, a, s, l, u, c, p = x.ajaxSetup({}, n), f = p.context || p, d = p.context && (f.nodeType || f.jquery) ? x(f) : x.event, h = x.Deferred(), g = x.Callbacks("once memory"), m = p.statusCode || {}, y = {}, v = {}, b = 0, w = "canceled", C = {readyState: 0, getResponseHeader: function (e) { var t; if (2 === b) { if (!c) { c = {}; while (t = Tn.exec(a))c[t[1].toLowerCase()] = t[2] } t = c[e.toLowerCase()] } return null == t ? null : t }, getAllResponseHeaders: function () { return 2 === b ? a : null }, setRequestHeader: function (e, t) { var n = e.toLowerCase(); return b || (e = v[n] = v[n] || e, y[e] = t), this }, overrideMimeType: function (e) { return b || (p.mimeType = e), this }, statusCode: function (e) { var t; if (e)if (2 > b)for (t in e)m[t] = [m[t], e[t]]; else C.always(e[C.status]); return this }, abort: function (e) { var t = e || w; return u && u.abort(t), k(0, t), this }}; if (h.promise(C).complete = g.add, C.success = C.done, C.error = C.fail, p.url = ((e || p.url || yn) + "").replace(xn, "").replace(kn, mn[1] + "//"), p.type = n.method || n.type || p.method || p.type, p.dataTypes = x.trim(p.dataType || "*").toLowerCase().match(T) || [""], null == p.crossDomain && (r = En.exec(p.url.toLowerCase()), p.crossDomain = !(!r || r[1] === mn[1] && r[2] === mn[2] && (r[3] || ("http:" === r[1] ? "80" : "443")) === (mn[3] || ("http:" === mn[1] ? "80" : "443")))), p.data && p.processData && "string" != typeof p.data && (p.data = x.param(p.data, p.traditional)), qn(An, p, n, C), 2 === b)return C; l = p.global, l && 0 === x.active++ && x.event.trigger("ajaxStart"), p.type = p.type.toUpperCase(), p.hasContent = !Nn.test(p.type), o = p.url, p.hasContent || (p.data && (o = p.url += (bn.test(o) ? "&" : "?") + p.data, delete p.data), p.cache === !1 && (p.url = wn.test(o) ? o.replace(wn, "$1_=" + vn++) : o + (bn.test(o) ? "&" : "?") + "_=" + vn++)), p.ifModified && (x.lastModified[o] && C.setRequestHeader("If-Modified-Since", x.lastModified[o]), x.etag[o] && C.setRequestHeader("If-None-Match", x.etag[o])), (p.data && p.hasContent && p.contentType !== !1 || n.contentType) && C.setRequestHeader("Content-Type", p.contentType), C.setRequestHeader("Accept", p.dataTypes[0] && p.accepts[p.dataTypes[0]] ? p.accepts[p.dataTypes[0]] + ("*" !== p.dataTypes[0] ? ", " + Dn + "; q=0.01" : "") : p.accepts["*"]); for (i in p.headers)C.setRequestHeader(i, p.headers[i]); if (p.beforeSend && (p.beforeSend.call(f, C, p) === !1 || 2 === b))return C.abort(); w = "abort"; for (i in{success: 1, error: 1, complete: 1})C[i](p[i]); if (u = qn(jn, p, n, C)) { C.readyState = 1, l && d.trigger("ajaxSend", [C, p]), p.async && p.timeout > 0 && (s = setTimeout(function () { C.abort("timeout") }, p.timeout)); try { b = 1, u.send(y, k) } catch (N) { if (!(2 > b))throw N; k(-1, N) } } else k(-1, "No Transport"); function k(e, n, r, i) { var c, y, v, w, T, N = n; 2 !== b && (b = 2, s && clearTimeout(s), u = t, a = i || "", C.readyState = e > 0 ? 4 : 0, c = e >= 200 && 300 > e || 304 === e, r && (w = Mn(p, C, r)), w = On(p, w, C, c), c ? (p.ifModified && (T = C.getResponseHeader("Last-Modified"), T && (x.lastModified[o] = T), T = C.getResponseHeader("etag"), T && (x.etag[o] = T)), 204 === e || "HEAD" === p.type ? N = "nocontent" : 304 === e ? N = "notmodified" : (N = w.state, y = w.data, v = w.error, c = !v)) : (v = N, (e || !N) && (N = "error", 0 > e && (e = 0))), C.status = e, C.statusText = (n || N) + "", c ? h.resolveWith(f, [y, N, C]) : h.rejectWith(f, [C, N, v]), C.statusCode(m), m = t, l && d.trigger(c ? "ajaxSuccess" : "ajaxError", [C, p, c ? y : v]), g.fireWith(f, [C, N]), l && (d.trigger("ajaxComplete", [C, p]), --x.active || x.event.trigger("ajaxStop"))) } return C }, getJSON: function (e, t, n) { return x.get(e, t, n, "json") }, getScript: function (e, n) { return x.get(e, t, n, "script") }}), x.each(["get", "post"], function (e, n) { x[n] = function (e, r, i, o) { return x.isFunction(r) && (o = o || i, i = r, r = t), x.ajax({url: e, type: n, dataType: o, data: r, success: i}) } }); function Mn(e, n, r) { var i, o, a, s, l = e.contents, u = e.dataTypes; while ("*" === u[0])u.shift(), o === t && (o = e.mimeType || n.getResponseHeader("Content-Type")); if (o)for (s in l)if (l[s] && l[s].test(o)) { u.unshift(s); break } if (u[0]in r)a = u[0]; else { for (s in r) { if (!u[0] || e.converters[s + " " + u[0]]) { a = s; break } i || (i = s) } a = a || i } return a ? (a !== u[0] && u.unshift(a), r[a]) : t } function On(e, t, n, r) { var i, o, a, s, l, u = {}, c = e.dataTypes.slice(); if (c[1])for (a in e.converters)u[a.toLowerCase()] = e.converters[a]; o = c.shift(); while (o)if (e.responseFields[o] && (n[e.responseFields[o]] = t), !l && r && e.dataFilter && (t = e.dataFilter(t, e.dataType)), l = o, o = c.shift())if ("*" === o)o = l; else if ("*" !== l && l !== o) { if (a = u[l + " " + o] || u["* " + o], !a)for (i in u)if (s = i.split(" "), s[1] === o && (a = u[l + " " + s[0]] || u["* " + s[0]])) { a === !0 ? a = u[i] : u[i] !== !0 && (o = s[0], c.unshift(s[1])); break } if (a !== !0)if (a && e["throws"])t = a(t); else try { t = a(t) } catch (p) { return{state: "parsererror", error: a ? p : "No conversion from " + l + " to " + o} } } return{state: "success", data: t} } x.ajaxSetup({accepts: {script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"}, contents: {script: /(?:java|ecma)script/}, converters: {"text script": function (e) { return x.globalEval(e), e }}}), x.ajaxPrefilter("script", function (e) { e.cache === t && (e.cache = !1), e.crossDomain && (e.type = "GET", e.global = !1) }), x.ajaxTransport("script", function (e) { if (e.crossDomain) { var n, r = a.head || x("head")[0] || a.documentElement; return{send: function (t, i) { n = a.createElement("script"), n.async = !0, e.scriptCharset && (n.charset = e.scriptCharset), n.src = e.url, n.onload = n.onreadystatechange = function (e, t) { (t || !n.readyState || /loaded|complete/.test(n.readyState)) && (n.onload = n.onreadystatechange = null, n.parentNode && n.parentNode.removeChild(n), n = null, t || i(200, "success")) }, r.insertBefore(n, r.firstChild) }, abort: function () { n && n.onload(t, !0) }} } }); var Fn = [], Bn = /(=)\?(?=&|$)|\?\?/; x.ajaxSetup({jsonp: "callback", jsonpCallback: function () { var e = Fn.pop() || x.expando + "_" + vn++; return this[e] = !0, e }}), x.ajaxPrefilter("json jsonp", function (n, r, i) { var o, a, s, l = n.jsonp !== !1 && (Bn.test(n.url) ? "url" : "string" == typeof n.data && !(n.contentType || "").indexOf("application/x-www-form-urlencoded") && Bn.test(n.data) && "data"); return l || "jsonp" === n.dataTypes[0] ? (o = n.jsonpCallback = x.isFunction(n.jsonpCallback) ? n.jsonpCallback() : n.jsonpCallback, l ? n[l] = n[l].replace(Bn, "$1" + o) : n.jsonp !== !1 && (n.url += (bn.test(n.url) ? "&" : "?") + n.jsonp + "=" + o), n.converters["script json"] = function () { return s || x.error(o + " was not called"), s[0] }, n.dataTypes[0] = "json", a = e[o], e[o] = function () { s = arguments }, i.always(function () { e[o] = a, n[o] && (n.jsonpCallback = r.jsonpCallback, Fn.push(o)), s && x.isFunction(a) && a(s[0]), s = a = t }), "script") : t }); var Pn, Rn, Wn = 0, $n = e.ActiveXObject && function () { var e; for (e in Pn)Pn[e](t, !0) }; function In() { try { return new e.XMLHttpRequest } catch (t) { } } function zn() { try { return new e.ActiveXObject("Microsoft.XMLHTTP") } catch (t) { } } x.ajaxSettings.xhr = e.ActiveXObject ? function () { return!this.isLocal && In() || zn() } : In, Rn = x.ajaxSettings.xhr(), x.support.cors = !!Rn && "withCredentials"in Rn, Rn = x.support.ajax = !!Rn, Rn && x.ajaxTransport(function (n) { if (!n.crossDomain || x.support.cors) { var r; return{send: function (i, o) { var a, s, l = n.xhr(); if (n.username ? l.open(n.type, n.url, n.async, n.username, n.password) : l.open(n.type, n.url, n.async), n.xhrFields)for (s in n.xhrFields)l[s] = n.xhrFields[s]; n.mimeType && l.overrideMimeType && l.overrideMimeType(n.mimeType), n.crossDomain || i["X-Requested-With"] || (i["X-Requested-With"] = "XMLHttpRequest"); try { for (s in i)l.setRequestHeader(s, i[s]) } catch (u) { } l.send(n.hasContent && n.data || null), r = function (e, i) { var s, u, c, p; try { if (r && (i || 4 === l.readyState))if (r = t, a && (l.onreadystatechange = x.noop, $n && delete Pn[a]), i)4 !== l.readyState && l.abort(); else { p = {}, s = l.status, u = l.getAllResponseHeaders(), "string" == typeof l.responseText && (p.text = l.responseText); try { c = l.statusText } catch (f) { c = "" } s || !n.isLocal || n.crossDomain ? 1223 === s && (s = 204) : s = p.text ? 200 : 404 } } catch (d) { i || o(-1, d) } p && o(s, c, p, u) }, n.async ? 4 === l.readyState ? setTimeout(r) : (a = ++Wn, $n && (Pn || (Pn = {}, x(e).unload($n)), Pn[a] = r), l.onreadystatechange = r) : r() }, abort: function () { r && r(t, !0) }} } }); var Xn, Un, Vn = /^(?:toggle|show|hide)$/, Yn = RegExp("^(?:([+-])=|)(" + w + ")([a-z%]*)$", "i"), Jn = /queueHooks$/, Gn = [nr], Qn = {"*": [function (e, t) { var n = this.createTween(e, t), r = n.cur(), i = Yn.exec(t), o = i && i[3] || (x.cssNumber[e] ? "" : "px"), a = (x.cssNumber[e] || "px" !== o && +r) && Yn.exec(x.css(n.elem, e)), s = 1, l = 20; if (a && a[3] !== o) { o = o || a[3], i = i || [], a = +r || 1; do s = s || ".5", a /= s, x.style(n.elem, e, a + o); while (s !== (s = n.cur() / r) && 1 !== s && --l) } return i && (a = n.start = +a || +r || 0, n.unit = o, n.end = i[1] ? a + (i[1] + 1) * i[2] : +i[2]), n }]}; function Kn() { return setTimeout(function () { Xn = t }), Xn = x.now() } function Zn(e, t, n) { var r, i = (Qn[t] || []).concat(Qn["*"]), o = 0, a = i.length; for (; a > o; o++)if (r = i[o].call(n, t, e))return r } function er(e, t, n) { var r, i, o = 0, a = Gn.length, s = x.Deferred().always(function () { delete l.elem }), l = function () { if (i)return!1; var t = Xn || Kn(), n = Math.max(0, u.startTime + u.duration - t), r = n / u.duration || 0, o = 1 - r, a = 0, l = u.tweens.length; for (; l > a; a++)u.tweens[a].run(o); return s.notifyWith(e, [u, o, n]), 1 > o && l ? n : (s.resolveWith(e, [u]), !1) }, u = s.promise({elem: e, props: x.extend({}, t), opts: x.extend(!0, {specialEasing: {}}, n), originalProperties: t, originalOptions: n, startTime: Xn || Kn(), duration: n.duration, tweens: [], createTween: function (t, n) { var r = x.Tween(e, u.opts, t, n, u.opts.specialEasing[t] || u.opts.easing); return u.tweens.push(r), r }, stop: function (t) { var n = 0, r = t ? u.tweens.length : 0; if (i)return this; for (i = !0; r > n; n++)u.tweens[n].run(1); return t ? s.resolveWith(e, [u, t]) : s.rejectWith(e, [u, t]), this }}), c = u.props; for (tr(c, u.opts.specialEasing); a > o; o++)if (r = Gn[o].call(u, e, c, u.opts))return r; return x.map(c, Zn, u), x.isFunction(u.opts.start) && u.opts.start.call(e, u), x.fx.timer(x.extend(l, {elem: e, anim: u, queue: u.opts.queue})), u.progress(u.opts.progress).done(u.opts.done, u.opts.complete).fail(u.opts.fail).always(u.opts.always) } function tr(e, t) { var n, r, i, o, a; for (n in e)if (r = x.camelCase(n), i = t[r], o = e[n], x.isArray(o) && (i = o[1], o = e[n] = o[0]), n !== r && (e[r] = o, delete e[n]), a = x.cssHooks[r], a && "expand"in a) { o = a.expand(o), delete e[r]; for (n in o)n in e || (e[n] = o[n], t[n] = i) } else t[r] = i } x.Animation = x.extend(er, {tweener: function (e, t) { x.isFunction(e) ? (t = e, e = ["*"]) : e = e.split(" "); var n, r = 0, i = e.length; for (; i > r; r++)n = e[r], Qn[n] = Qn[n] || [], Qn[n].unshift(t) }, prefilter: function (e, t) { t ? Gn.unshift(e) : Gn.push(e) }}); function nr(e, t, n) { var r, i, o, a, s, l, u = this, c = {}, p = e.style, f = e.nodeType && nn(e), d = x._data(e, "fxshow"); n.queue || (s = x._queueHooks(e, "fx"), null == s.unqueued && (s.unqueued = 0, l = s.empty.fire, s.empty.fire = function () { s.unqueued || l() }), s.unqueued++, u.always(function () { u.always(function () { s.unqueued--, x.queue(e, "fx").length || s.empty.fire() }) })), 1 === e.nodeType && ("height"in t || "width"in t) && (n.overflow = [p.overflow, p.overflowX, p.overflowY], "inline" === x.css(e, "display") && "none" === x.css(e, "float") && (x.support.inlineBlockNeedsLayout && "inline" !== ln(e.nodeName) ? p.zoom = 1 : p.display = "inline-block")), n.overflow && (p.overflow = "hidden", x.support.shrinkWrapBlocks || u.always(function () { p.overflow = n.overflow[0], p.overflowX = n.overflow[1], p.overflowY = n.overflow[2] })); for (r in t)if (i = t[r], Vn.exec(i)) { if (delete t[r], o = o || "toggle" === i, i === (f ? "hide" : "show"))continue; c[r] = d && d[r] || x.style(e, r) } if (!x.isEmptyObject(c)) { d ? "hidden"in d && (f = d.hidden) : d = x._data(e, "fxshow", {}), o && (d.hidden = !f), f ? x(e).show() : u.done(function () { x(e).hide() }), u.done(function () { var t; x._removeData(e, "fxshow"); for (t in c)x.style(e, t, c[t]) }); for (r in c)a = Zn(f ? d[r] : 0, r, u), r in d || (d[r] = a.start, f && (a.end = a.start, a.start = "width" === r || "height" === r ? 1 : 0)) } } function rr(e, t, n, r, i) { return new rr.prototype.init(e, t, n, r, i) } x.Tween = rr, rr.prototype = {constructor: rr, init: function (e, t, n, r, i, o) { this.elem = e, this.prop = n, this.easing = i || "swing", this.options = t, this.start = this.now = this.cur(), this.end = r, this.unit = o || (x.cssNumber[n] ? "" : "px") }, cur: function () { var e = rr.propHooks[this.prop]; return e && e.get ? e.get(this) : rr.propHooks._default.get(this) }, run: function (e) { var t, n = rr.propHooks[this.prop]; return this.pos = t = this.options.duration ? x.easing[this.easing](e, this.options.duration * e, 0, 1, this.options.duration) : e, this.now = (this.end - this.start) * t + this.start, this.options.step && this.options.step.call(this.elem, this.now, this), n && n.set ? n.set(this) : rr.propHooks._default.set(this), this }}, rr.prototype.init.prototype = rr.prototype, rr.propHooks = {_default: {get: function (e) { var t; return null == e.elem[e.prop] || e.elem.style && null != e.elem.style[e.prop] ? (t = x.css(e.elem, e.prop, ""), t && "auto" !== t ? t : 0) : e.elem[e.prop] }, set: function (e) { x.fx.step[e.prop] ? x.fx.step[e.prop](e) : e.elem.style && (null != e.elem.style[x.cssProps[e.prop]] || x.cssHooks[e.prop]) ? x.style(e.elem, e.prop, e.now + e.unit) : e.elem[e.prop] = e.now }}}, rr.propHooks.scrollTop = rr.propHooks.scrollLeft = {set: function (e) { e.elem.nodeType && e.elem.parentNode && (e.elem[e.prop] = e.now) }}, x.each(["toggle", "show", "hide"], function (e, t) { var n = x.fn[t]; x.fn[t] = function (e, r, i) { return null == e || "boolean" == typeof e ? n.apply(this, arguments) : this.animate(ir(t, !0), e, r, i) } }), x.fn.extend({fadeTo: function (e, t, n, r) { return this.filter(nn).css("opacity", 0).show().end().animate({opacity: t}, e, n, r) }, animate: function (e, t, n, r) { var i = x.isEmptyObject(e), o = x.speed(t, n, r), a = function () { var t = er(this, x.extend({}, e), o); (i || x._data(this, "finish")) && t.stop(!0) }; return a.finish = a, i || o.queue === !1 ? this.each(a) : this.queue(o.queue, a) }, stop: function (e, n, r) { var i = function (e) { var t = e.stop; delete e.stop, t(r) }; return"string" != typeof e && (r = n, n = e, e = t), n && e !== !1 && this.queue(e || "fx", []), this.each(function () { var t = !0, n = null != e && e + "queueHooks", o = x.timers, a = x._data(this); if (n)a[n] && a[n].stop && i(a[n]); else for (n in a)a[n] && a[n].stop && Jn.test(n) && i(a[n]); for (n = o.length; n--;)o[n].elem !== this || null != e && o[n].queue !== e || (o[n].anim.stop(r), t = !1, o.splice(n, 1)); (t || !r) && x.dequeue(this, e) }) }, finish: function (e) { return e !== !1 && (e = e || "fx"), this.each(function () { var t, n = x._data(this), r = n[e + "queue"], i = n[e + "queueHooks"], o = x.timers, a = r ? r.length : 0; for (n.finish = !0, x.queue(this, e, []), i && i.stop && i.stop.call(this, !0), t = o.length; t--;)o[t].elem === this && o[t].queue === e && (o[t].anim.stop(!0), o.splice(t, 1)); for (t = 0; a > t; t++)r[t] && r[t].finish && r[t].finish.call(this); delete n.finish }) }}); function ir(e, t) { var n, r = {height: e}, i = 0; for (t = t ? 1 : 0; 4 > i; i += 2 - t)n = Zt[i], r["margin" + n] = r["padding" + n] = e; return t && (r.opacity = r.width = e), r } x.each({slideDown: ir("show"), slideUp: ir("hide"), slideToggle: ir("toggle"), fadeIn: {opacity: "show"}, fadeOut: {opacity: "hide"}, fadeToggle: {opacity: "toggle"}}, function (e, t) { x.fn[e] = function (e, n, r) { return this.animate(t, e, n, r) } }), x.speed = function (e, t, n) { var r = e && "object" == typeof e ? x.extend({}, e) : {complete: n || !n && t || x.isFunction(e) && e, duration: e, easing: n && t || t && !x.isFunction(t) && t}; return r.duration = x.fx.off ? 0 : "number" == typeof r.duration ? r.duration : r.duration in x.fx.speeds ? x.fx.speeds[r.duration] : x.fx.speeds._default, (null == r.queue || r.queue === !0) && (r.queue = "fx"), r.old = r.complete, r.complete = function () { x.isFunction(r.old) && r.old.call(this), r.queue && x.dequeue(this, r.queue) }, r }, x.easing = {linear: function (e) { return e }, swing: function (e) { return.5 - Math.cos(e * Math.PI) / 2 }}, x.timers = [], x.fx = rr.prototype.init, x.fx.tick = function () { var e, n = x.timers, r = 0; for (Xn = x.now(); n.length > r; r++)e = n[r], e() || n[r] !== e || n.splice(r--, 1); n.length || x.fx.stop(), Xn = t }, x.fx.timer = function (e) { e() && x.timers.push(e) && x.fx.start() }, x.fx.interval = 13, x.fx.start = function () { Un || (Un = setInterval(x.fx.tick, x.fx.interval)) }, x.fx.stop = function () { clearInterval(Un), Un = null }, x.fx.speeds = {slow: 600, fast: 200, _default: 400}, x.fx.step = {}, x.expr && x.expr.filters && (x.expr.filters.animated = function (e) { return x.grep(x.timers, function (t) { return e === t.elem }).length }), x.fn.offset = function (e) { if (arguments.length)return e === t ? this : this.each(function (t) { x.offset.setOffset(this, e, t) }); var n, r, o = {top: 0, left: 0}, a = this[0], s = a && a.ownerDocument; if (s)return n = s.documentElement, x.contains(n, a) ? (typeof a.getBoundingClientRect !== i && (o = a.getBoundingClientRect()), r = or(s), {top: o.top + (r.pageYOffset || n.scrollTop) - (n.clientTop || 0), left: o.left + (r.pageXOffset || n.scrollLeft) - (n.clientLeft || 0)}) : o }, x.offset = {setOffset: function (e, t, n) { var r = x.css(e, "position"); "static" === r && (e.style.position = "relative"); var i = x(e), o = i.offset(), a = x.css(e, "top"), s = x.css(e, "left"), l = ("absolute" === r || "fixed" === r) && x.inArray("auto", [a, s]) > -1, u = {}, c = {}, p, f; l ? (c = i.position(), p = c.top, f = c.left) : (p = parseFloat(a) || 0, f = parseFloat(s) || 0), x.isFunction(t) && (t = t.call(e, n, o)), null != t.top && (u.top = t.top - o.top + p), null != t.left && (u.left = t.left - o.left + f), "using"in t ? t.using.call(e, u) : i.css(u) }}, x.fn.extend({position: function () { if (this[0]) { var e, t, n = {top: 0, left: 0}, r = this[0]; return"fixed" === x.css(r, "position") ? t = r.getBoundingClientRect() : (e = this.offsetParent(), t = this.offset(), x.nodeName(e[0], "html") || (n = e.offset()), n.top += x.css(e[0], "borderTopWidth", !0), n.left += x.css(e[0], "borderLeftWidth", !0)), {top: t.top - n.top - x.css(r, "marginTop", !0), left: t.left - n.left - x.css(r, "marginLeft", !0)} } }, offsetParent: function () { return this.map(function () { var e = this.offsetParent || s; while (e && !x.nodeName(e, "html") && "static" === x.css(e, "position"))e = e.offsetParent; return e || s }) }}), x.each({scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function (e, n) { var r = /Y/.test(n); x.fn[e] = function (i) { return x.access(this, function (e, i, o) { var a = or(e); return o === t ? a ? n in a ? a[n] : a.document.documentElement[i] : e[i] : (a ? a.scrollTo(r ? x(a).scrollLeft() : o, r ? o : x(a).scrollTop()) : e[i] = o, t) }, e, i, arguments.length, null) } }); function or(e) { return x.isWindow(e) ? e : 9 === e.nodeType ? e.defaultView || e.parentWindow : !1 } x.each({Height: "height", Width: "width"}, function (e, n) { x.each({padding: "inner" + e, content: n, "": "outer" + e}, function (r, i) { x.fn[i] = function (i, o) { var a = arguments.length && (r || "boolean" != typeof i), s = r || (i === !0 || o === !0 ? "margin" : "border"); return x.access(this, function (n, r, i) { var o; return x.isWindow(n) ? n.document.documentElement["client" + e] : 9 === n.nodeType ? (o = n.documentElement, Math.max(n.body["scroll" + e], o["scroll" + e], n.body["offset" + e], o["offset" + e], o["client" + e])) : i === t ? x.css(n, r, s) : x.style(n, r, i, s) }, n, a ? i : t, a, null) } }) }), x.fn.size = function () { return this.length }, x.fn.andSelf = x.fn.addBack, "object" == typeof module && module && "object" == typeof module.exports ? module.exports = x : (e.jQuery = e.$ = x, "function" == typeof define && define.amd && define("jquery", [], function () { return x })) })(window);
import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); export const store = new Vuex.Store({ state: { products: [ {id: 1, name: 'Banana Skin', price: 20}, {id: 2, name: 'Shiny Star', price: 40}, {id: 3, name: 'Green Shells', price: 60}, {id: 4, name: 'Red Shells', price: 40} ] }, getters: { saleProducts: state => { var saleProducts = state.products.map( product => { return { id: product.id, name: '**' + product.name + '**', price: product.price/2 } }); return saleProducts; } }, mutations: { //mutations shouldn't be used when trying to do asynchronous tasks, it might be difficult to track. For that is better to use actions reducePrice: (state, payload) => { state.products.forEach( product => { product.price -= payload; }); } }, actions: { reducePrice: (context, payload) => { setTimeout(function() { context.commit('reducePrice', payload); }, 2000); } } });
import React, {Component} from 'react'; import {Link} from 'react-router'; export default class LinkButton extends Component { constructor(props) { super(props); } render() { let queryString = this.props.location.search ? this.props.location.search : ''; let linkClass = this.props.linkClass ? this.props.linkClass : ''; return ( <Link to={this.props.linkRoute + queryString} className={linkClass} onClick={this.props.onClick}> {this.props.children} </Link> ); }; }
function IndexController($scope, $http, $modal) { $scope.newMeeting = function() { $modal.open({ templateUrl: 'newMeetingModal.html', backdrop: true, size: 'lg', controller: function($scope, $modalInstance) { $scope.loading = false; $scope.error = null; $scope.name = ''; $scope.timePerTopic = 4; $scope.timePerTopicAfterVote = 2; $scope.votesPerPerson = 3; $scope.submit = function() { // TODO: Validate numbers if ($scope.name === '') { $scope.error = 'Name must be given!'; return; } $scope.error = ''; $scope.loading = true; var postData = { name: $scope.name, timePerTopic: $scope.timePerTopic, timePerTopicAfterVote: $scope.timePerTopicAfterVote, votesPerPerson: $scope.votesPerPerson }; $http.post('/meeting', postData).success(function(meeting) { $scope.loading = false; window.location.href = '/meeting/' + meeting.id; }).error(function(error) { $scope.loading = false; $scope.error = error; }); }; $scope.cancel = function () { $modalInstance.dismiss(false); }; } }); }; } macchiatoControllers.controller('IndexController', IndexController);
const Dotenv = require("dotenv-webpack"); export default { apollo: { clientConfigs: { default: { httpEndpoint: process.env.GRAPHQL_ENDPOINT } } }, build: { extend(config, { }) { config.plugins.push(new Dotenv({ safe: true })); } }, head: { meta: [ { charset: "utf-8" }, { name: "viewport", content: "width=device-width, initial-scale=1" } ], title: "Tasks" }, modules: [ "@nuxtjs/apollo", "@nuxtjs/vuetify" ] }
/*! * Minimal Mistakes Jekyll Theme 4.21.0 by Michael Rose * Copyright 2013-2020 Michael Rose - mademistakes.com | @mmistakes * Licensed under MIT */ !function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(T,e){"use strict";function m(e){return null!=e&&e===e.window}var t=[],r=Object.getPrototypeOf,s=t.slice,g=t.flat?function(e){return t.flat.call(e)}:function(e){return t.concat.apply([],e)},u=t.push,i=t.indexOf,n={},o=n.toString,v=n.hasOwnProperty,a=v.toString,l=a.call(Object),y={},b=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType},E=T.document,c={type:!0,src:!0,nonce:!0,noModule:!0};function x(e,t,n){var r,i,o=(n=n||E).createElement("script");if(o.text=e,t)for(r in c)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function w(e){return null==e?e+":"object"==typeof e||"function"==typeof e?n[o.call(e)]||"object":typeof e}var f="3.5.1",S=function(e,t){return new S.fn.init(e,t)};function d(e){var t=!!e&&"length"in e&&e.length,n=w(e);return!b(e)&&!m(e)&&("array"===n||0===t||"number"==typeof t&&0<t&&t-1 in e)}S.fn=S.prototype={jquery:f,constructor:S,length:0,toArray:function(){return s.call(this)},get:function(e){return null==e?s.call(this):e<0?this[e+this.length]:this[e]},pushStack:function(e){var t=S.merge(this.constructor(),e);return t.prevObject=this,t},each:function(e){return S.each(this,e)},map:function(n){return this.pushStack(S.map(this,function(e,t){return n.call(e,t,e)}))},slice:function(){return this.pushStack(s.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},even:function(){return this.pushStack(S.grep(this,function(e,t){return(t+1)%2}))},odd:function(){return this.pushStack(S.grep(this,function(e,t){return t%2}))},eq:function(e){var t=this.length,n=+e+(e<0?t:0);return this.pushStack(0<=n&&n<t?[this[n]]:[])},end:function(){return this.prevObject||this.constructor()},push:u,sort:t.sort,splice:t.splice},S.extend=S.fn.extend=function(){var e,t,n,r,i,o,a=arguments[0]||{},s=1,u=arguments.length,l=!1;for("boolean"==typeof a&&(l=a,a=arguments[s]||{},s++),"object"==typeof a||b(a)||(a={}),s===u&&(a=this,s--);s<u;s++)if(null!=(e=arguments[s]))for(t in e)r=e[t],"__proto__"!==t&&a!==r&&(l&&r&&(S.isPlainObject(r)||(i=Array.isArray(r)))?(n=a[t],o=i&&!Array.isArray(n)?[]:i||S.isPlainObject(n)?n:{},i=!1,a[t]=S.extend(l,o,r)):void 0!==r&&(a[t]=r));return a},S.extend({expando:"jQuery"+(f+Math.random()).replace(/\D/g,"),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isPlainObject:function(e){var t,n;return!(!e||"[object Object]"!==o.call(e))&&(!(t=r(e))||"function"==typeof(n=v.call(t,"constructor")&&t.constructor)&&a.call(n)===l)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},globalEval:function(e,t,n){x(e,{nonce:t&&t.nonce},n)},each:function(e,t){var n,r=0;if(d(e))for(n=e.length;r<n&&!1!==t.call(e[r],r,e[r]);r++);else for(r in e)if(!1===t.call(e[r],r,e[r]))break;return e},makeArray:function(e,t){var n=t||[];return null!=e&&(d(Object(e))?S.merge(n,"string"==typeof e?[e]:e):u.call(n,e)),n},inArray:function(e,t,n){return null==t?-1:i.call(t,e,n)},merge:function(e,t){for(var n=+t.length,r=0,i=e.length;r<n;r++)e[i++]=t[r];return e.length=i,e},grep:function(e,t,n){for(var r=[],i=0,o=e.length,a=!n;i<o;i++)!t(e[i],i)!=a&&r.push(e[i]);return r},map:function(e,t,n){var r,i,o=0,a=[];if(d(e))for(r=e.length;o<r;o++)null!=(i=t(e[o],o,n))&&a.push(i);else for(o in e)null!=(i=t(e[o],o,n))&&a.push(i);return g(a)},guid:1,support:y}),"function"==typeof Symbol&&(S.fn[Symbol.iterator]=t[Symbol.iterator]),S.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(e,t){n["[object "+t+"]"]=t.toLowerCase()});var p=function(n){function f(e,t){var n="0x"+e.slice(1)-65536;return t||(n<0?String.fromCharCode(65536+n):String.fromCharCode(n>>10|55296,1023&n|56320))}function i(){C()}var e,p,x,o,a,h,d,m,w,u,l,C,T,s,E,g,c,v,y,S="sizzle"+ +new Date,b=n.document,k=0,r=0,A=ue(),N=ue(),j=ue(),I=ue(),L=function(e,t){return e===t&&(l=!0),0},D={}.hasOwnProperty,t=[],O=t.pop,P=t.push,H=t.push,q=t.slice,M=function(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1},_="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",$="[\\x20\\t\\r\\n\\f]",R="(?:\\\\[\\da-fA-F]{1,6}"+$+"?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+",B="\\["+$+"*("+R+")(?:"+$+"*([*^$|!~]?=)"+$+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+R+"))|)"+$+"*\\]",F=":("+R+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+B+")*)|.*)\\)|)",z=new RegExp($+"+","g"),W=new RegExp("^"+$+"+|((?:^|[^\\\\])(?:\\\\.)*)"+$+"+$","g"),U=new RegExp("^"+$+"*,"+$+"*"),X=new RegExp("^"+$+"*([>+~]|"+$+")"+$+"*"),Q=new RegExp($+"|>"),Y=new RegExp(F),V=new RegExp("^"+R+"$"),G={ID:new RegExp("^#("+R+")"),CLASS:new RegExp("^\\.("+R+")"),TAG:new RegExp("^("+R+"|[*])"),ATTR:new RegExp("^"+B),PSEUDO:new RegExp("^"+F),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+$+"*(even|odd|(([+-]|)(\\d*)n|)"+$+"*(?:([+-]|)"+$+"*(\\d+)|))"+$+"*\\)|)","i"),bool:new RegExp("^(?:"+_+")$","i"),needsContext:new RegExp("^"+$+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+$+"*((?:-\\d)?\\d*)"+$+"*\\)|)(?=[^-]|$)","i")},K=/HTML$/i,Z=/^(?:input|select|textarea|button)$/i,J=/^h\d$/i,ee=/^[^{]+\{\s*\[native \w/,te=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ne=/[+~]/,re=new RegExp("\\\\[\\da-fA-F]{1,6}"+$+"?|\\\\([^\\r\\n\\f])","g"),ie=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,oe=function(e,t){return t?"\0"===e?"'":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},ae=xe(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{H.apply(t=q.call(b.childNodes),b.childNodes),t[b.childNodes.length].nodeType}catch(e){H={apply:t.length?function(e,t){P.apply(e,q.call(t))}:function(e,t){for(var n=e.length,r=0;e[n++]=t[r++];);e.length=n-1}}}function se(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,d=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==d&&9!==d&&11!==d)return n;if(!r&&(C(e),e=e||T,E)){if(11!==d&&(u=te.exec(t)))if(i=u[1]){if(9===d){if(!(a=e.getElementById(i)))return n;if(a.id===i)return n.push(a),n}else if(f&&(a=f.getElementById(i))&&y(e,a)&&a.id===i)return n.push(a),n}else{if(u[2])return H.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&p.getElementsByClassName&&e.getElementsByClassName)return H.apply(n,e.getElementsByClassName(i)),n}if(p.qsa&&!I[t+" "]&&(!g||!g.test(t))&&(1!==d||"object"!==e.nodeName.toLowerCase())){if(c=t,f=e,1===d&&(Q.test(t)||X.test(t))){for((f=ne.test(t)&&ve(e.parentNode)||e)===e&&p.scope||((s=e.getAttribute("id"))?s=s.replace(ie,oe):e.setAttribute("id",s=S)),o=(l=h(t)).length;o--;)l[o]=(s?"#"+s:":scope")+" "+be(l[o]);c=l.join(",")}try{return H.apply(n,f.querySelectorAll(c)),n}catch(e){I(t,!0)}finally{s===S&&e.removeAttribute("id")}}}return m(t.replace(W,"$1"),e,n,r)}function ue(){var r=[];return function e(t,n){return r.push(t+" ")>x.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function le(e){return e[S]=!0,e}function ce(e){var t=T.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){for(var n=e.split("|"),r=n.length;r--;)x.attrHandle[n[r]]=t}function de(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)for(;n=n.nextSibling;)if(n===t)return-1;return e?1:-1}function pe(t){return function(e){return"input"===e.nodeName.toLowerCase()&&e.type===t}}function he(n){return function(e){var t=e.nodeName.toLowerCase();return("input"===t||"button"===t)&&e.type===n}}function me(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&ae(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function ge(a){return le(function(o){return o=+o,le(function(e,t){for(var n,r=a([],e.length,o),i=r.length;i--;)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function ve(e){return e&&void 0!==e.getElementsByTagName&&e}for(e in p=se.support={},a=se.isXML=function(e){var t=e.namespaceURI,n=(e.ownerDocument||e).documentElement;return!K.test(t||n&&n.nodeName||"HTML")},C=se.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:b;return r!=T&&9===r.nodeType&&r.documentElement&&(s=(T=r).documentElement,E=!a(T),b!=T&&(n=T.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",i,!1):n.attachEvent&&n.attachEvent("onunload",i)),p.scope=ce(function(e){return s.appendChild(e).appendChild(T.createElement("div")),void 0!==e.querySelectorAll&&!e.querySelectorAll(":scope fieldset div").length}),p.attributes=ce(function(e){return e.className="i",!e.getAttribute("className")}),p.getElementsByTagName=ce(function(e){return e.appendChild(T.createComment(")),!e.getElementsByTagName("*").length}),p.getElementsByClassName=ee.test(T.getElementsByClassName),p.getById=ce(function(e){return s.appendChild(e).id=S,!T.getElementsByName||!T.getElementsByName(S).length}),p.getById?(x.filter.ID=function(e){var t=e.replace(re,f);return function(e){return e.getAttribute("id")===t}},x.find.ID=function(e,t){if(void 0!==t.getElementById&&E){var n=t.getElementById(e);return n?[n]:[]}}):(x.filter.ID=function(e){var n=e.replace(re,f);return function(e){var t=void 0!==e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},x.find.ID=function(e,t){if(void 0!==t.getElementById&&E){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];for(i=t.getElementsByName(e),r=0;o=i[r++];)if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),x.find.TAG=p.getElementsByTagName?function(e,t){return void 0!==t.getElementsByTagName?t.getElementsByTagName(e):p.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"!==e)return o;for(;n=o[i++];)1===n.nodeType&&r.push(n);return r},x.find.CLASS=p.getElementsByClassName&&function(e,t){if(void 0!==t.getElementsByClassName&&E)return t.getElementsByClassName(e)},c=[],g=[],(p.qsa=ee.test(T.querySelectorAll))&&(ce(function(e){var t;s.appendChild(e).innerHTML="<a id='"+S+"'></a><select id='"+S+"-\r\\' msallowcapture=''><option selected=''></option></select>",e.querySelectorAll("[msallowcapture^='']").length&&g.push("[*^$]="+$+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||g.push("\\["+$+"*(?:value|"+_+")"),e.querySelectorAll("[id~="+S+"-]").length||g.push("~="),(t=T.createElement("input")).setAttribute("name","),e.appendChild(t),e.querySelectorAll("[name='']").length||g.push("\\["+$+"*name"+$+"*="+$+"*(?:''|\"\")"),e.querySelectorAll(":checked").length||g.push(":checked"),e.querySelectorAll("a#"+S+"+*").length||g.push(".#.+[+~]"),e.querySelectorAll("\\\f"),g.push("[\\r\\n\\f]")}),ce(function(e){e.innerHTML="<a href='' disabled='disabled'></a><select disabled='disabled'><option/></select>";var t=T.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&g.push("name"+$+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&g.push(":enabled",":disabled"),s.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&g.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),g.push(",.*:")})),(p.matchesSelector=ee.test(v=s.matches||s.webkitMatchesSelector||s.mozMatchesSelector||s.oMatchesSelector||s.msMatchesSelector))&&ce(function(e){p.disconnectedMatch=v.call(e,"*"),v.call(e,"[s!='']:x"),c.push("!=",F)}),g=g.length&&new RegExp(g.join("|")),c=c.length&&new RegExp(c.join("|")),t=ee.test(s.compareDocumentPosition),y=t||ee.test(s.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)for(;t=t.parentNode;)if(t===e)return!0;return!1},L=t?function(e,t){if(e===t)return l=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)==(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!p.sortDetached&&t.compareDocumentPosition(e)===n?e==T||e.ownerDocument==b&&y(b,e)?-1:t==T||t.ownerDocument==b&&y(b,t)?1:u?M(u,e)-M(u,t):0:4&n?-1:1)}:function(e,t){if(e===t)return l=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e==T?-1:t==T?1:i?-1:o?1:u?M(u,e)-M(u,t):0;if(i===o)return de(e,t);for(n=e;n=n.parentNode;)a.unshift(n);for(n=t;n=n.parentNode;)s.unshift(n);for(;a[r]===s[r];)r++;return r?de(a[r],s[r]):a[r]==b?-1:s[r]==b?1:0}),T},se.matches=function(e,t){return se(e,null,null,t)},se.matchesSelector=function(e,t){if(C(e),p.matchesSelector&&E&&!I[t+" "]&&(!c||!c.test(t))&&(!g||!g.test(t)))try{var n=v.call(e,t);if(n||p.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){I(t,!0)}return 0<se(t,T,null,[e]).length},se.contains=function(e,t){return(e.ownerDocument||e)!=T&&C(e),y(e,t)},se.attr=function(e,t){(e.ownerDocument||e)!=T&&C(e);var n=x.attrHandle[t.toLowerCase()],r=n&&D.call(x.attrHandle,t.toLowerCase())?n(e,t,!E):void 0;return void 0!==r?r:p.attributes||!E?e.getAttribute(t):(r=e.getAttributeNode(t))&&r.specified?r.value:null},se.escape=function(e){return(e+").replace(ie,oe)},se.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},se.uniqueSort=function(e){var t,n=[],r=0,i=0;if(l=!p.detectDuplicates,u=!p.sortStable&&e.slice(0),e.sort(L),l){for(;t=e[i++];)t===e[i]&&(r=n.push(i));for(;r--;)e.splice(n[r],1)}return u=null,e},o=se.getText=function(e){var t,n=",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=o(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r++];)n+=o(t);return n},(x=se.selectors={cacheLength:50,createPseudo:le,match:G,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(re,f),e[3]=(e[3]||e[4]||e[5]||").replace(re,f),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||se.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&se.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return G.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||":n&&Y.test(n)&&(t=h(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(re,f).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=A[e+" "];return t||(t=new RegExp("(^|"+$+")"+e+"("+$+"|$)"))&&A(e,function(e){return t.test("string"==typeof e.className&&e.className||void 0!==e.getAttribute&&e.getAttribute("class")||")})},ATTR:function(n,r,i){return function(e){var t=se.attr(e,n);return null==t?"!="===r:!r||(t+=","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1<t.indexOf(i):"$="===r?i&&t.slice(-i.length)===i:"~="===r?-1<(" "+t.replace(z," ")+" ").indexOf(i):"|="===r&&(t===i||t.slice(0,i.length+1)===i+"-"))}},CHILD:function(h,e,t,m,g){var v="nth"!==h.slice(0,3),y="last"!==h.slice(-4),b="of-type"===e;return 1===m&&0===g?function(e){return!!e.parentNode}:function(e,t,n){var r,i,o,a,s,u,l=v!=y?"nextSibling":"previousSibling",c=e.parentNode,f=b&&e.nodeName.toLowerCase(),d=!n&&!b,p=!1;if(c){if(v){for(;l;){for(a=e;a=a[l];)if(b?a.nodeName.toLowerCase()===f:1===a.nodeType)return!1;u=l="only"===h&&!u&&"nextSibling"}return!0}if(u=[y?c.firstChild:c.lastChild],y&&d){for(p=(s=(r=(i=(o=(a=c)[S]||(a[S]={}))[a.uniqueID]||(o[a.uniqueID]={}))[h]||[])[0]===k&&r[1])&&r[2],a=s&&c.childNodes[s];a=++s&&a&&a[l]||(p=s=0)||u.pop();)if(1===a.nodeType&&++p&&a===e){i[h]=[k,s,p];break}}else if(d&&(p=s=(r=(i=(o=(a=e)[S]||(a[S]={}))[a.uniqueID]||(o[a.uniqueID]={}))[h]||[])[0]===k&&r[1]),!1===p)for(;(a=++s&&a&&a[l]||(p=s=0)||u.pop())&&((b?a.nodeName.toLowerCase()!==f:1!==a.nodeType)||!++p||(d&&((i=(o=a[S]||(a[S]={}))[a.uniqueID]||(o[a.uniqueID]={}))[h]=[k,p]),a!==e)););return(p-=g)===m||p%m==0&&0<=p/m}}},PSEUDO:function(e,o){var t,a=x.pseudos[e]||x.setFilters[e.toLowerCase()]||se.error("unsupported pseudo: "+e);return a[S]?a(o):1<a.length?(t=[e,e,",o],x.setFilters.hasOwnProperty(e.toLowerCase())?le(function(e,t){for(var n,r=a(e,o),i=r.length;i--;)e[n=M(e,r[i])]=!(t[n]=r[i])}):function(e){return a(e,0,t)}):a}},pseudos:{not:le(function(e){var r=[],i=[],s=d(e.replace(W,"$1"));return s[S]?le(function(e,t,n,r){for(var i,o=s(e,null,r,[]),a=e.length;a--;)(i=o[a])&&(e[a]=!(t[a]=i))}):function(e,t,n){return r[0]=e,s(r,null,n,i),r[0]=null,!i.pop()}}),has:le(function(t){return function(e){return 0<se(t,e).length}}),contains:le(function(t){return t=t.replace(re,f),function(e){return-1<(e.textContent||o(e)).indexOf(t)}}),lang:le(function(n){return V.test(n||")||se.error("unsupported lang: "+n),n=n.replace(re,f).toLowerCase(),function(e){var t;do{if(t=E?e.lang:e.getAttribute("xml:lang")||e.getAttribute("lang"))return(t=t.toLowerCase())===n||0===t.indexOf(n+"-")}while((e=e.parentNode)&&1===e.nodeType);return!1}}),target:function(e){var t=n.location&&n.location.hash;return t&&t.slice(1)===e.id},root:function(e){return e===s},focus:function(e){return e===T.activeElement&&(!T.hasFocus||T.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:me(!1),disabled:me(!0),checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,!0===e.selected},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!x.pseudos.empty(e)},header:function(e){return J.test(e.nodeName)},input:function(e){return Z.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:ge(function(){return[0]}),last:ge(function(e,t){return[t-1]}),eq:ge(function(e,t,n){return[n<0?n+t:n]}),even:ge(function(e,t){for(var n=0;n<t;n+=2)e.push(n);return e}),odd:ge(function(e,t){for(var n=1;n<t;n+=2)e.push(n);return e}),lt:ge(function(e,t,n){for(var r=n<0?n+t:t<n?t:n;0<=--r;)e.push(r);return e}),gt:ge(function(e,t,n){for(var r=n<0?n+t:n;++r<t;)e.push(r);return e})}}).pseudos.nth=x.pseudos.eq,{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})x.pseudos[e]=pe(e);for(e in{submit:!0,reset:!0})x.pseudos[e]=he(e);function ye(){}function be(e){for(var t=0,n=e.length,r=";t<n;t++)r+=e[t].value;return r}function xe(s,e,t){var u=e.dir,l=e.next,c=l||u,f=t&&"parentNode"===c,d=r++;return e.first?function(e,t,n){for(;e=e[u];)if(1===e.nodeType||f)return s(e,t,n);return!1}:function(e,t,n){var r,i,o,a=[k,d];if(n){for(;e=e[u];)if((1===e.nodeType||f)&&s(e,t,n))return!0}else for(;e=e[u];)if(1===e.nodeType||f)if(i=(o=e[S]||(e[S]={}))[e.uniqueID]||(o[e.uniqueID]={}),l&&l===e.nodeName.toLowerCase())e=e[u]||e;else{if((r=i[c])&&r[0]===k&&r[1]===d)return a[2]=r[2];if((i[c]=a)[2]=s(e,t,n))return!0}return!1}}function we(i){return 1<i.length?function(e,t,n){for(var r=i.length;r--;)if(!i[r](e,t,n))return!1;return!0}:i[0]}function Ce(e,t,n,r,i){for(var o,a=[],s=0,u=e.length,l=null!=t;s<u;s++)(o=e[s])&&(n&&!n(o,r,i)||(a.push(o),l&&t.push(s)));return a}function Te(p,h,m,g,v,e){return g&&!g[S]&&(g=Te(g)),v&&!v[S]&&(v=Te(v,e)),le(function(e,t,n,r){var i,o,a,s=[],u=[],l=t.length,c=e||function(e,t,n){for(var r=0,i=t.length;r<i;r++)se(e,t[r],n);return n}(h||"*",n.nodeType?[n]:n,[]),f=!p||!e&&h?c:Ce(c,s,p,n,r),d=m?v||(e?p:l||g)?[]:t:f;if(m&&m(f,d,n,r),g)for(i=Ce(d,u),g(i,[],n,r),o=i.length;o--;)(a=i[o])&&(d[u[o]]=!(f[u[o]]=a));if(e){if(v||p){if(v){for(i=[],o=d.length;o--;)(a=d[o])&&i.push(f[o]=a);v(null,d=[],i,r)}for(o=d.length;o--;)(a=d[o])&&-1<(i=v?M(e,a):s[o])&&(e[i]=!(t[i]=a))}}else d=Ce(d===t?d.splice(l,d.length):d),v?v(null,t,d,r):H.apply(t,d)})}function Ee(e){for(var i,t,n,r=e.length,o=x.relative[e[0].type],a=o||x.relative[" "],s=o?1:0,u=xe(function(e){return e===i},a,!0),l=xe(function(e){return-1<M(i,e)},a,!0),c=[function(e,t,n){var r=!o&&(n||t!==w)||((i=t).nodeType?u:l)(e,t,n);return i=null,r}];s<r;s++)if(t=x.relative[e[s].type])c=[xe(we(c),t)];else{if((t=x.filter[e[s].type].apply(null,e[s].matches))[S]){for(n=++s;n<r&&!x.relative[e[n].type];n++);return Te(1<s&&we(c),1<s&&be(e.slice(0,s-1).concat({value:" "===e[s-2].type?"*":"})).replace(W,"$1"),t,s<n&&Ee(e.slice(s,n)),n<r&&Ee(e=e.slice(n)),n<r&&be(e))}c.push(t)}return we(c)}function Se(g,v){function e(e,t,n,r,i){var o,a,s,u=0,l="0",c=e&&[],f=[],d=w,p=e||b&&x.find.TAG("*",i),h=k+=null==d?1:Math.random()||.1,m=p.length;for(i&&(w=t==T||t||i);l!==m&&null!=(o=p[l]);l++){if(b&&o){for(a=0,t||o.ownerDocument==T||(C(o),n=!E);s=g[a++];)if(s(o,t||T,n)){r.push(o);break}i&&(k=h)}y&&((o=!s&&o)&&u--,e&&c.push(o))}if(u+=l,y&&l!==u){for(a=0;s=v[a++];)s(c,f,t,n);if(e){if(0<u)for(;l--;)c[l]||f[l]||(f[l]=O.call(r));f=Ce(f)}H.apply(r,f),i&&!e&&0<f.length&&1<u+v.length&&se.uniqueSort(r)}return i&&(k=h,w=d),c}var y=0<v.length,b=0<g.length;return y?le(e):e}return ye.prototype=x.filters=x.pseudos,x.setFilters=new ye,h=se.tokenize=function(e,t){var n,r,i,o,a,s,u,l=N[e+" "];if(l)return t?0:l.slice(0);for(a=e,s=[],u=x.preFilter;a;){for(o in n&&!(r=U.exec(a))||(r&&(a=a.slice(r[0].length)||a),s.push(i=[])),n=!1,(r=X.exec(a))&&(n=r.shift(),i.push({value:n,type:r[0].replace(W," ")}),a=a.slice(n.length)),x.filter)!(r=G[o].exec(a))||u[o]&&!(r=u[o](r))||(n=r.shift(),i.push({value:n,type:o,matches:r}),a=a.slice(n.length));if(!n)break}return t?a.length:a?se.error(e):N(e,s).slice(0)},d=se.compile=function(e,t){var n,r=[],i=[],o=j[e+" "];if(!o){for(n=(t=t||h(e)).length;n--;)(o=Ee(t[n]))[S]?r.push(o):i.push(o);(o=j(e,Se(i,r))).selector=e}return o},m=se.select=function(e,t,n,r){var i,o,a,s,u,l="function"==typeof e&&e,c=!r&&h(e=l.selector||e);if(n=n||[],1===c.length){if(2<(o=c[0]=c[0].slice(0)).length&&"ID"===(a=o[0]).type&&9===t.nodeType&&E&&x.relative[o[1].type]){if(!(t=(x.find.ID(a.matches[0].replace(re,f),t)||[])[0]))return n;l&&(t=t.parentNode),e=e.slice(o.shift().value.length)}for(i=G.needsContext.test(e)?0:o.length;i--&&(a=o[i],!x.relative[s=a.type]);)if((u=x.find[s])&&(r=u(a.matches[0].replace(re,f),ne.test(o[0].type)&&ve(t.parentNode)||t))){if(o.splice(i,1),!(e=r.length&&be(o)))return H.apply(n,r),n;break}}return(l||d(e,c))(r,t,!E,n,!t||ne.test(e)&&ve(t.parentNode)||t),n},p.sortStable=S.split(").sort(L).join(")===S,p.detectDuplicates=!!l,C(),p.sortDetached=ce(function(e){return 1&e.compareDocumentPosition(T.createElement("fieldset"))}),ce(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||fe("type|href|height|width",function(e,t,n){if(!n)return e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),p.attributes&&ce(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value","),"===e.firstChild.getAttribute("value")})||fe("value",function(e,t,n){if(!n&&"input"===e.nodeName.toLowerCase())return e.defaultValue}),ce(function(e){return null==e.getAttribute("disabled")})||fe(_,function(e,t,n){var r;if(!n)return!0===e[t]?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null}),se}(T);S.find=p,S.expr=p.selectors,S.expr[":"]=S.expr.pseudos,S.uniqueSort=S.unique=p.uniqueSort,S.text=p.getText,S.isXMLDoc=p.isXML,S.contains=p.contains,S.escapeSelector=p.escape;function h(e,t,n){for(var r=[],i=void 0!==n;(e=e[t])&&9!==e.nodeType;)if(1===e.nodeType){if(i&&S(e).is(n))break;r.push(e)}return r}function C(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}var k=S.expr.match.needsContext;function A(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()}var N=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function j(e,n,r){return b(n)?S.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?S.grep(e,function(e){return e===n!==r}):"string"!=typeof n?S.grep(e,function(e){return-1<i.call(n,e)!==r}):S.filter(n,e,r)}S.filter=function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?S.find.matchesSelector(r,e)?[r]:[]:S.find.matches(e,S.grep(t,function(e){return 1===e.nodeType}))},S.fn.extend({find:function(e){var t,n,r=this.length,i=this;if("string"!=typeof e)return this.pushStack(S(e).filter(function(){for(t=0;t<r;t++)if(S.contains(i[t],this))return!0}));for(n=this.pushStack([]),t=0;t<r;t++)S.find(e,i[t],n);return 1<r?S.uniqueSort(n):n},filter:function(e){return this.pushStack(j(this,e||[],!1))},not:function(e){return this.pushStack(j(this,e||[],!0))},is:function(e){return!!j(this,"string"==typeof e&&k.test(e)?S(e):e||[],!1).length}});var I,L=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/;(S.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||I,"string"!=typeof e)return e.nodeType?(this[0]=e,this.length=1,this):b(e)?void 0!==n.ready?n.ready(e):e(S):S.makeArray(e,this);if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:L.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof S?t[0]:t,S.merge(this,S.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:E,!0)),N.test(r[1])&&S.isPlainObject(t))for(r in t)b(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=E.getElementById(r[2]))&&(this[0]=i,this.length=1),this}).prototype=S.fn,I=S(E);var D=/^(?:parents|prev(?:Until|All))/,O={children:!0,contents:!0,next:!0,prev:!0};function P(e,t){for(;(e=e[t])&&1!==e.nodeType;);return e}S.fn.extend({has:function(e){var t=S(e,this),n=t.length;return this.filter(function(){for(var e=0;e<n;e++)if(S.contains(this,t[e]))return!0})},closest:function(e,t){var n,r=0,i=this.length,o=[],a="string"!=typeof e&&S(e);if(!k.test(e))for(;r<i;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(n.nodeType<11&&(a?-1<a.index(n):1===n.nodeType&&S.find.matchesSelector(n,e))){o.push(n);break}return this.pushStack(1<o.length?S.uniqueSort(o):o)},index:function(e){return e?"string"==typeof e?i.call(S(e),this[0]):i.call(this,e.jquery?e[0]:e):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(S.uniqueSort(S.merge(this.get(),S(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),S.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return h(e,"parentNode")},parentsUntil:function(e,t,n){return h(e,"parentNode",n)},next:function(e){return P(e,"nextSibling")},prev:function(e){return P(e,"previousSibling")},nextAll:function(e){return h(e,"nextSibling")},prevAll:function(e){return h(e,"previousSibling")},nextUntil:function(e,t,n){return h(e,"nextSibling",n)},prevUntil:function(e,t,n){return h(e,"previousSibling",n)},siblings:function(e){return C((e.parentNode||{}).firstChild,e)},children:function(e){return C(e.firstChild)},contents:function(e){return null!=e.contentDocument&&r(e.contentDocument)?e.contentDocument:(A(e,"template")&&(e=e.content||e),S.merge([],e.childNodes))}},function(r,i){S.fn[r]=function(e,t){var n=S.map(this,i,e);return"Until"!==r.slice(-5)&&(t=e),t&&"string"==typeof t&&(n=S.filter(t,n)),1<this.length&&(O[r]||S.uniqueSort(n),D.test(r)&&n.reverse()),this.pushStack(n)}});var H=/[^\x20\t\r\n\f]+/g;function q(e){return e}function M(e){throw e}function _(e,t,n,r){var i;try{e&&b(i=e.promise)?i.call(e).done(t).fail(n):e&&b(i=e.then)?i.call(e,t,n):t.apply(void 0,[e].slice(r))}catch(e){n.apply(void 0,[e])}}S.Callbacks=function(r){var e,n;r="string"==typeof r?(e=r,n={},S.each(e.match(H)||[],function(e,t){n[t]=!0}),n):S.extend({},r);function i(){for(s=s||r.once,a=o=!0;l.length;c=-1)for(t=l.shift();++c<u.length;)!1===u[c].apply(t[0],t[1])&&r.stopOnFalse&&(c=u.length,t=!1);r.memory||(t=!1),o=!1,s&&(u=t?[]:")}var o,t,a,s,u=[],l=[],c=-1,f={add:function(){return u&&(t&&!o&&(c=u.length-1,l.push(t)),function n(e){S.each(e,function(e,t){b(t)?r.unique&&f.has(t)||u.push(t):t&&t.length&&"string"!==w(t)&&n(t)})}(arguments),t&&!o&&i()),this},remove:function(){return S.each(arguments,function(e,t){for(var n;-1<(n=S.inArray(t,u,n));)u.splice(n,1),n<=c&&c--}),this},has:function(e){return e?-1<S.inArray(e,u):0<u.length},empty:function(){return u=u&&[],this},disable:function(){return s=l=[],u=t=",this},disabled:function(){return!u},lock:function(){return s=l=[],t||o||(u=t="),this},locked:function(){return!!s},fireWith:function(e,t){return s||(t=[e,(t=t||[]).slice?t.slice():t],l.push(t),o||i()),this},fire:function(){return f.fireWith(this,arguments),this},fired:function(){return!!a}};return f},S.extend({Deferred:function(e){var o=[["notify","progress",S.Callbacks("memory"),S.Callbacks("memory"),2],["resolve","done",S.Callbacks("once memory"),S.Callbacks("once memory"),0,"resolved"],["reject","fail",S.Callbacks("once memory"),S.Callbacks("once memory"),1,"rejected"]],i="pending",a={state:function(){return i},always:function(){return s.done(arguments).fail(arguments),this},catch:function(e){return a.then(null,e)},pipe:function(){var i=arguments;return S.Deferred(function(r){S.each(o,function(e,t){var n=b(i[t[4]])&&i[t[4]];s[t[1]](function(){var e=n&&n.apply(this,arguments);e&&b(e.promise)?e.promise().progress(r.notify).done(r.resolve).fail(r.reject):r[t[0]+"With"](this,n?[e]:arguments)})}),i=null}).promise()},then:function(t,n,r){var u=0;function l(i,o,a,s){return function(){function e(){var e,t;if(!(i<u)){if((e=a.apply(n,r))===o.promise())throw new TypeError("Thenable self-resolution");t=e&&("object"==typeof e||"function"==typeof e)&&e.then,b(t)?s?t.call(e,l(u,o,q,s),l(u,o,M,s)):(u++,t.call(e,l(u,o,q,s),l(u,o,M,s),l(u,o,q,o.notifyWith))):(a!==q&&(n=void 0,r=[e]),(s||o.resolveWith)(n,r))}}var n=this,r=arguments,t=s?e:function(){try{e()}catch(e){S.Deferred.exceptionHook&&S.Deferred.exceptionHook(e,t.stackTrace),u<=i+1&&(a!==M&&(n=void 0,r=[e]),o.rejectWith(n,r))}};i?t():(S.Deferred.getStackHook&&(t.stackTrace=S.Deferred.getStackHook()),T.setTimeout(t))}}return S.Deferred(function(e){o[0][3].add(l(0,e,b(r)?r:q,e.notifyWith)),o[1][3].add(l(0,e,b(t)?t:q)),o[2][3].add(l(0,e,b(n)?n:M))}).promise()},promise:function(e){return null!=e?S.extend(e,a):a}},s={};return S.each(o,function(e,t){var n=t[2],r=t[5];a[t[1]]=n.add,r&&n.add(function(){i=r},o[3-e][2].disable,o[3-e][3].disable,o[0][2].lock,o[0][3].lock),n.add(t[3].fire),s[t[0]]=function(){return s[t[0]+"With"](this===s?void 0:this,arguments),this},s[t[0]+"With"]=n.fireWith}),a.promise(s),e&&e.call(s,s),s},when:function(e){function t(t){return function(e){i[t]=this,o[t]=1<arguments.length?s.call(arguments):e,--n||a.resolveWith(i,o)}}var n=arguments.length,r=n,i=Array(r),o=s.call(arguments),a=S.Deferred();if(n<=1&&(_(e,a.done(t(r)).resolve,a.reject,!n),"pending"===a.state()||b(o[r]&&o[r].then)))return a.then();for(;r--;)_(o[r],t(r),a.reject);return a.promise()}});var $=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;S.Deferred.exceptionHook=function(e,t){T.console&&T.console.warn&&e&&$.test(e.name)&&T.console.warn("jQuery.Deferred exception: "+e.message,e.stack,t)},S.readyException=function(e){T.setTimeout(function(){throw e})};var R=S.Deferred();function B(){E.removeEventListener("DOMContentLoaded",B),T.removeEventListener("load",B),S.ready()}S.fn.ready=function(e){return R.then(e).catch(function(e){S.readyException(e)}),this},S.extend({isReady:!1,readyWait:1,ready:function(e){(!0===e?--S.readyWait:S.isReady)||(S.isReady=!0)!==e&&0<--S.readyWait||R.resolveWith(E,[S])}}),S.ready.then=R.then,"complete"===E.readyState||"loading"!==E.readyState&&!E.documentElement.doScroll?T.setTimeout(S.ready):(E.addEventListener("DOMContentLoaded",B),T.addEventListener("load",B));var F=function(e,t,n,r,i,o,a){var s=0,u=e.length,l=null==n;if("object"===w(n))for(s in i=!0,n)F(e,t,s,n[s],!0,o,a);else if(void 0!==r&&(i=!0,b(r)||(a=!0),l&&(t=a?(t.call(e,r),null):(l=t,function(e,t,n){return l.call(S(e),n)})),t))for(;s<u;s++)t(e[s],n,a?r:r.call(e[s],s,t(e[s],n)));return i?e:l?t.call(e):u?t(e[0],n):o},z=/^-ms-/,W=/-([a-z])/g;function U(e,t){return t.toUpperCase()}function X(e){return e.replace(z,"ms-").replace(W,U)}function Q(e){return 1===e.nodeType||9===e.nodeType||!+e.nodeType}function Y(){this.expando=S.expando+Y.uid++}Y.uid=1,Y.prototype={cache:function(e){var t=e[this.expando];return t||(t={},Q(e)&&(e.nodeType?e[this.expando]=t:Object.defineProperty(e,this.expando,{value:t,configurable:!0}))),t},set:function(e,t,n){var r,i=this.cache(e);if("string"==typeof t)i[X(t)]=n;else for(r in t)i[X(r)]=t[r];return i},get:function(e,t){return void 0===t?this.cache(e):e[this.expando]&&e[this.expando][X(t)]},access:function(e,t,n){return void 0===t||t&&"string"==typeof t&&void 0===n?this.get(e,t):(this.set(e,t,n),void 0!==n?n:t)},remove:function(e,t){var n,r=e[this.expando];if(void 0!==r){if(void 0!==t){n=(t=Array.isArray(t)?t.map(X):(t=X(t))in r?[t]:t.match(H)||[]).length;for(;n--;)delete r[t[n]]}void 0!==t&&!S.isEmptyObject(r)||(e.nodeType?e[this.expando]=void 0:delete e[this.expando])}},hasData:function(e){var t=e[this.expando];return void 0!==t&&!S.isEmptyObject(t)}};var V=new Y,G=new Y,K=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,Z=/[A-Z]/g;function J(e,t,n){var r,i;if(void 0===n&&1===e.nodeType)if(r="data-"+t.replace(Z,"-$&").toLowerCase(),"string"==typeof(n=e.getAttribute(r))){try{n="true"===(i=n)||"false"!==i&&("null"===i?null:i===+i+"?+i:K.test(i)?JSON.parse(i):i)}catch(e){}G.set(e,t,n)}else n=void 0;return n}S.extend({hasData:function(e){return G.hasData(e)||V.hasData(e)},data:function(e,t,n){return G.access(e,t,n)},removeData:function(e,t){G.remove(e,t)},_data:function(e,t,n){return V.access(e,t,n)},_removeData:function(e,t){V.remove(e,t)}}),S.fn.extend({data:function(n,e){var t,r,i,o=this[0],a=o&&o.attributes;if(void 0!==n)return"object"==typeof n?this.each(function(){G.set(this,n)}):F(this,function(e){var t;if(o&&void 0===e)return void 0!==(t=G.get(o,n))||void 0!==(t=J(o,n))?t:void 0;this.each(function(){G.set(this,n,e)})},null,e,1<arguments.length,null,!0);if(this.length&&(i=G.get(o),1===o.nodeType&&!V.get(o,"hasDataAttrs"))){for(t=a.length;t--;)a[t]&&0===(r=a[t].name).indexOf("data-")&&(r=X(r.slice(5)),J(o,r,i[r]));V.set(o,"hasDataAttrs",!0)}return i},removeData:function(e){return this.each(function(){G.remove(this,e)})}}),S.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=V.get(e,t),n&&(!r||Array.isArray(n)?r=V.access(e,t,S.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=S.queue(e,t),r=n.length,i=n.shift(),o=S._queueHooks(e,t);"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,function(){S.dequeue(e,t)},o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return V.get(e,n)||V.access(e,n,{empty:S.Callbacks("once memory").add(function(){V.remove(e,[t+"queue",n])})})}}),S.fn.extend({queue:function(t,n){var e=2;return"string"!=typeof t&&(n=t,t="fx",e--),arguments.length<e?S.queue(this[0],t):void 0===n?this:this.each(function(){var e=S.queue(this,t,n);S._queueHooks(this,t),"fx"===t&&"inprogress"!==e[0]&&S.dequeue(this,t)})},dequeue:function(e){return this.each(function(){S.dequeue(this,e)})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){function n(){--i||o.resolveWith(a,[a])}var r,i=1,o=S.Deferred(),a=this,s=this.length;for("string"!=typeof e&&(t=e,e=void 0),e=e||"fx";s--;)(r=V.get(a[s],e+"queueHooks"))&&r.empty&&(i++,r.empty.add(n));return n(),o.promise(t)}});var ee=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,te=new RegExp("^(?:([+-])=|)("+ee+")([a-z%]*)$","i"),ne=["Top","Right","Bottom","Left"],re=E.documentElement,ie=function(e){return S.contains(e.ownerDocument,e)},oe={composed:!0};re.getRootNode&&(ie=function(e){return S.contains(e.ownerDocument,e)||e.getRootNode(oe)===e.ownerDocument});var ae=function(e,t){return"none"===(e=t||e).style.display||"===e.style.display&&ie(e)&&"none"===S.css(e,"display")};function se(e,t,n,r){var i,o,a=20,s=r?function(){return r.cur()}:function(){return S.css(e,t,")},u=s(),l=n&&n[3]||(S.cssNumber[t]?":"px"),c=e.nodeType&&(S.cssNumber[t]||"px"!==l&&+u)&&te.exec(S.css(e,t));if(c&&c[3]!==l){for(u/=2,l=l||c[3],c=+u||1;a--;)S.style(e,t,c+l),(1-o)*(1-(o=s()/u||.5))<=0&&(a=0),c/=o;c*=2,S.style(e,t,c+l),n=n||[]}return n&&(c=+c||+u||0,i=n[1]?c+(n[1]+1)*n[2]:+n[2],r&&(r.unit=l,r.start=c,r.end=i)),i}var ue={};function le(e,t){for(var n,r,i,o,a,s,u,l=[],c=0,f=e.length;c<f;c++)(r=e[c]).style&&(n=r.style.display,t?("none"===n&&(l[c]=V.get(r,"display")||null,l[c]||(r.style.display=")),"===r.style.display&&ae(r)&&(l[c]=(u=a=o=void 0,a=(i=r).ownerDocument,s=i.nodeName,(u=ue[s])||(o=a.body.appendChild(a.createElement(s)),u=S.css(o,"display"),o.parentNode.removeChild(o),"none"===u&&(u="block"),ue[s]=u)))):"none"!==n&&(l[c]="none",V.set(r,"display",n)));for(c=0;c<f;c++)null!=l[c]&&(e[c].style.display=l[c]);return e}S.fn.extend({show:function(){return le(this,!0)},hide:function(){return le(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){ae(this)?S(this).show():S(this).hide()})}});var ce,fe,de=/^(?:checkbox|radio)$/i,pe=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i,he=/^$|^module$|\/(?:java|ecma)script/i;ce=E.createDocumentFragment().appendChild(E.createElement("div")),(fe=E.createElement("input")).setAttribute("type","radio"),fe.setAttribute("checked","checked"),fe.setAttribute("name","t"),ce.appendChild(fe),y.checkClone=ce.cloneNode(!0).cloneNode(!0).lastChild.checked,ce.innerHTML="<textarea>x</textarea>",y.noCloneChecked=!!ce.cloneNode(!0).lastChild.defaultValue,ce.innerHTML="<option></option>",y.option=!!ce.lastChild;var me={thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,","]};function ge(e,t){var n;return n=void 0!==e.getElementsByTagName?e.getElementsByTagName(t||"*"):void 0!==e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&A(e,t)?S.merge([e],n):n}function ve(e,t){for(var n=0,r=e.length;n<r;n++)V.set(e[n],"globalEval",!t||V.get(t[n],"globalEval"))}me.tbody=me.tfoot=me.colgroup=me.caption=me.thead,me.th=me.td,y.option||(me.optgroup=me.option=[1,"<select multiple='multiple'>","</select>"]);var ye=/<|&#?\w+;/;function be(e,t,n,r,i){for(var o,a,s,u,l,c,f=t.createDocumentFragment(),d=[],p=0,h=e.length;p<h;p++)if((o=e[p])||0===o)if("object"===w(o))S.merge(d,o.nodeType?[o]:o);else if(ye.test(o)){for(a=a||f.appendChild(t.createElement("div")),s=(pe.exec(o)||[","])[1].toLowerCase(),u=me[s]||me._default,a.innerHTML=u[1]+S.htmlPrefilter(o)+u[2],c=u[0];c--;)a=a.lastChild;S.merge(d,a.childNodes),(a=f.firstChild).textContent="}else d.push(t.createTextNode(o));for(f.textContent=",p=0;o=d[p++];)if(r&&-1<S.inArray(o,r))i&&i.push(o);else if(l=ie(o),a=ge(f.appendChild(o),"script"),l&&ve(a),n)for(c=0;o=a[c++];)he.test(o.type||")&&n.push(o);return f}var xe=/^key/,we=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,Ce=/^([^.]*)(?:\.(.+)|)/;function Te(){return!0}function Ee(){return!1}function Se(e,t){return e===function(){try{return E.activeElement}catch(e){}}()==("focus"===t)}function ke(e,t,n,r,i,o){var a,s;if("object"==typeof t){for(s in"string"!=typeof n&&(r=r||n,n=void 0),t)ke(e,s,n,r,t[s],o);return e}if(null==r&&null==i?(i=n,r=n=void 0):null==i&&("string"==typeof n?(i=r,r=void 0):(i=r,r=n,n=void 0)),!1===i)i=Ee;else if(!i)return e;return 1===o&&(a=i,(i=function(e){return S().off(e),a.apply(this,arguments)}).guid=a.guid||(a.guid=S.guid++)),e.each(function(){S.event.add(this,t,i,r,n)})}function Ae(e,i,o){o?(V.set(e,i,!1),S.event.add(e,i,{namespace:!1,handler:function(e){var t,n,r=V.get(this,i);if(1&e.isTrigger&&this[i]){if(r.length)(S.event.special[i]||{}).delegateType&&e.stopPropagation();else if(r=s.call(arguments),V.set(this,i,r),t=o(this,i),this[i](),r!==(n=V.get(this,i))||t?V.set(this,i,!1):n={},r!==n)return e.stopImmediatePropagation(),e.preventDefault(),n.value}else r.length&&(V.set(this,i,{value:S.event.trigger(S.extend(r[0],S.Event.prototype),r.slice(1),this)}),e.stopImmediatePropagation())}})):void 0===V.get(e,i)&&S.event.add(e,i,Te)}S.event={global:{},add:function(t,e,n,r,i){var o,a,s,u,l,c,f,d,p,h,m,g=V.get(t);if(Q(t))for(n.handler&&(n=(o=n).handler,i=o.selector),i&&S.find.matchesSelector(re,i),n.guid||(n.guid=S.guid++),(u=g.events)||(u=g.events=Object.create(null)),(a=g.handle)||(a=g.handle=function(e){return void 0!==S&&S.event.triggered!==e.type?S.event.dispatch.apply(t,arguments):void 0}),l=(e=(e||").match(H)||["]).length;l--;)p=m=(s=Ce.exec(e[l])||[])[1],h=(s[2]||").split(".").sort(),p&&(f=S.event.special[p]||{},p=(i?f.delegateType:f.bindType)||p,f=S.event.special[p]||{},c=S.extend({type:p,origType:m,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&S.expr.match.needsContext.test(i),namespace:h.join(".")},o),(d=u[p])||((d=u[p]=[]).delegateCount=0,f.setup&&!1!==f.setup.call(t,r,h,a)||t.addEventListener&&t.addEventListener(p,a)),f.add&&(f.add.call(t,c),c.handler.guid||(c.handler.guid=n.guid)),i?d.splice(d.delegateCount++,0,c):d.push(c),S.event.global[p]=!0)},remove:function(e,t,n,r,i){var o,a,s,u,l,c,f,d,p,h,m,g=V.hasData(e)&&V.get(e);if(g&&(u=g.events)){for(l=(t=(t||").match(H)||["]).length;l--;)if(p=m=(s=Ce.exec(t[l])||[])[1],h=(s[2]||").split(".").sort(),p){for(f=S.event.special[p]||{},d=u[p=(r?f.delegateType:f.bindType)||p]||[],s=s[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=o=d.length;o--;)c=d[o],!i&&m!==c.origType||n&&n.guid!==c.guid||s&&!s.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(d.splice(o,1),c.selector&&d.delegateCount--,f.remove&&f.remove.call(e,c));a&&!d.length&&(f.teardown&&!1!==f.teardown.call(e,h,g.handle)||S.removeEvent(e,p,g.handle),delete u[p])}else for(p in u)S.event.remove(e,p+t[l],n,r,!0);S.isEmptyObject(u)&&V.remove(e,"handle events")}},dispatch:function(e){var t,n,r,i,o,a,s=new Array(arguments.length),u=S.event.fix(e),l=(V.get(this,"events")||Object.create(null))[u.type]||[],c=S.event.special[u.type]||{};for(s[0]=u,t=1;t<arguments.length;t++)s[t]=arguments[t];if(u.delegateTarget=this,!c.preDispatch||!1!==c.preDispatch.call(this,u)){for(a=S.event.handlers.call(this,u,l),t=0;(i=a[t++])&&!u.isPropagationStopped();)for(u.currentTarget=i.elem,n=0;(o=i.handlers[n++])&&!u.isImmediatePropagationStopped();)u.rnamespace&&!1!==o.namespace&&!u.rnamespace.test(o.namespace)||(u.handleObj=o,u.data=o.data,void 0!==(r=((S.event.special[o.origType]||{}).handle||o.handler).apply(i.elem,s))&&!1===(u.result=r)&&(u.preventDefault(),u.stopPropagation()));return c.postDispatch&&c.postDispatch.call(this,u),u.result}},handlers:function(e,t){var n,r,i,o,a,s=[],u=t.delegateCount,l=e.target;if(u&&l.nodeType&&!("click"===e.type&&1<=e.button))for(;l!==this;l=l.parentNode||this)if(1===l.nodeType&&("click"!==e.type||!0!==l.disabled)){for(o=[],a={},n=0;n<u;n++)void 0===a[i=(r=t[n]).selector+" "]&&(a[i]=r.needsContext?-1<S(i,this).index(l):S.find(i,this,null,[l]).length),a[i]&&o.push(r);o.length&&s.push({elem:l,handlers:o})}return l=this,u<t.length&&s.push({elem:l,handlers:t.slice(u)}),s},addProp:function(t,e){Object.defineProperty(S.Event.prototype,t,{enumerable:!0,configurable:!0,get:b(e)?function(){if(this.originalEvent)return e(this.originalEvent)}:function(){if(this.originalEvent)return this.originalEvent[t]},set:function(e){Object.defineProperty(this,t,{enumerable:!0,configurable:!0,writable:!0,value:e})}})},fix:function(e){return e[S.expando]?e:new S.Event(e)},special:{load:{noBubble:!0},click:{setup:function(e){var t=this||e;return de.test(t.type)&&t.click&&A(t,"input")&&Ae(t,"click",Te),!1},trigger:function(e){var t=this||e;return de.test(t.type)&&t.click&&A(t,"input")&&Ae(t,"click"),!0},_default:function(e){var t=e.target;return de.test(t.type)&&t.click&&A(t,"input")&&V.get(t,"click")||A(t,"a")}},beforeunload:{postDispatch:function(e){void 0!==e.result&&e.originalEvent&&(e.originalEvent.returnValue=e.result)}}}},S.removeEvent=function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n)},S.Event=function(e,t){if(!(this instanceof S.Event))return new S.Event(e,t);e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||void 0===e.defaultPrevented&&!1===e.returnValue?Te:Ee,this.target=e.target&&3===e.target.nodeType?e.target.parentNode:e.target,this.currentTarget=e.currentTarget,this.relatedTarget=e.relatedTarget):this.type=e,t&&S.extend(this,t),this.timeStamp=e&&e.timeStamp||Date.now(),this[S.expando]=!0},S.Event.prototype={constructor:S.Event,isDefaultPrevented:Ee,isPropagationStopped:Ee,isImmediatePropagationStopped:Ee,isSimulated:!1,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=Te,e&&!this.isSimulated&&e.preventDefault()},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=Te,e&&!this.isSimulated&&e.stopPropagation()},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=Te,e&&!this.isSimulated&&e.stopImmediatePropagation(),this.stopPropagation()}},S.each({altKey:!0,bubbles:!0,cancelable:!0,changedTouches:!0,ctrlKey:!0,detail:!0,eventPhase:!0,metaKey:!0,pageX:!0,pageY:!0,shiftKey:!0,view:!0,char:!0,code:!0,charCode:!0,key:!0,keyCode:!0,button:!0,buttons:!0,clientX:!0,clientY:!0,offsetX:!0,offsetY:!0,pointerId:!0,pointerType:!0,screenX:!0,screenY:!0,targetTouches:!0,toElement:!0,touches:!0,which:function(e){var t=e.button;return null==e.which&&xe.test(e.type)?null!=e.charCode?e.charCode:e.keyCode:!e.which&&void 0!==t&&we.test(e.type)?1&t?1:2&t?3:4&t?2:0:e.which}},S.event.addProp),S.each({focus:"focusin",blur:"focusout"},function(e,t){S.event.special[e]={setup:function(){return Ae(this,e,Se),!1},trigger:function(){return Ae(this,e),!0},delegateType:t}}),S.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(e,i){S.event.special[e]={delegateType:i,bindType:i,handle:function(e){var t,n=e.relatedTarget,r=e.handleObj;return n&&(n===this||S.contains(this,n))||(e.type=r.origType,t=r.handler.apply(this,arguments),e.type=i),t}}}),S.fn.extend({on:function(e,t,n,r){return ke(this,e,t,n,r)},one:function(e,t,n,r){return ke(this,e,t,n,r,1)},off:function(e,t,n){var r,i;if(e&&e.preventDefault&&e.handleObj)return r=e.handleObj,S(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler),this;if("object"!=typeof e)return!1!==t&&"function"!=typeof t||(n=t,t=void 0),!1===n&&(n=Ee),this.each(function(){S.event.remove(this,e,n,t)});for(i in e)this.off(i,t,e[i]);return this}});var Ne=/<script|<style|<link/i,je=/checked\s*(?:[^=]|=\s*.checked.)/i,Ie=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;function Le(e,t){return A(e,"table")&&A(11!==t.nodeType?t:t.firstChild,"tr")&&S(e).children("tbody")[0]||e}function De(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function Oe(e){return"true/"===(e.type||").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Pe(e,t){var n,r,i,o,a,s;if(1===t.nodeType){if(V.hasData(e)&&(s=V.get(e).events))for(i in V.remove(t,"handle events"),s)for(n=0,r=s[i].length;n<r;n++)S.event.add(t,i,s[i][n]);G.hasData(e)&&(o=G.access(e),a=S.extend({},o),G.set(t,a))}}function He(n,r,i,o){r=g(r);var e,t,a,s,u,l,c=0,f=n.length,d=f-1,p=r[0],h=b(p);if(h||1<f&&"string"==typeof p&&!y.checkClone&&je.test(p))return n.each(function(e){var t=n.eq(e);h&&(r[0]=p.call(this,e,t.html())),He(t,r,i,o)});if(f&&(t=(e=be(r,n[0].ownerDocument,!1,n,o)).firstChild,1===e.childNodes.length&&(e=t),t||o)){for(s=(a=S.map(ge(e,"script"),De)).length;c<f;c++)u=e,c!==d&&(u=S.clone(u,!0,!0),s&&S.merge(a,ge(u,"script"))),i.call(n[c],u,c);if(s)for(l=a[a.length-1].ownerDocument,S.map(a,Oe),c=0;c<s;c++)u=a[c],he.test(u.type||")&&!V.access(u,"globalEval")&&S.contains(l,u)&&(u.src&&"module"!==(u.type||").toLowerCase()?S._evalUrl&&!u.noModule&&S._evalUrl(u.src,{nonce:u.nonce||u.getAttribute("nonce")},l):x(u.textContent.replace(Ie,"),u,l))}return n}function qe(e,t,n){for(var r,i=t?S.filter(t,e):e,o=0;null!=(r=i[o]);o++)n||1!==r.nodeType||S.cleanData(ge(r)),r.parentNode&&(n&&ie(r)&&ve(ge(r,"script")),r.parentNode.removeChild(r));return e}S.extend({htmlPrefilter:function(e){return e},clone:function(e,t,n){var r,i,o,a,s,u,l,c=e.cloneNode(!0),f=ie(e);if(!(y.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||S.isXMLDoc(e)))for(a=ge(c),r=0,i=(o=ge(e)).length;r<i;r++)s=o[r],u=a[r],"input"===(l=u.nodeName.toLowerCase())&&de.test(s.type)?u.checked=s.checked:"input"!==l&&"textarea"!==l||(u.defaultValue=s.defaultValue);if(t)if(n)for(o=o||ge(e),a=a||ge(c),r=0,i=o.length;r<i;r++)Pe(o[r],a[r]);else Pe(e,c);return 0<(a=ge(c,"script")).length&&ve(a,!f&&ge(e,"script")),c},cleanData:function(e){for(var t,n,r,i=S.event.special,o=0;void 0!==(n=e[o]);o++)if(Q(n)){if(t=n[V.expando]){if(t.events)for(r in t.events)i[r]?S.event.remove(n,r):S.removeEvent(n,r,t.handle);n[V.expando]=void 0}n[G.expando]&&(n[G.expando]=void 0)}}}),S.fn.extend({detach:function(e){return qe(this,e,!0)},remove:function(e){return qe(this,e)},text:function(e){return F(this,function(e){return void 0===e?S.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=e)})},null,e,arguments.length)},append:function(){return He(this,arguments,function(e){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||Le(this,e).appendChild(e)})},prepend:function(){return He(this,arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Le(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return He(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return He(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},empty:function(){for(var e,t=0;null!=(e=this[t]);t++)1===e.nodeType&&(S.cleanData(ge(e,!1)),e.textContent=");return this},clone:function(e,t){return e=null!=e&&e,t=null==t?e:t,this.map(function(){return S.clone(this,e,t)})},html:function(e){return F(this,function(e){var t=this[0]||{},n=0,r=this.length;if(void 0===e&&1===t.nodeType)return t.innerHTML;if("string"==typeof e&&!Ne.test(e)&&!me[(pe.exec(e)||[","])[1].toLowerCase()]){e=S.htmlPrefilter(e);try{for(;n<r;n++)1===(t=this[n]||{}).nodeType&&(S.cleanData(ge(t,!1)),t.innerHTML=e);t=0}catch(e){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var n=[];return He(this,arguments,function(e){var t=this.parentNode;S.inArray(this,n)<0&&(S.cleanData(ge(this)),t&&t.replaceChild(e,this))},n)}}),S.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,a){S.fn[e]=function(e){for(var t,n=[],r=S(e),i=r.length-1,o=0;o<=i;o++)t=o===i?this:this.clone(!0),S(r[o])[a](t),u.apply(n,t.get());return this.pushStack(n)}});function Me(e,t,n){var r,i,o={};for(i in t)o[i]=e.style[i],e.style[i]=t[i];for(i in r=n.call(e),t)e.style[i]=o[i];return r}var _e,$e,Re,Be,Fe,ze,We,Ue,Xe=new RegExp("^("+ee+")(?!px)[a-z%]+$","i"),Qe=function(e){var t=e.ownerDocument.defaultView;return t&&t.opener||(t=T),t.getComputedStyle(e)},Ye=new RegExp(ne.join("|"),"i");function Ve(){if(Ue){We.style.cssText="position:absolute;left:-11111px;width:60px;margin-top:1px;padding:0;border:0",Ue.style.cssText="position:relative;display:block;box-sizing:border-box;overflow:scroll;margin:auto;border:1px;padding:1px;width:60%;top:1%",re.appendChild(We).appendChild(Ue);var e=T.getComputedStyle(Ue);_e="1%"!==e.top,ze=12===Ge(e.marginLeft),Ue.style.right="60%",Be=36===Ge(e.right),$e=36===Ge(e.width),Ue.style.position="absolute",Re=12===Ge(Ue.offsetWidth/3),re.removeChild(We),Ue=null}}function Ge(e){return Math.round(parseFloat(e))}function Ke(e,t,n){var r,i,o,a,s=e.style;return(n=n||Qe(e))&&("!==(a=n.getPropertyValue(t)||n[t])||ie(e)||(a=S.style(e,t)),!y.pixelBoxStyles()&&Xe.test(a)&&Ye.test(t)&&(r=s.width,i=s.minWidth,o=s.maxWidth,s.minWidth=s.maxWidth=s.width=a,a=n.width,s.width=r,s.minWidth=i,s.maxWidth=o)),void 0!==a?a+":a}function Ze(e,t){return{get:function(){if(!e())return(this.get=t).apply(this,arguments);delete this.get}}}We=E.createElement("div"),(Ue=E.createElement("div")).style&&(Ue.style.backgroundClip="content-box",Ue.cloneNode(!0).style.backgroundClip=",y.clearCloneStyle="content-box"===Ue.style.backgroundClip,S.extend(y,{boxSizingReliable:function(){return Ve(),$e},pixelBoxStyles:function(){return Ve(),Be},pixelPosition:function(){return Ve(),_e},reliableMarginLeft:function(){return Ve(),ze},scrollboxSize:function(){return Ve(),Re},reliableTrDimensions:function(){var e,t,n,r;return null==Fe&&(e=E.createElement("table"),t=E.createElement("tr"),n=E.createElement("div"),e.style.cssText="position:absolute;left:-11111px",t.style.height="1px",n.style.height="9px",re.appendChild(e).appendChild(t).appendChild(n),r=T.getComputedStyle(t),Fe=3<parseInt(r.height),re.removeChild(e)),Fe}}));var Je=["Webkit","Moz","ms"],et=E.createElement("div").style,tt={};function nt(e){var t=S.cssProps[e]||tt[e];return t||(e in et?e:tt[e]=function(e){for(var t=e[0].toUpperCase()+e.slice(1),n=Je.length;n--;)if((e=Je[n]+t)in et)return e}(e)||e)}var rt=/^(none|table(?!-c[ea]).+)/,it=/^--/,ot={position:"absolute",visibility:"hidden",display:"block"},at={letterSpacing:"0",fontWeight:"400"};function st(e,t,n){var r=te.exec(t);return r?Math.max(0,r[2]-(n||0))+(r[3]||"px"):t}function ut(e,t,n,r,i,o){var a="width"===t?1:0,s=0,u=0;if(n===(r?"border":"content"))return 0;for(;a<4;a+=2)"margin"===n&&(u+=S.css(e,n+ne[a],!0,i)),r?("content"===n&&(u-=S.css(e,"padding"+ne[a],!0,i)),"margin"!==n&&(u-=S.css(e,"border"+ne[a]+"Width",!0,i))):(u+=S.css(e,"padding"+ne[a],!0,i),"padding"!==n?u+=S.css(e,"border"+ne[a]+"Width",!0,i):s+=S.css(e,"border"+ne[a]+"Width",!0,i));return!r&&0<=o&&(u+=Math.max(0,Math.ceil(e["offset"+t[0].toUpperCase()+t.slice(1)]-o-u-s-.5))||0),u}function lt(e,t,n){var r=Qe(e),i=(!y.boxSizingReliable()||n)&&"border-box"===S.css(e,"boxSizing",!1,r),o=i,a=Ke(e,t,r),s="offset"+t[0].toUpperCase()+t.slice(1);if(Xe.test(a)){if(!n)return a;a="auto"}return(!y.boxSizingReliable()&&i||!y.reliableTrDimensions()&&A(e,"tr")||"auto"===a||!parseFloat(a)&&"inline"===S.css(e,"display",!1,r))&&e.getClientRects().length&&(i="border-box"===S.css(e,"boxSizing",!1,r),(o=s in e)&&(a=e[s])),(a=parseFloat(a)||0)+ut(e,t,n||(i?"border":"content"),o,r,a)+"px"}function ct(e,t,n,r,i){return new ct.prototype.init(e,t,n,r,i)}S.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Ke(e,"opacity");return"===n?"1":n}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,gridArea:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnStart:!0,gridRow:!0,gridRowEnd:!0,gridRowStart:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{},style:function(e,t,n,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,a,s=X(t),u=it.test(t),l=e.style;if(u||(t=nt(s)),a=S.cssHooks[t]||S.cssHooks[s],void 0===n)return a&&"get"in a&&void 0!==(i=a.get(e,!1,r))?i:l[t];"string"===(o=typeof n)&&(i=te.exec(n))&&i[1]&&(n=se(e,t,i),o="number"),null!=n&&n==n&&("number"!==o||u||(n+=i&&i[3]||(S.cssNumber[s]?":"px")),y.clearCloneStyle||"!==n||0!==t.indexOf("background")||(l[t]="inherit"),a&&"set"in a&&void 0===(n=a.set(e,n,r))||(u?l.setProperty(t,n):l[t]=n))}},css:function(e,t,n,r){var i,o,a,s=X(t);return it.test(t)||(t=nt(s)),(a=S.cssHooks[t]||S.cssHooks[s])&&"get"in a&&(i=a.get(e,!0,n)),void 0===i&&(i=Ke(e,t,r)),"normal"===i&&t in at&&(i=at[t]),"===n||n?(o=parseFloat(i),!0===n||isFinite(o)?o||0:i):i}}),S.each(["height","width"],function(e,u){S.cssHooks[u]={get:function(e,t,n){if(t)return!rt.test(S.css(e,"display"))||e.getClientRects().length&&e.getBoundingClientRect().width?lt(e,u,n):Me(e,ot,function(){return lt(e,u,n)})},set:function(e,t,n){var r,i=Qe(e),o=!y.scrollboxSize()&&"absolute"===i.position,a=(o||n)&&"border-box"===S.css(e,"boxSizing",!1,i),s=n?ut(e,u,n,a,i):0;return a&&o&&(s-=Math.ceil(e["offset"+u[0].toUpperCase()+u.slice(1)]-parseFloat(i[u])-ut(e,u,"border",!1,i)-.5)),s&&(r=te.exec(t))&&"px"!==(r[3]||"px")&&(e.style[u]=t,t=S.css(e,u)),st(0,t,s)}}}),S.cssHooks.marginLeft=Ze(y.reliableMarginLeft,function(e,t){if(t)return(parseFloat(Ke(e,"marginLeft"))||e.getBoundingClientRect().left-Me(e,{marginLeft:0},function(){return e.getBoundingClientRect().left}))+"px"}),S.each({margin:",padding:",border:"Width"},function(i,o){S.cssHooks[i+o]={expand:function(e){for(var t=0,n={},r="string"==typeof e?e.split(" "):[e];t<4;t++)n[i+ne[t]+o]=r[t]||r[t-2]||r[0];return n}},"margin"!==i&&(S.cssHooks[i+o].set=st)}),S.fn.extend({css:function(e,t){return F(this,function(e,t,n){var r,i,o={},a=0;if(Array.isArray(t)){for(r=Qe(e),i=t.length;a<i;a++)o[t[a]]=S.css(e,t[a],!1,r);return o}return void 0!==n?S.style(e,t,n):S.css(e,t)},e,t,1<arguments.length)}}),((S.Tween=ct).prototype={constructor:ct,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||S.easing._default,this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(S.cssNumber[n]?":"px")},cur:function(){var e=ct.propHooks[this.prop];return e&&e.get?e.get(this):ct.propHooks._default.get(this)},run:function(e){var t,n=ct.propHooks[this.prop];return this.options.duration?this.pos=t=S.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):ct.propHooks._default.set(this),this}}).init.prototype=ct.prototype,(ct.propHooks={_default:{get:function(e){var t;return 1!==e.elem.nodeType||null!=e.elem[e.prop]&&null==e.elem.style[e.prop]?e.elem[e.prop]:(t=S.css(e.elem,e.prop,"))&&"auto"!==t?t:0},set:function(e){S.fx.step[e.prop]?S.fx.step[e.prop](e):1!==e.elem.nodeType||!S.cssHooks[e.prop]&&null==e.elem.style[nt(e.prop)]?e.elem[e.prop]=e.now:S.style(e.elem,e.prop,e.now+e.unit)}}}).scrollTop=ct.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},S.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2},_default:"swing"},S.fx=ct.prototype.init,S.fx.step={};var ft,dt,pt,ht,mt=/^(?:toggle|show|hide)$/,gt=/queueHooks$/;function vt(){dt&&(!1===E.hidden&&T.requestAnimationFrame?T.requestAnimationFrame(vt):T.setTimeout(vt,S.fx.interval),S.fx.tick())}function yt(){return T.setTimeout(function(){ft=void 0}),ft=Date.now()}function bt(e,t){var n,r=0,i={height:e};for(t=t?1:0;r<4;r+=2-t)i["margin"+(n=ne[r])]=i["padding"+n]=e;return t&&(i.opacity=i.width=e),i}function xt(e,t,n){for(var r,i=(wt.tweeners[t]||[]).concat(wt.tweeners["*"]),o=0,a=i.length;o<a;o++)if(r=i[o].call(n,t,e))return r}function wt(o,e,t){var n,a,r=0,i=wt.prefilters.length,s=S.Deferred().always(function(){delete u.elem}),u=function(){if(a)return!1;for(var e=ft||yt(),t=Math.max(0,l.startTime+l.duration-e),n=1-(t/l.duration||0),r=0,i=l.tweens.length;r<i;r++)l.tweens[r].run(n);return s.notifyWith(o,[l,n,t]),n<1&&i?t:(i||s.notifyWith(o,[l,1,0]),s.resolveWith(o,[l]),!1)},l=s.promise({elem:o,props:S.extend({},e),opts:S.extend(!0,{specialEasing:{},easing:S.easing._default},t),originalProperties:e,originalOptions:t,startTime:ft||yt(),duration:t.duration,tweens:[],createTween:function(e,t){var n=S.Tween(o,l.opts,e,t,l.opts.specialEasing[e]||l.opts.easing);return l.tweens.push(n),n},stop:function(e){var t=0,n=e?l.tweens.length:0;if(a)return this;for(a=!0;t<n;t++)l.tweens[t].run(1);return e?(s.notifyWith(o,[l,1,0]),s.resolveWith(o,[l,e])):s.rejectWith(o,[l,e]),this}}),c=l.props;for(!function(e,t){var n,r,i,o,a;for(n in e)if(i=t[r=X(n)],o=e[n],Array.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),(a=S.cssHooks[r])&&"expand"in a)for(n in o=a.expand(o),delete e[r],o)n in e||(e[n]=o[n],t[n]=i);else t[r]=i}(c,l.opts.specialEasing);r<i;r++)if(n=wt.prefilters[r].call(l,o,c,l.opts))return b(n.stop)&&(S._queueHooks(l.elem,l.opts.queue).stop=n.stop.bind(n)),n;return S.map(c,xt,l),b(l.opts.start)&&l.opts.start.call(o,l),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always),S.fx.timer(S.extend(u,{elem:o,anim:l,queue:l.opts.queue})),l}S.Animation=S.extend(wt,{tweeners:{"*":[function(e,t){var n=this.createTween(e,t);return se(n.elem,e,te.exec(t),n),n}]},tweener:function(e,t){for(var n,r=0,i=(e=b(e)?(t=e,["*"]):e.match(H)).length;r<i;r++)n=e[r],wt.tweeners[n]=wt.tweeners[n]||[],wt.tweeners[n].unshift(t)},prefilters:[function(e,t,n){var r,i,o,a,s,u,l,c,f="width"in t||"height"in t,d=this,p={},h=e.style,m=e.nodeType&&ae(e),g=V.get(e,"fxshow");for(r in n.queue||(null==(a=S._queueHooks(e,"fx")).unqueued&&(a.unqueued=0,s=a.empty.fire,a.empty.fire=function(){a.unqueued||s()}),a.unqueued++,d.always(function(){d.always(function(){a.unqueued--,S.queue(e,"fx").length||a.empty.fire()})})),t)if(i=t[r],mt.test(i)){if(delete t[r],o=o||"toggle"===i,i===(m?"hide":"show")){if("show"!==i||!g||void 0===g[r])continue;m=!0}p[r]=g&&g[r]||S.style(e,r)}if((u=!S.isEmptyObject(t))||!S.isEmptyObject(p))for(r in f&&1===e.nodeType&&(n.overflow=[h.overflow,h.overflowX,h.overflowY],null==(l=g&&g.display)&&(l=V.get(e,"display")),"none"===(c=S.css(e,"display"))&&(l?c=l:(le([e],!0),l=e.style.display||l,c=S.css(e,"display"),le([e]))),("inline"===c||"inline-block"===c&&null!=l)&&"none"===S.css(e,"float")&&(u||(d.done(function(){h.display=l}),null==l&&(c=h.display,l="none"===c?":c)),h.display="inline-block")),n.overflow&&(h.overflow="hidden",d.always(function(){h.overflow=n.overflow[0],h.overflowX=n.overflow[1],h.overflowY=n.overflow[2]})),u=!1,p)u||(g?"hidden"in g&&(m=g.hidden):g=V.access(e,"fxshow",{display:l}),o&&(g.hidden=!m),m&&le([e],!0),d.done(function(){for(r in m||le([e]),V.remove(e,"fxshow"),p)S.style(e,r,p[r])})),u=xt(m?g[r]:0,r,d),r in g||(g[r]=u.start,m&&(u.end=u.start,u.start=0))}],prefilter:function(e,t){t?wt.prefilters.unshift(e):wt.prefilters.push(e)}}),S.speed=function(e,t,n){var r=e&&"object"==typeof e?S.extend({},e):{complete:n||!n&&t||b(e)&&e,duration:e,easing:n&&t||t&&!b(t)&&t};return S.fx.off?r.duration=0:"number"!=typeof r.duration&&(r.duration in S.fx.speeds?r.duration=S.fx.speeds[r.duration]:r.duration=S.fx.speeds._default),null!=r.queue&&!0!==r.queue||(r.queue="fx"),r.old=r.complete,r.complete=function(){b(r.old)&&r.old.call(this),r.queue&&S.dequeue(this,r.queue)},r},S.fn.extend({fadeTo:function(e,t,n,r){return this.filter(ae).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(t,e,n,r){function i(){var e=wt(this,S.extend({},t),a);(o||V.get(this,"finish"))&&e.stop(!0)}var o=S.isEmptyObject(t),a=S.speed(e,n,r);return i.finish=i,o||!1===a.queue?this.each(i):this.queue(a.queue,i)},stop:function(i,e,o){function a(e){var t=e.stop;delete e.stop,t(o)}return"string"!=typeof i&&(o=e,e=i,i=void 0),e&&this.queue(i||"fx",[]),this.each(function(){var e=!0,t=null!=i&&i+"queueHooks",n=S.timers,r=V.get(this);if(t)r[t]&&r[t].stop&&a(r[t]);else for(t in r)r[t]&&r[t].stop&&gt.test(t)&&a(r[t]);for(t=n.length;t--;)n[t].elem!==this||null!=i&&n[t].queue!==i||(n[t].anim.stop(o),e=!1,n.splice(t,1));!e&&o||S.dequeue(this,i)})},finish:function(a){return!1!==a&&(a=a||"fx"),this.each(function(){var e,t=V.get(this),n=t[a+"queue"],r=t[a+"queueHooks"],i=S.timers,o=n?n.length:0;for(t.finish=!0,S.queue(this,a,[]),r&&r.stop&&r.stop.call(this,!0),e=i.length;e--;)i[e].elem===this&&i[e].queue===a&&(i[e].anim.stop(!0),i.splice(e,1));for(e=0;e<o;e++)n[e]&&n[e].finish&&n[e].finish.call(this);delete t.finish})}}),S.each(["toggle","show","hide"],function(e,r){var i=S.fn[r];S.fn[r]=function(e,t,n){return null==e||"boolean"==typeof e?i.apply(this,arguments):this.animate(bt(r,!0),e,t,n)}}),S.each({slideDown:bt("show"),slideUp:bt("hide"),slideToggle:bt("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,r){S.fn[e]=function(e,t,n){return this.animate(r,e,t,n)}}),S.timers=[],S.fx.tick=function(){var e,t=0,n=S.timers;for(ft=Date.now();t<n.length;t++)(e=n[t])()||n[t]!==e||n.splice(t--,1);n.length||S.fx.stop(),ft=void 0},S.fx.timer=function(e){S.timers.push(e),S.fx.start()},S.fx.interval=13,S.fx.start=function(){dt||(dt=!0,vt())},S.fx.stop=function(){dt=null},S.fx.speeds={slow:600,fast:200,_default:400},S.fn.delay=function(r,e){return r=S.fx&&S.fx.speeds[r]||r,e=e||"fx",this.queue(e,function(e,t){var n=T.setTimeout(e,r);t.stop=function(){T.clearTimeout(n)}})},pt=E.createElement("input"),ht=E.createElement("select").appendChild(E.createElement("option")),pt.type="checkbox",y.checkOn="!==pt.value,y.optSelected=ht.selected,(pt=E.createElement("input")).value="t",pt.type="radio",y.radioValue="t"===pt.value;var Ct,Tt=S.expr.attrHandle;S.fn.extend({attr:function(e,t){return F(this,S.attr,e,t,1<arguments.length)},removeAttr:function(e){return this.each(function(){S.removeAttr(this,e)})}}),S.extend({attr:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return void 0===e.getAttribute?S.prop(e,t,n):(1===o&&S.isXMLDoc(e)||(i=S.attrHooks[t.toLowerCase()]||(S.expr.match.bool.test(t)?Ct:void 0)),void 0!==n?null===n?void S.removeAttr(e,t):i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:(e.setAttribute(t,n+"),n):!(i&&"get"in i&&null!==(r=i.get(e,t)))&&null==(r=S.find.attr(e,t))?void 0:r)},attrHooks:{type:{set:function(e,t){if(!y.radioValue&&"radio"===t&&A(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},removeAttr:function(e,t){var n,r=0,i=t&&t.match(H);if(i&&1===e.nodeType)for(;n=i[r++];)e.removeAttribute(n)}}),Ct={set:function(e,t,n){return!1===t?S.removeAttr(e,n):e.setAttribute(n,n),n}},S.each(S.expr.match.bool.source.match(/\w+/g),function(e,t){var a=Tt[t]||S.find.attr;Tt[t]=function(e,t,n){var r,i,o=t.toLowerCase();return n||(i=Tt[o],Tt[o]=r,r=null!=a(e,t,n)?o:null,Tt[o]=i),r}});var Et=/^(?:input|select|textarea|button)$/i,St=/^(?:a|area)$/i;function kt(e){return(e.match(H)||[]).join(" ")}function At(e){return e.getAttribute&&e.getAttribute("class")||"}function Nt(e){return Array.isArray(e)?e:"string"==typeof e&&e.match(H)||[]}S.fn.extend({prop:function(e,t){return F(this,S.prop,e,t,1<arguments.length)},removeProp:function(e){return this.each(function(){delete this[S.propFix[e]||e]})}}),S.extend({prop:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return 1===o&&S.isXMLDoc(e)||(t=S.propFix[t]||t,i=S.propHooks[t]),void 0!==n?i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){var t=S.find.attr(e,"tabindex");return t?parseInt(t,10):Et.test(e.nodeName)||St.test(e.nodeName)&&e.href?0:-1}}},propFix:{for:"htmlFor",class:"className"}}),y.optSelected||(S.propHooks.selected={get:function(e){var t=e.parentNode;return t&&t.parentNode&&t.parentNode.selectedIndex,null},set:function(e){var t=e.parentNode;t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex)}}),S.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){S.propFix[this.toLowerCase()]=this}),S.fn.extend({addClass:function(t){var e,n,r,i,o,a,s,u=0;if(b(t))return this.each(function(e){S(this).addClass(t.call(this,e,At(this)))});if((e=Nt(t)).length)for(;n=this[u++];)if(i=At(n),r=1===n.nodeType&&" "+kt(i)+" "){for(a=0;o=e[a++];)r.indexOf(" "+o+" ")<0&&(r+=o+" ");i!==(s=kt(r))&&n.setAttribute("class",s)}return this},removeClass:function(t){var e,n,r,i,o,a,s,u=0;if(b(t))return this.each(function(e){S(this).removeClass(t.call(this,e,At(this)))});if(!arguments.length)return this.attr("class",");if((e=Nt(t)).length)for(;n=this[u++];)if(i=At(n),r=1===n.nodeType&&" "+kt(i)+" "){for(a=0;o=e[a++];)for(;-1<r.indexOf(" "+o+" ");)r=r.replace(" "+o+" "," ");i!==(s=kt(r))&&n.setAttribute("class",s)}return this},toggleClass:function(i,t){var o=typeof i,a="string"==o||Array.isArray(i);return"boolean"==typeof t&&a?t?this.addClass(i):this.removeClass(i):b(i)?this.each(function(e){S(this).toggleClass(i.call(this,e,At(this),t),t)}):this.each(function(){var e,t,n,r;if(a)for(t=0,n=S(this),r=Nt(i);e=r[t++];)n.hasClass(e)?n.removeClass(e):n.addClass(e);else void 0!==i&&"boolean"!=o||((e=At(this))&&V.set(this,"__className__",e),this.setAttribute&&this.setAttribute("class",!e&&!1!==i&&V.get(this,"__className__")||"))})},hasClass:function(e){var t,n,r=0;for(t=" "+e+" ";n=this[r++];)if(1===n.nodeType&&-1<(" "+kt(At(n))+" ").indexOf(t))return!0;return!1}});var jt=/\r/g;S.fn.extend({val:function(n){var r,e,i,t=this[0];return arguments.length?(i=b(n),this.each(function(e){var t;1===this.nodeType&&(null==(t=i?n.call(this,e,S(this).val()):n)?t=":"number"==typeof t?t+=":Array.isArray(t)&&(t=S.map(t,function(e){return null==e?":e+"})),(r=S.valHooks[this.type]||S.valHooks[this.nodeName.toLowerCase()])&&"set"in r&&void 0!==r.set(this,t,"value")||(this.value=t))})):t?(r=S.valHooks[t.type]||S.valHooks[t.nodeName.toLowerCase()])&&"get"in r&&void 0!==(e=r.get(t,"value"))?e:"string"==typeof(e=t.value)?e.replace(jt,"):null==e?":e:void 0}}),S.extend({valHooks:{option:{get:function(e){var t=S.find.attr(e,"value");return null!=t?t:kt(S.text(e))}},select:{get:function(e){var t,n,r,i=e.options,o=e.selectedIndex,a="select-one"===e.type,s=a?null:[],u=a?o+1:i.length;for(r=o<0?u:a?o:0;r<u;r++)if(((n=i[r]).selected||r===o)&&!n.disabled&&(!n.parentNode.disabled||!A(n.parentNode,"optgroup"))){if(t=S(n).val(),a)return t;s.push(t)}return s},set:function(e,t){for(var n,r,i=e.options,o=S.makeArray(t),a=i.length;a--;)((r=i[a]).selected=-1<S.inArray(S.valHooks.option.get(r),o))&&(n=!0);return n||(e.selectedIndex=-1),o}}}}),S.each(["radio","checkbox"],function(){S.valHooks[this]={set:function(e,t){if(Array.isArray(t))return e.checked=-1<S.inArray(S(e).val(),t)}},y.checkOn||(S.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})}),y.focusin="onfocusin"in T;function It(e){e.stopPropagation()}var Lt=/^(?:focusinfocus|focusoutblur)$/;S.extend(S.event,{trigger:function(e,t,n,r){var i,o,a,s,u,l,c,f,d=[n||E],p=v.call(e,"type")?e.type:e,h=v.call(e,"namespace")?e.namespace.split("."):[];if(o=f=a=n=n||E,3!==n.nodeType&&8!==n.nodeType&&!Lt.test(p+S.event.triggered)&&(-1<p.indexOf(".")&&(p=(h=p.split(".")).shift(),h.sort()),u=p.indexOf(":")<0&&"on"+p,(e=e[S.expando]?e:new S.Event(p,"object"==typeof e&&e)).isTrigger=r?2:3,e.namespace=h.join("."),e.rnamespace=e.namespace?new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,e.result=void 0,e.target||(e.target=n),t=null==t?[e]:S.makeArray(t,[e]),c=S.event.special[p]||{},r||!c.trigger||!1!==c.trigger.apply(n,t))){if(!r&&!c.noBubble&&!m(n)){for(s=c.delegateType||p,Lt.test(s+p)||(o=o.parentNode);o;o=o.parentNode)d.push(o),a=o;a===(n.ownerDocument||E)&&d.push(a.defaultView||a.parentWindow||T)}for(i=0;(o=d[i++])&&!e.isPropagationStopped();)f=o,e.type=1<i?s:c.bindType||p,(l=(V.get(o,"events")||Object.create(null))[e.type]&&V.get(o,"handle"))&&l.apply(o,t),(l=u&&o[u])&&l.apply&&Q(o)&&(e.result=l.apply(o,t),!1===e.result&&e.preventDefault());return e.type=p,r||e.isDefaultPrevented()||c._default&&!1!==c._default.apply(d.pop(),t)||!Q(n)||u&&b(n[p])&&!m(n)&&((a=n[u])&&(n[u]=null),S.event.triggered=p,e.isPropagationStopped()&&f.addEventListener(p,It),n[p](),e.isPropagationStopped()&&f.removeEventListener(p,It),S.event.triggered=void 0,a&&(n[u]=a)),e.result}},simulate:function(e,t,n){var r=S.extend(new S.Event,n,{type:e,isSimulated:!0});S.event.trigger(r,null,t)}}),S.fn.extend({trigger:function(e,t){return this.each(function(){S.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];if(n)return S.event.trigger(e,t,n,!0)}}),y.focusin||S.each({focus:"focusin",blur:"focusout"},function(n,r){function i(e){S.event.simulate(r,e.target,S.event.fix(e))}S.event.special[r]={setup:function(){var e=this.ownerDocument||this.document||this,t=V.access(e,r);t||e.addEventListener(n,i,!0),V.access(e,r,(t||0)+1)},teardown:function(){var e=this.ownerDocument||this.document||this,t=V.access(e,r)-1;t?V.access(e,r,t):(e.removeEventListener(n,i,!0),V.remove(e,r))}}});var Dt=T.location,Ot={guid:Date.now()},Pt=/\?/;S.parseXML=function(e){var t;if(!e||"string"!=typeof e)return null;try{t=(new T.DOMParser).parseFromString(e,"text/xml")}catch(e){t=void 0}return t&&!t.getElementsByTagName("parsererror").length||S.error("Invalid XML: "+e),t};var Ht=/\[\]$/,qt=/\r?\n/g,Mt=/^(?:submit|button|image|reset|file)$/i,_t=/^(?:input|select|textarea|keygen)/i;function $t(n,e,r,i){var t;if(Array.isArray(e))S.each(e,function(e,t){r||Ht.test(n)?i(n,t):$t(n+"["+("object"==typeof t&&null!=t?e:")+"]",t,r,i)});else if(r||"object"!==w(e))i(n,e);else for(t in e)$t(n+"["+t+"]",e[t],r,i)}S.param=function(e,t){function n(e,t){var n=b(t)?t():t;i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(null==n?":n)}var r,i=[];if(null==e)return";if(Array.isArray(e)||e.jquery&&!S.isPlainObject(e))S.each(e,function(){n(this.name,this.value)});else for(r in e)$t(r,e[r],t,n);return i.join("&")},S.fn.extend({serialize:function(){return S.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=S.prop(this,"elements");return e?S.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!S(this).is(":disabled")&&_t.test(this.nodeName)&&!Mt.test(e)&&(this.checked||!de.test(e))}).map(function(e,t){var n=S(this).val();return null==n?null:Array.isArray(n)?S.map(n,function(e){return{name:t.name,value:e.replace(qt,"\r\n")}}):{name:t.name,value:n.replace(qt,"\r\n")}}).get()}});var Rt=/%20/g,Bt=/#.*$/,Ft=/([?&])_=[^&]*/,zt=/^(.*?):[ \t]*([^\r\n]*)$/gm,Wt=/^(?:GET|HEAD)$/,Ut=/^\/\//,Xt={},Qt={},Yt="*/".concat("*"),Vt=E.createElement("a");function Gt(o){return function(e,t){"string"!=typeof e&&(t=e,e="*");var n,r=0,i=e.toLowerCase().match(H)||[];if(b(t))for(;n=i[r++];)"+"===n[0]?(n=n.slice(1)||"*",(o[n]=o[n]||[]).unshift(t)):(o[n]=o[n]||[]).push(t)}}function Kt(t,i,o,a){var s={},u=t===Qt;function l(e){var r;return s[e]=!0,S.each(t[e]||[],function(e,t){var n=t(i,o,a);return"string"!=typeof n||u||s[n]?u?!(r=n):void 0:(i.dataTypes.unshift(n),l(n),!1)}),r}return l(i.dataTypes[0])||!s["*"]&&l("*")}function Zt(e,t){var n,r,i=S.ajaxSettings.flatOptions||{};for(n in t)void 0!==t[n]&&((i[n]?e:r=r||{})[n]=t[n]);return r&&S.extend(!0,e,r),e}Vt.href=Dt.href,S.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Dt.href,type:"GET",isLocal:/^(?:about|app|app-storage|.+-extension|file|res|widget):$/.test(Dt.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Yt,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":JSON.parse,"text xml":S.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?Zt(Zt(e,S.ajaxSettings),t):Zt(S.ajaxSettings,e)},ajaxPrefilter:Gt(Xt),ajaxTransport:Gt(Qt),ajax:function(e,t){"object"==typeof e&&(t=e,e=void 0),t=t||{};var c,f,d,n,p,r,h,m,i,o,g=S.ajaxSetup({},t),v=g.context||g,y=g.context&&(v.nodeType||v.jquery)?S(v):S.event,b=S.Deferred(),x=S.Callbacks("once memory"),w=g.statusCode||{},a={},s={},u="canceled",C={readyState:0,getResponseHeader:function(e){var t;if(h){if(!n)for(n={};t=zt.exec(d);)n[t[1].toLowerCase()+" "]=(n[t[1].toLowerCase()+" "]||[]).concat(t[2]);t=n[e.toLowerCase()+" "]}return null==t?null:t.join(", ")},getAllResponseHeaders:function(){return h?d:null},setRequestHeader:function(e,t){return null==h&&(e=s[e.toLowerCase()]=s[e.toLowerCase()]||e,a[e]=t),this},overrideMimeType:function(e){return null==h&&(g.mimeType=e),this},statusCode:function(e){var t;if(e)if(h)C.always(e[C.status]);else for(t in e)w[t]=[w[t],e[t]];return this},abort:function(e){var t=e||u;return c&&c.abort(t),l(0,t),this}};if(b.promise(C),g.url=((e||g.url||Dt.href)+").replace(Ut,Dt.protocol+"//"),g.type=t.method||t.type||g.method||g.type,g.dataTypes=(g.dataType||"*").toLowerCase().match(H)||["],null==g.crossDomain){r=E.createElement("a");try{r.href=g.url,r.href=r.href,g.crossDomain=Vt.protocol+"//"+Vt.host!=r.protocol+"//"+r.host}catch(e){g.crossDomain=!0}}if(g.data&&g.processData&&"string"!=typeof g.data&&(g.data=S.param(g.data,g.traditional)),Kt(Xt,g,t,C),h)return C;for(i in(m=S.event&&g.global)&&0==S.active++&&S.event.trigger("ajaxStart"),g.type=g.type.toUpperCase(),g.hasContent=!Wt.test(g.type),f=g.url.replace(Bt,"),g.hasContent?g.data&&g.processData&&0===(g.contentType||").indexOf("application/x-www-form-urlencoded")&&(g.data=g.data.replace(Rt,"+")):(o=g.url.slice(f.length),g.data&&(g.processData||"string"==typeof g.data)&&(f+=(Pt.test(f)?"&":"?")+g.data,delete g.data),!1===g.cache&&(f=f.replace(Ft,"$1"),o=(Pt.test(f)?"&":"?")+"_="+Ot.guid+++o),g.url=f+o),g.ifModified&&(S.lastModified[f]&&C.setRequestHeader("If-Modified-Since",S.lastModified[f]),S.etag[f]&&C.setRequestHeader("If-None-Match",S.etag[f])),(g.data&&g.hasContent&&!1!==g.contentType||t.contentType)&&C.setRequestHeader("Content-Type",g.contentType),C.setRequestHeader("Accept",g.dataTypes[0]&&g.accepts[g.dataTypes[0]]?g.accepts[g.dataTypes[0]]+("*"!==g.dataTypes[0]?", "+Yt+"; q=0.01":"):g.accepts["*"]),g.headers)C.setRequestHeader(i,g.headers[i]);if(g.beforeSend&&(!1===g.beforeSend.call(v,C,g)||h))return C.abort();if(u="abort",x.add(g.complete),C.done(g.success),C.fail(g.error),c=Kt(Qt,g,t,C)){if(C.readyState=1,m&&y.trigger("ajaxSend",[C,g]),h)return C;g.async&&0<g.timeout&&(p=T.setTimeout(function(){C.abort("timeout")},g.timeout));try{h=!1,c.send(a,l)}catch(e){if(h)throw e;l(-1,e)}}else l(-1,"No Transport");function l(e,t,n,r){var i,o,a,s,u,l=t;h||(h=!0,p&&T.clearTimeout(p),c=void 0,d=r||",C.readyState=0<e?4:0,i=200<=e&&e<300||304===e,n&&(s=function(e,t,n){for(var r,i,o,a,s=e.contents,u=e.dataTypes;"*"===u[0];)u.shift(),void 0===r&&(r=e.mimeType||t.getResponseHeader("Content-Type"));if(r)for(i in s)if(s[i]&&s[i].test(r)){u.unshift(i);break}if(u[0]in n)o=u[0];else{for(i in n){if(!u[0]||e.converters[i+" "+u[0]]){o=i;break}a=a||i}o=o||a}if(o)return o!==u[0]&&u.unshift(o),n[o]}(g,C,n)),!i&&-1<S.inArray("script",g.dataTypes)&&(g.converters["text script"]=function(){}),s=function(e,t,n,r){var i,o,a,s,u,l={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)l[a.toLowerCase()]=e.converters[a];for(o=c.shift();o;)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!u&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u=o,o=c.shift())if("*"===o)o=u;else if("*"!==u&&u!==o){if(!(a=l[u+" "+o]||l["* "+o]))for(i in l)if((s=i.split(" "))[1]===o&&(a=l[u+" "+s[0]]||l["* "+s[0]])){!0===a?a=l[i]:!0!==l[i]&&(o=s[0],c.unshift(s[1]));break}if(!0!==a)if(a&&e.throws)t=a(t);else try{t=a(t)}catch(e){return{state:"parsererror",error:a?e:"No conversion from "+u+" to "+o}}}return{state:"success",data:t}}(g,s,C,i),i?(g.ifModified&&((u=C.getResponseHeader("Last-Modified"))&&(S.lastModified[f]=u),(u=C.getResponseHeader("etag"))&&(S.etag[f]=u)),204===e||"HEAD"===g.type?l="nocontent":304===e?l="notmodified":(l=s.state,o=s.data,i=!(a=s.error))):(a=l,!e&&l||(l="error",e<0&&(e=0))),C.status=e,C.statusText=(t||l)+",i?b.resolveWith(v,[o,l,C]):b.rejectWith(v,[C,l,a]),C.statusCode(w),w=void 0,m&&y.trigger(i?"ajaxSuccess":"ajaxError",[C,g,i?o:a]),x.fireWith(v,[C,l]),m&&(y.trigger("ajaxComplete",[C,g]),--S.active||S.event.trigger("ajaxStop")))}return C},getJSON:function(e,t,n){return S.get(e,t,n,"json")},getScript:function(e,t){return S.get(e,void 0,t,"script")}}),S.each(["get","post"],function(e,i){S[i]=function(e,t,n,r){return b(t)&&(r=r||n,n=t,t=void 0),S.ajax(S.extend({url:e,type:i,dataType:r,data:t,success:n},S.isPlainObject(e)&&e))}}),S.ajaxPrefilter(function(e){var t;for(t in e.headers)"content-type"===t.toLowerCase()&&(e.contentType=e.headers[t]||")}),S._evalUrl=function(e,t,n){return S.ajax({url:e,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,converters:{"text script":function(){}},dataFilter:function(e){S.globalEval(e,t,n)}})},S.fn.extend({wrapAll:function(e){var t;return this[0]&&(b(e)&&(e=e.call(this[0])),t=S(e,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){for(var e=this;e.firstElementChild;)e=e.firstElementChild;return e}).append(this)),this},wrapInner:function(n){return b(n)?this.each(function(e){S(this).wrapInner(n.call(this,e))}):this.each(function(){var e=S(this),t=e.contents();t.length?t.wrapAll(n):e.append(n)})},wrap:function(t){var n=b(t);return this.each(function(e){S(this).wrapAll(n?t.call(this,e):t)})},unwrap:function(e){return this.parent(e).not("body").each(function(){S(this).replaceWith(this.childNodes)}),this}}),S.expr.pseudos.hidden=function(e){return!S.expr.pseudos.visible(e)},S.expr.pseudos.visible=function(e){return!!(e.offsetWidth||e.offsetHeight||e.getClientRects().length)},S.ajaxSettings.xhr=function(){try{return new T.XMLHttpRequest}catch(e){}};var Jt={0:200,1223:204},en=S.ajaxSettings.xhr();y.cors=!!en&&"withCredentials"in en,y.ajax=en=!!en,S.ajaxTransport(function(i){var o,a;if(y.cors||en&&!i.crossDomain)return{send:function(e,t){var n,r=i.xhr();if(r.open(i.type,i.url,i.async,i.username,i.password),i.xhrFields)for(n in i.xhrFields)r[n]=i.xhrFields[n];for(n in i.mimeType&&r.overrideMimeType&&r.overrideMimeType(i.mimeType),i.crossDomain||e["X-Requested-With"]||(e["X-Requested-With"]="XMLHttpRequest"),e)r.setRequestHeader(n,e[n]);o=function(e){return function(){o&&(o=a=r.onload=r.onerror=r.onabort=r.ontimeout=r.onreadystatechange=null,"abort"===e?r.abort():"error"===e?"number"!=typeof r.status?t(0,"error"):t(r.status,r.statusText):t(Jt[r.status]||r.status,r.statusText,"text"!==(r.responseType||"text")||"string"!=typeof r.responseText?{binary:r.response}:{text:r.responseText},r.getAllResponseHeaders()))}},r.onload=o(),a=r.onerror=r.ontimeout=o("error"),void 0!==r.onabort?r.onabort=a:r.onreadystatechange=function(){4===r.readyState&&T.setTimeout(function(){o&&a()})},o=o("abort");try{r.send(i.hasContent&&i.data||null)}catch(e){if(o)throw e}},abort:function(){o&&o()}}}),S.ajaxPrefilter(function(e){e.crossDomain&&(e.contents.script=!1)}),S.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(e){return S.globalEval(e),e}}}),S.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET")}),S.ajaxTransport("script",function(n){var r,i;if(n.crossDomain||n.scriptAttrs)return{send:function(e,t){r=S("<script>").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),E.head.appendChild(r[0])},abort:function(){i&&i()}}});var tn,nn=[],rn=/(=)\?(?=&|$)|\?\?/;S.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=nn.pop()||S.expando+"_"+Ot.guid++;return this[e]=!0,e}}),S.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(rn.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||").indexOf("application/x-www-form-urlencoded")&&rn.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=b(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(rn,"$1"+r):!1!==e.jsonp&&(e.url+=(Pt.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||S.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=T[r],T[r]=function(){o=arguments},n.always(function(){void 0===i?S(T).removeProp(r):T[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,nn.push(r)),o&&b(i)&&i(o[0]),o=i=void 0}),"script"}),y.createHTMLDocument=((tn=E.implementation.createHTMLDocument(").body).innerHTML="<form></form><form></form>",2===tn.childNodes.length),S.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(y.createHTMLDocument?((r=(t=E.implementation.createHTMLDocument(")).createElement("base")).href=E.location.href,t.head.appendChild(r)):t=E),o=!n&&[],(i=N.exec(e))?[t.createElement(i[1])]:(i=be([e],t,o),o&&o.length&&S(o).remove(),S.merge([],i.childNodes)));var r,i,o},S.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1<s&&(r=kt(e.slice(s)),e=e.slice(0,s)),b(t)?(n=t,t=void 0):t&&"object"==typeof t&&(i="POST"),0<a.length&&S.ajax({url:e,type:i||"GET",dataType:"html",data:t}).done(function(e){o=arguments,a.html(r?S("<div>").append(S.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},S.expr.pseudos.animated=function(t){return S.grep(S.timers,function(e){return t===e.elem}).length},S.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=S.css(e,"position"),c=S(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=S.css(e,"top"),u=S.css(e,"left"),i=("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,r.left):(a=parseFloat(o)||0,parseFloat(u)||0),b(t)&&(t=t.call(e,n,S.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):("number"==typeof f.top&&(f.top+="px"),"number"==typeof f.left&&(f.left+="px"),c.css(f))}},S.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){S.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===S.css(r,"position"))t=r.getBoundingClientRect();else{for(t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;e&&(e===n.body||e===n.documentElement)&&"static"===S.css(e,"position");)e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=S(e).offset()).top+=S.css(e,"borderTopWidth",!0),i.left+=S.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-S.css(r,"marginTop",!0),left:t.left-i.left-S.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var e=this.offsetParent;e&&"static"===S.css(e,"position");)e=e.offsetParent;return e||re})}}),S.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;S.fn[t]=function(e){return F(this,function(e,t,n){var r;if(m(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),S.each(["top","left"],function(e,n){S.cssHooks[n]=Ze(y.pixelPosition,function(e,t){if(t)return t=Ke(e,n),Xe.test(t)?S(e).position()[n]+"px":t})}),S.each({Height:"height",Width:"width"},function(a,s){S.each({padding:"inner"+a,content:s,":"outer"+a},function(r,o){S.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return F(this,function(e,t,n){var r;return m(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?S.css(e,t,i):S.style(e,t,n,i)},s,n?e:void 0,n)}})}),S.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){S.fn[t]=function(e){return this.on(t,e)}}),S.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),S.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){S.fn[n]=function(e,t){return 0<arguments.length?this.on(n,null,e,t):this.trigger(n)}});var on=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;S.proxy=function(e,t){var n,r,i;if("string"==typeof t&&(n=e[t],t=e,e=n),b(e))return r=s.call(arguments,2),(i=function(){return e.apply(t||this,r.concat(s.call(arguments)))}).guid=e.guid=e.guid||S.guid++,i},S.holdReady=function(e){e?S.readyWait++:S.ready(!0)},S.isArray=Array.isArray,S.parseJSON=JSON.parse,S.nodeName=A,S.isFunction=b,S.isWindow=m,S.camelCase=X,S.type=w,S.now=Date.now,S.isNumeric=function(e){var t=S.type(e);return("number"===t||"string"===t)&&!isNaN(e-parseFloat(e))},S.trim=function(e){return null==e?":(e+").replace(on,")},"function"==typeof define&&define.amd&&define("jquery",[],function(){return S});var an=T.jQuery,sn=T.$;return S.noConflict=function(e){return T.$===S&&(T.$=sn),e&&T.jQuery===S&&(T.jQuery=an),S},void 0===e&&(T.jQuery=T.$=S),S}),function(o){"use strict";o.fn.fitVids=function(e){var n={customSelector:null,ignore:null};if(!document.getElementById("fit-vids-style")){var t=document.head||document.getElementsByTagName("head")[0],r=document.createElement("div");r.innerHTML='<p>x</p><style id="fit-vids-style">.fluid-width-video-wrapper{width:100%;position:relative;padding:0;}.fluid-width-video-wrapper iframe,.fluid-width-video-wrapper object,.fluid-width-video-wrapper embed {position:absolute;top:0;left:0;width:100%;height:100%;}</style>',t.appendChild(r.childNodes[1])}return e&&o.extend(n,e),this.each(function(){var e=['iframe[src*="player.vimeo.com"]','iframe[src*="youtube.com"]','iframe[src*="youtube-nocookie.com"]','iframe[src*="kickstarter.com"][src*="video.html"]',"object","embed"];n.customSelector&&e.push(n.customSelector);var i=".fitvidsignore";n.ignore&&(i=i+", "+n.ignore);var t=o(this).find(e.join(","));(t=(t=t.not("object object")).not(i)).each(function(e){var t=o(this);if(!(0<t.parents(i).length||"embed"===this.tagName.toLowerCase()&&t.parent("object").length||t.parent(".fluid-width-video-wrapper").length)){t.css("height")||t.css("width")||!isNaN(t.attr("height"))&&!isNaN(t.attr("width"))||(t.attr("height",9),t.attr("width",16));var n=("object"===this.tagName.toLowerCase()||t.attr("height")&&!isNaN(parseInt(t.attr("height"),10))?parseInt(t.attr("height"),10):t.height())/(isNaN(parseInt(t.attr("width"),10))?t.width():parseInt(t.attr("width"),10));if(!t.attr("id")){var r="fitvid"+e;t.attr("id",r)}t.wrap('<div class="fluid-width-video-wrapper"></div>').parent(".fluid-width-video-wrapper").css("padding-top",100*n+"%"),t.removeAttr("height").removeAttr("width")}})})}}(window.jQuery||window.Zepto),$(function(){var r,i,e,o,t=$("nav.greedy-nav .greedy-nav__toggle"),a=$("nav.greedy-nav .visible-links"),s=$("nav.greedy-nav .hidden-links"),n=$("nav.greedy-nav"),u=$("nav.greedy-nav .site-logo"),l=$("nav.greedy-nav .site-logo img"),c=$("nav.greedy-nav .site-title"),f=$("nav.greedy-nav button.search__toggle");function d(){function n(e,t){i+=t,r+=1,o.push(i)}i=r=0,e=1e3,o=[],a.children().outerWidth(n),s.children().each(function(){var e,t;e=$(this),(t=e.clone()).css("visibility","hidden"),a.append(t),n(0,t.outerWidth()),t.remove()})}d();var p,h,m,g,v=$(window).width(),y=v<768?0:v<1024?1:v<1280?2:3;function b(){var e=(v=$(window).width())<768?0:v<1024?1:v<1280?2:3;e!==y&&d(),y=e,h=a.children().length,p=n.innerWidth()-(0!==u.length?u.outerWidth(!0):0)-c.outerWidth(!0)-(0!==f.length?f.outerWidth(!0):0)-(h!==o.length?t.outerWidth(!0):0),m=o[h-1],p<m?(a.children().last().prependTo(s),--h,b()):p+(h===o.length-1?t.outerWidth(!0):0)>o[h]&&(s.children().first().appendTo(a),h+=1,b()),t.attr("count",r-h),h===r?t.addClass("hidden"):t.removeClass("hidden")}$(window).resize(function(){b()}),t.on("click",function(){s.toggleClass("hidden"),clearTimeout(g)}),s.on("mouseleave",function(){g=setTimeout(function(){s.addClass("hidden")},e)}).on("mouseenter",function(){clearTimeout(g)}),0===l.length||l[0].complete||0!==l[0].naturalWidth?b():l.one("load error",b)}),function(e){"function"==typeof define&&define.amd?define(["jquery"],e):"object"==typeof exports?e(require("jquery")):e(window.jQuery||window.Zepto)}(function(c){function e(){}function f(e,t){m.ev.on("mfp"+e+x,t)}function d(e,t,n,r){var i=document.createElement("div");return i.className="mfp-"+e,n&&(i.innerHTML=n),r?t&&t.appendChild(i):(i=c(i),t&&i.appendTo(t)),i}function p(e,t){m.ev.triggerHandler("mfp"+e,t),m.st.callbacks&&(e=e.charAt(0).toLowerCase()+e.slice(1),m.st.callbacks[e]&&m.st.callbacks[e].apply(m,c.isArray(t)?t:[t]))}function h(e){return e===t&&m.currTemplate.closeBtn||(m.currTemplate.closeBtn=c(m.st.closeMarkup.replace("%title%",m.st.tClose)),t=e),m.currTemplate.closeBtn}function o(){c.magnificPopup.instance||((m=new e).init(),c.magnificPopup.instance=m)}var m,r,g,i,v,t,u="Close",l="BeforeClose",y="MarkupParse",b="Open",x=".mfp",w="mfp-ready",n="mfp-removing",a="mfp-prevent-close",s=!!window.jQuery,C=c(window);e.prototype={constructor:e,init:function(){var e=navigator.appVersion;m.isLowIE=m.isIE8=document.all&&!document.addEventListener,m.isAndroid=/android/gi.test(e),m.isIOS=/iphone|ipad|ipod/gi.test(e),m.supportsTransition=function(){var e=document.createElement("p").style,t=["ms","O","Moz","Webkit"];if(void 0!==e.transition)return!0;for(;t.length;)if(t.pop()+"Transition"in e)return!0;return!1}(),m.probablyMobile=m.isAndroid||m.isIOS||/(Opera Mini)|Kindle|webOS|BlackBerry|(Opera Mobi)|(Windows Phone)|IEMobile/i.test(navigator.userAgent),g=c(document),m.popupsCache={}},open:function(e){var t;if(!1===e.isObj){m.items=e.items.toArray(),m.index=0;var n,r=e.items;for(t=0;t<r.length;t++)if((n=r[t]).parsed&&(n=n.el[0]),n===e.el[0]){m.index=t;break}}else m.items=c.isArray(e.items)?e.items:[e.items],m.index=e.index||0;if(!m.isOpen){m.types=[],v=",e.mainEl&&e.mainEl.length?m.ev=e.mainEl.eq(0):m.ev=g,e.key?(m.popupsCache[e.key]||(m.popupsCache[e.key]={}),m.currTemplate=m.popupsCache[e.key]):m.currTemplate={},m.st=c.extend(!0,{},c.magnificPopup.defaults,e),m.fixedContentPos="auto"===m.st.fixedContentPos?!m.probablyMobile:m.st.fixedContentPos,m.st.modal&&(m.st.closeOnContentClick=!1,m.st.closeOnBgClick=!1,m.st.showCloseBtn=!1,m.st.enableEscapeKey=!1),m.bgOverlay||(m.bgOverlay=d("bg").on("click"+x,function(){m.close()}),m.wrap=d("wrap").attr("tabindex",-1).on("click"+x,function(e){m._checkIfClose(e.target)&&m.close()}),m.container=d("container",m.wrap)),m.contentContainer=d("content"),m.st.preloader&&(m.preloader=d("preloader",m.container,m.st.tLoading));var i=c.magnificPopup.modules;for(t=0;t<i.length;t++){var o=i[t];o=o.charAt(0).toUpperCase()+o.slice(1),m["init"+o].call(m)}p("BeforeOpen"),m.st.showCloseBtn&&(m.st.closeBtnInside?(f(y,function(e,t,n,r){n.close_replaceWith=h(r.type)}),v+=" mfp-close-btn-in"):m.wrap.append(h())),m.st.alignTop&&(v+=" mfp-align-top"),m.fixedContentPos?m.wrap.css({overflow:m.st.overflowY,overflowX:"hidden",overflowY:m.st.overflowY}):m.wrap.css({top:C.scrollTop(),position:"absolute"}),!1!==m.st.fixedBgPos&&("auto"!==m.st.fixedBgPos||m.fixedContentPos)||m.bgOverlay.css({height:g.height(),position:"absolute"}),m.st.enableEscapeKey&&g.on("keyup"+x,function(e){27===e.keyCode&&m.close()}),C.on("resize"+x,function(){m.updateSize()}),m.st.closeOnContentClick||(v+=" mfp-auto-cursor"),v&&m.wrap.addClass(v);var a=m.wH=C.height(),s={};if(m.fixedContentPos&&m._hasScrollBar(a)){var u=m._getScrollbarSize();u&&(s.marginRight=u)}m.fixedContentPos&&(m.isIE7?c("body, html").css("overflow","hidden"):s.overflow="hidden");var l=m.st.mainClass;return m.isIE7&&(l+=" mfp-ie7"),l&&m._addClassToMFP(l),m.updateItemHTML(),p("BuildControls"),c("html").css(s),m.bgOverlay.add(m.wrap).prependTo(m.st.prependTo||c(document.body)),m._lastFocusedEl=document.activeElement,setTimeout(function(){m.content?(m._addClassToMFP(w),m._setFocus()):m.bgOverlay.addClass(w),g.on("focusin"+x,m._onFocusIn)},16),m.isOpen=!0,m.updateSize(a),p(b),e}m.updateItemHTML()},close:function(){m.isOpen&&(p(l),m.isOpen=!1,m.st.removalDelay&&!m.isLowIE&&m.supportsTransition?(m._addClassToMFP(n),setTimeout(function(){m._close()},m.st.removalDelay)):m._close())},_close:function(){p(u);var e=n+" "+w+" ";if(m.bgOverlay.detach(),m.wrap.detach(),m.container.empty(),m.st.mainClass&&(e+=m.st.mainClass+" "),m._removeClassFromMFP(e),m.fixedContentPos){var t={marginRight:"};m.isIE7?c("body, html").css("overflow","):t.overflow=",c("html").css(t)}g.off("keyup.mfp focusin"+x),m.ev.off(x),m.wrap.attr("class","mfp-wrap").removeAttr("style"),m.bgOverlay.attr("class","mfp-bg"),m.container.attr("class","mfp-container"),!m.st.showCloseBtn||m.st.closeBtnInside&&!0!==m.currTemplate[m.currItem.type]||m.currTemplate.closeBtn&&m.currTemplate.closeBtn.detach(),m.st.autoFocusLast&&m._lastFocusedEl&&c(m._lastFocusedEl).focus(),m.currItem=null,m.content=null,m.currTemplate=null,m.prevHeight=0,p("AfterClose")},updateSize:function(e){if(m.isIOS){var t=document.documentElement.clientWidth/window.innerWidth,n=window.innerHeight*t;m.wrap.css("height",n),m.wH=n}else m.wH=e||C.height();m.fixedContentPos||m.wrap.css("height",m.wH),p("Resize")},updateItemHTML:function(){var e=m.items[m.index];m.contentContainer.detach(),m.content&&m.content.detach(),e.parsed||(e=m.parseEl(m.index));var t=e.type;if(p("BeforeChange",[m.currItem?m.currItem.type:",t]),m.currItem=e,!m.currTemplate[t]){var n=!!m.st[t]&&m.st[t].markup;p("FirstMarkupParse",n),m.currTemplate[t]=!n||c(n)}i&&i!==e.type&&m.container.removeClass("mfp-"+i+"-holder");var r=m["get"+t.charAt(0).toUpperCase()+t.slice(1)](e,m.currTemplate[t]);m.appendContent(r,t),e.preloaded=!0,p("Change",e),i=e.type,m.container.prepend(m.contentContainer),p("AfterChange")},appendContent:function(e,t){(m.content=e)?m.st.showCloseBtn&&m.st.closeBtnInside&&!0===m.currTemplate[t]?m.content.find(".mfp-close").length||m.content.append(h()):m.content=e:m.content=",p("BeforeAppend"),m.container.addClass("mfp-"+t+"-holder"),m.contentContainer.append(m.content)},parseEl:function(e){var t,n=m.items[e];if((n=n.tagName?{el:c(n)}:(t=n.type,{data:n,src:n.src})).el){for(var r=m.types,i=0;i<r.length;i++)if(n.el.hasClass("mfp-"+r[i])){t=r[i];break}n.src=n.el.attr("data-mfp-src"),n.src||(n.src=n.el.attr("href"))}return n.type=t||m.st.type||"inline",n.index=e,n.parsed=!0,m.items[e]=n,p("ElementParse",n),m.items[e]},addGroup:function(t,n){function e(e){e.mfpEl=this,m._openClick(e,t,n)}var r="click.magnificPopup";(n=n||{}).mainEl=t,n.items?(n.isObj=!0,t.off(r).on(r,e)):(n.isObj=!1,n.delegate?t.off(r).on(r,n.delegate,e):(n.items=t).off(r).on(r,e))},_openClick:function(e,t,n){if((void 0!==n.midClick?n.midClick:c.magnificPopup.defaults.midClick)||!(2===e.which||e.ctrlKey||e.metaKey||e.altKey||e.shiftKey)){var r=void 0!==n.disableOn?n.disableOn:c.magnificPopup.defaults.disableOn;if(r)if(c.isFunction(r)){if(!r.call(m))return!0}else if(C.width()<r)return!0;e.type&&(e.preventDefault(),m.isOpen&&e.stopPropagation()),n.el=c(e.mfpEl),n.delegate&&(n.items=t.find(n.delegate)),m.open(n)}},updateStatus:function(e,t){if(m.preloader){r!==e&&m.container.removeClass("mfp-s-"+r),t||"loading"!==e||(t=m.st.tLoading);var n={status:e,text:t};p("UpdateStatus",n),e=n.status,t=n.text,m.preloader.html(t),m.preloader.find("a").on("click",function(e){e.stopImmediatePropagation()}),m.container.addClass("mfp-s-"+e),r=e}},_checkIfClose:function(e){if(!c(e).hasClass(a)){var t=m.st.closeOnContentClick,n=m.st.closeOnBgClick;if(t&&n)return!0;if(!m.content||c(e).hasClass("mfp-close")||m.preloader&&e===m.preloader[0])return!0;if(e===m.content[0]||c.contains(m.content[0],e)){if(t)return!0}else if(n&&c.contains(document,e))return!0;return!1}},_addClassToMFP:function(e){m.bgOverlay.addClass(e),m.wrap.addClass(e)},_removeClassFromMFP:function(e){this.bgOverlay.removeClass(e),m.wrap.removeClass(e)},_hasScrollBar:function(e){return(m.isIE7?g.height():document.body.scrollHeight)>(e||C.height())},_setFocus:function(){(m.st.focus?m.content.find(m.st.focus).eq(0):m.wrap).focus()},_onFocusIn:function(e){if(e.target!==m.wrap[0]&&!c.contains(m.wrap[0],e.target))return m._setFocus(),!1},_parseMarkup:function(i,e,t){var o;t.data&&(e=c.extend(t.data,e)),p(y,[i,e,t]),c.each(e,function(e,t){if(void 0===t||!1===t)return!0;if(1<(o=e.split("_")).length){var n=i.find(x+"-"+o[0]);if(0<n.length){var r=o[1];"replaceWith"===r?n[0]!==t[0]&&n.replaceWith(t):"img"===r?n.is("img")?n.attr("src",t):n.replaceWith(c("<img>").attr("src",t).attr("class",n.attr("class"))):n.attr(o[1],t)}}else i.find(x+"-"+e).html(t)})},_getScrollbarSize:function(){if(void 0===m.scrollbarSize){var e=document.createElement("div");e.style.cssText="width: 99px; height: 99px; overflow: scroll; position: absolute; top: -9999px;",document.body.appendChild(e),m.scrollbarSize=e.offsetWidth-e.clientWidth,document.body.removeChild(e)}return m.scrollbarSize}},c.magnificPopup={instance:null,proto:e.prototype,modules:[],open:function(e,t){return o(),(e=e?c.extend(!0,{},e):{}).isObj=!0,e.index=t||0,this.instance.open(e)},close:function(){return c.magnificPopup.instance&&c.magnificPopup.instance.close()},registerModule:function(e,t){t.options&&(c.magnificPopup.defaults[e]=t.options),c.extend(this.proto,t.proto),this.modules.push(e)},defaults:{disableOn:0,key:null,midClick:!1,mainClass:",preloader:!0,focus:",closeOnContentClick:!1,closeOnBgClick:!0,closeBtnInside:!0,showCloseBtn:!0,enableEscapeKey:!0,modal:!1,alignTop:!1,removalDelay:0,prependTo:null,fixedContentPos:"auto",fixedBgPos:"auto",overflowY:"auto",closeMarkup:'<button title="%title%" type="button" class="mfp-close">&#215;</button>',tClose:"Close (Esc)",tLoading:"Loading...",autoFocusLast:!0}},c.fn.magnificPopup=function(e){o();var t=c(this);if("string"==typeof e)if("open"===e){var n,r=s?t.data("magnificPopup"):t[0].magnificPopup,i=parseInt(arguments[1],10)||0;n=r.items?r.items[i]:(n=t,r.delegate&&(n=n.find(r.delegate)),n.eq(i)),m._openClick({mfpEl:n},t,r)}else m.isOpen&&m[e].apply(m,Array.prototype.slice.call(arguments,1));else e=c.extend(!0,{},e),s?t.data("magnificPopup",e):t[0].magnificPopup=e,m.addGroup(t,e);return t};function T(){k&&(S.after(k.addClass(E)).detach(),k=null)}var E,S,k,A="inline";c.magnificPopup.registerModule(A,{options:{hiddenClass:"hide",markup:",tNotFound:"Content not found"},proto:{initInline:function(){m.types.push(A),f(u+"."+A,function(){T()})},getInline:function(e,t){if(T(),e.src){var n=m.st.inline,r=c(e.src);if(r.length){var i=r[0].parentNode;i&&i.tagName&&(S||(E=n.hiddenClass,S=d(E),E="mfp-"+E),k=r.after(S).detach().removeClass(E)),m.updateStatus("ready")}else m.updateStatus("error",n.tNotFound),r=c("<div>");return e.inlineElement=r}return m.updateStatus("ready"),m._parseMarkup(t,{},e),t}}});function N(){I&&c(document.body).removeClass(I)}function j(){N(),m.req&&m.req.abort()}var I,L="ajax";c.magnificPopup.registerModule(L,{options:{settings:null,cursor:"mfp-ajax-cur",tError:'<a href="%url%">The content</a> could not be loaded.'},proto:{initAjax:function(){m.types.push(L),I=m.st.ajax.cursor,f(u+"."+L,j),f("BeforeChange."+L,j)},getAjax:function(i){I&&c(document.body).addClass(I),m.updateStatus("loading");var e=c.extend({url:i.src,success:function(e,t,n){var r={data:e,xhr:n};p("ParseAjax",r),m.appendContent(c(r.data),L),i.finished=!0,N(),m._setFocus(),setTimeout(function(){m.wrap.addClass(w)},16),m.updateStatus("ready"),p("AjaxContentAdded")},error:function(){N(),i.finished=i.loadError=!0,m.updateStatus("error",m.st.ajax.tError.replace("%url%",i.src))}},m.st.ajax.settings);return m.req=c.ajax(e),"}}});var D;c.magnificPopup.registerModule("image",{options:{markup:'<div class="mfp-figure"><div class="mfp-close"></div><figure><div class="mfp-img"></div><figcaption><div class="mfp-bottom-bar"><div class="mfp-title"></div><div class="mfp-counter"></div></div></figcaption></figure></div>',cursor:"mfp-zoom-out-cur",titleSrc:"title",verticalFit:!0,tError:'<a href="%url%">The image</a> could not be loaded.'},proto:{initImage:function(){var e=m.st.image,t=".image";m.types.push("image"),f(b+t,function(){"image"===m.currItem.type&&e.cursor&&c(document.body).addClass(e.cursor)}),f(u+t,function(){e.cursor&&c(document.body).removeClass(e.cursor),C.off("resize"+x)}),f("Resize"+t,m.resizeImage),m.isLowIE&&f("AfterChange",m.resizeImage)},resizeImage:function(){var e=m.currItem;if(e&&e.img&&m.st.image.verticalFit){var t=0;m.isLowIE&&(t=parseInt(e.img.css("padding-top"),10)+parseInt(e.img.css("padding-bottom"),10)),e.img.css("max-height",m.wH-t)}},_onImageHasSize:function(e){e.img&&(e.hasSize=!0,D&&clearInterval(D),e.isCheckingImgSize=!1,p("ImageHasSize",e),e.imgHidden&&(m.content&&m.content.removeClass("mfp-loading"),e.imgHidden=!1))},findImageSize:function(t){var n=0,r=t.img[0],i=function(e){D&&clearInterval(D),D=setInterval(function(){0<r.naturalWidth?m._onImageHasSize(t):(200<n&&clearInterval(D),3===++n?i(10):40===n?i(50):100===n&&i(500))},e)};i(1)},getImage:function(e,t){var n=0,r=function(){e&&(e.img[0].complete?(e.img.off(".mfploader"),e===m.currItem&&(m._onImageHasSize(e),m.updateStatus("ready")),e.hasSize=!0,e.loaded=!0,p("ImageLoadComplete")):++n<200?setTimeout(r,100):i())},i=function(){e&&(e.img.off(".mfploader"),e===m.currItem&&(m._onImageHasSize(e),m.updateStatus("error",o.tError.replace("%url%",e.src))),e.hasSize=!0,e.loaded=!0,e.loadError=!0)},o=m.st.image,a=t.find(".mfp-img");if(a.length){var s=document.createElement("img");s.className="mfp-img",e.el&&e.el.find("img").length&&(s.alt=e.el.find("img").attr("alt")),e.img=c(s).on("load.mfploader",r).on("error.mfploader",i),s.src=e.src,a.is("img")&&(e.img=e.img.clone()),0<(s=e.img[0]).naturalWidth?e.hasSize=!0:s.width||(e.hasSize=!1)}return m._parseMarkup(t,{title:function(e){if(e.data&&void 0!==e.data.title)return e.data.title;var t=m.st.image.titleSrc;if(t){if(c.isFunction(t))return t.call(m,e);if(e.el)return e.el.attr(t)||"}return"}(e),img_replaceWith:e.img},e),m.resizeImage(),e.hasSize?(D&&clearInterval(D),e.loadError?(t.addClass("mfp-loading"),m.updateStatus("error",o.tError.replace("%url%",e.src))):(t.removeClass("mfp-loading"),m.updateStatus("ready"))):(m.updateStatus("loading"),e.loading=!0,e.hasSize||(e.imgHidden=!0,t.addClass("mfp-loading"),m.findImageSize(e))),t}}});var O;c.magnificPopup.registerModule("zoom",{options:{enabled:!1,easing:"ease-in-out",duration:300,opener:function(e){return e.is("img")?e:e.find("img")}},proto:{initZoom:function(){var e,o=m.st.zoom,t=".zoom";if(o.enabled&&m.supportsTransition){function n(e){var t=e.clone().removeAttr("style").removeAttr("class").addClass("mfp-animated-image"),n="all "+o.duration/1e3+"s "+o.easing,r={position:"fixed",zIndex:9999,left:0,top:0,"-webkit-backface-visibility":"hidden"},i="transition";return r["-webkit-"+i]=r["-moz-"+i]=r["-o-"+i]=r[i]=n,t.css(r),t}function r(){m.content.css("visibility","visible")}var i,a,s=o.duration;f("BuildControls"+t,function(){if(m._allowZoom()){if(clearTimeout(i),m.content.css("visibility","hidden"),!(e=m._getItemToZoom()))return void r();(a=n(e)).css(m._getOffset()),m.wrap.append(a),i=setTimeout(function(){a.css(m._getOffset(!0)),i=setTimeout(function(){r(),setTimeout(function(){a.remove(),e=a=null,p("ZoomAnimationEnded")},16)},s)},16)}}),f(l+t,function(){if(m._allowZoom()){if(clearTimeout(i),m.st.removalDelay=s,!e){if(!(e=m._getItemToZoom()))return;a=n(e)}a.css(m._getOffset(!0)),m.wrap.append(a),m.content.css("visibility","hidden"),setTimeout(function(){a.css(m._getOffset())},16)}}),f(u+t,function(){m._allowZoom()&&(r(),a&&a.remove(),e=null)})}},_allowZoom:function(){return"image"===m.currItem.type},_getItemToZoom:function(){return!!m.currItem.hasSize&&m.currItem.img},_getOffset:function(e){var t,n=(t=e?m.currItem.img:m.st.zoom.opener(m.currItem.el||m.currItem)).offset(),r=parseInt(t.css("padding-top"),10),i=parseInt(t.css("padding-bottom"),10);n.top-=c(window).scrollTop()-r;var o={width:t.width(),height:(s?t.innerHeight():t[0].offsetHeight)-i-r};return void 0===O&&(O=void 0!==document.createElement("p").style.MozTransform),O?o["-moz-transform"]=o.transform="translate("+n.left+"px,"+n.top+"px)":(o.left=n.left,o.top=n.top),o}}});function P(e){if(m.currTemplate[H]){var t=m.currTemplate[H].find("iframe");t.length&&(e||(t[0].src="//about:blank"),m.isIE8&&t.css("display",e?"block":"none"))}}var H="iframe";c.magnificPopup.registerModule(H,{options:{markup:'<div class="mfp-iframe-scaler"><div class="mfp-close"></div><iframe class="mfp-iframe" src="//about:blank" frameborder="0" allowfullscreen></iframe></div>',srcAction:"iframe_src",patterns:{youtube:{index:"youtube.com",id:"v=",src:"//www.youtube.com/embed/%id%?autoplay=1"},vimeo:{index:"vimeo.com/",id:"/",src:"//player.vimeo.com/video/%id%?autoplay=1"},gmaps:{index:"//maps.google.",src:"%id%&output=embed"}}},proto:{initIframe:function(){m.types.push(H),f("BeforeChange",function(e,t,n){t!==n&&(t===H?P():n===H&&P(!0))}),f(u+"."+H,function(){P()})},getIframe:function(e,t){var n=e.src,r=m.st.iframe;c.each(r.patterns,function(){if(-1<n.indexOf(this.index))return this.id&&(n="string"==typeof this.id?n.substr(n.lastIndexOf(this.id)+this.id.length,n.length):this.id.call(this,n)),n=this.src.replace("%id%",n),!1});var i={};return r.srcAction&&(i[r.srcAction]=n),m._parseMarkup(t,i,e),m.updateStatus("ready"),t}}});function q(e){var t=m.items.length;return t-1<e?e-t:e<0?t+e:e}function M(e,t,n){return e.replace(/%curr%/gi,t+1).replace(/%total%/gi,n)}c.magnificPopup.registerModule("gallery",{options:{enabled:!1,arrowMarkup:'<button title="%title%" type="button" class="mfp-arrow mfp-arrow-%dir%"></button>',preload:[0,2],navigateByImgClick:!0,arrows:!0,tPrev:"Previous (Left arrow key)",tNext:"Next (Right arrow key)",tCounter:"%curr% of %total%"},proto:{initGallery:function(){var o=m.st.gallery,e=".mfp-gallery";if(m.direction=!0,!o||!o.enabled)return!1;v+=" mfp-gallery",f(b+e,function(){o.navigateByImgClick&&m.wrap.on("click"+e,".mfp-img",function(){if(1<m.items.length)return m.next(),!1}),g.on("keydown"+e,function(e){37===e.keyCode?m.prev():39===e.keyCode&&m.next()})}),f("UpdateStatus"+e,function(e,t){t.text&&(t.text=M(t.text,m.currItem.index,m.items.length))}),f(y+e,function(e,t,n,r){var i=m.items.length;n.counter=1<i?M(o.tCounter,r.index,i):"}),f("BuildControls"+e,function(){if(1<m.items.length&&o.arrows&&!m.arrowLeft){var e=o.arrowMarkup,t=m.arrowLeft=c(e.replace(/%title%/gi,o.tPrev).replace(/%dir%/gi,"left")).addClass(a),n=m.arrowRight=c(e.replace(/%title%/gi,o.tNext).replace(/%dir%/gi,"right")).addClass(a);t.click(function(){m.prev()}),n.click(function(){m.next()}),m.container.append(t.add(n))}}),f("Change"+e,function(){m._preloadTimeout&&clearTimeout(m._preloadTimeout),m._preloadTimeout=setTimeout(function(){m.preloadNearbyImages(),m._preloadTimeout=null},16)}),f(u+e,function(){g.off(e),m.wrap.off("click"+e),m.arrowRight=m.arrowLeft=null})},next:function(){m.direction=!0,m.index=q(m.index+1),m.updateItemHTML()},prev:function(){m.direction=!1,m.index=q(m.index-1),m.updateItemHTML()},goTo:function(e){m.direction=e>=m.index,m.index=e,m.updateItemHTML()},preloadNearbyImages:function(){var e,t=m.st.gallery.preload,n=Math.min(t[0],m.items.length),r=Math.min(t[1],m.items.length);for(e=1;e<=(m.direction?r:n);e++)m._preloadItem(m.index+e);for(e=1;e<=(m.direction?n:r);e++)m._preloadItem(m.index-e)},_preloadItem:function(e){if(e=q(e),!m.items[e].preloaded){var t=m.items[e];t.parsed||(t=m.parseEl(e)),p("LazyLoad",t),"image"===t.type&&(t.img=c('<img class="mfp-img" />').on("load.mfploader",function(){t.hasSize=!0}).on("error.mfploader",function(){t.hasSize=!0,t.loadError=!0,p("LazyLoadError",t)}).attr("src",t.src)),t.preloaded=!0}}}});var _="retina";c.magnificPopup.registerModule(_,{options:{replaceSrc:function(e){return e.src.replace(/\.\w+$/,function(e){return"@2x"+e})},ratio:1},proto:{initRetina:function(){if(1<window.devicePixelRatio){var n=m.st.retina,r=n.ratio;1<(r=isNaN(r)?r():r)&&(f("ImageHasSize."+_,function(e,t){t.img.css({"max-width":t.img[0].naturalWidth/r,width:"100%"})}),f("ElementParse."+_,function(e,t){t.src=n.replaceSrc(t,r)}))}}}}),o()}),function(e,c){var r,t=e.jQuery||e.Cowboy||(e.Cowboy={});t.throttle=r=function(i,o,a,s){var u,l=0;function e(){var e=this,t=new Date-l,n=arguments;function r(){l=+new Date,a.apply(e,n)}s&&!u&&r(),u&&clearTimeout(u),s===c&&i<t?r():!0!==o&&(u=setTimeout(s?function(){u=c}:r,s===c?i-t:i))}return"boolean"!=typeof o&&(s=a,a=o,o=c),t.guid&&(e.guid=a.guid=a.guid||t.guid++),e},t.debounce=function(e,t,n){return n===c?r(e,t,!1):r(e,n,!1!==t)}}(this),function(e,t){"function"==typeof define&&define.amd?define([],function(){return t(e)}):"object"==typeof exports?module.exports=t(e):e.SmoothScroll=t(e)}("undefined"!=typeof global?global:"undefined"!=typeof window?window:this,function(A){"use strict";function N(){var n={};return Array.prototype.forEach.call(arguments,function(e){for(var t in e){if(!e.hasOwnProperty(t))return;n[t]=e[t]}}),n}function o(e){"#"===e.charAt(0)&&(e=e.substr(1));for(var t,n=String(e),r=n.length,i=-1,o=",a=n.charCodeAt(0);++i<r;){if(0===(t=n.charCodeAt(i)))throw new InvalidCharacterError("Invalid character: the input contains U+0000.");1<=t&&t<=31||127==t||0===i&&48<=t&&t<=57||1===i&&48<=t&&t<=57&&45===a?o+="\\"+t.toString(16)+" ":o+=128<=t||45===t||95===t||48<=t&&t<=57||65<=t&&t<=90||97<=t&&t<=122?n.charAt(i):"\\"+n.charAt(i)}return"#"+o}function j(){return Math.max(document.body.scrollHeight,document.documentElement.scrollHeight,document.body.offsetHeight,document.documentElement.offsetHeight,document.body.clientHeight,document.documentElement.clientHeight)}function I(e){return e?(t=e,parseInt(A.getComputedStyle(t).height,10)+e.offsetTop):0;var t}function L(e,t,n,r){if(t.emitEvents&&"function"==typeof A.CustomEvent){var i=new CustomEvent(e,{bubbles:!0,detail:{anchor:n,toggle:r}});document.dispatchEvent(i)}}var D={ignore:"[data-scroll-ignore]",header:null,topOnEmptyHash:!0,speed:500,speedAsDuration:!1,durationMax:null,durationMin:null,clip:!0,offset:0,easing:"easeInOutCubic",customEasing:null,updateURL:!0,popstate:!0,emitEvents:!0};return function(r,e){var T,i,E,S,k={};k.cancelScroll=function(e){cancelAnimationFrame(S),S=null,e||L("scrollCancel",T)},k.animateScroll=function(a,s,e){k.cancelScroll();var u=N(T||D,e||{}),l="[object Number]"===Object.prototype.toString.call(a),t=l||!a.tagName?null:a;if(l||t){var c=A.pageYOffset;u.header&&!E&&(E=document.querySelector(u.header));var n,r,i,f,o,d,p,h,m=I(E),g=l?a:function(e,t,n,r){var i=0;if(e.offsetParent)for(;i+=e.offsetTop,e=e.offsetParent;);return i=Math.max(i-t-n,0),r&&(i=Math.min(i,j()-A.innerHeight)),i}(t,m,parseInt("function"==typeof u.offset?u.offset(a,s):u.offset,10),u.clip),v=g-c,y=j(),b=0,x=(n=v,i=(r=u).speedAsDuration?r.speed:Math.abs(n/1e3*r.speed),r.durationMax&&i>r.durationMax?r.durationMax:r.durationMin&&i<r.durationMin?r.durationMin:parseInt(i,10)),w=function(e,t){var n,r,i,o=A.pageYOffset;if(e==t||o==t||(c<t&&A.innerHeight+o)>=y)return k.cancelScroll(!0),r=t,i=l,0===(n=a)&&document.body.focus(),i||(n.focus(),document.activeElement!==n&&(n.setAttribute("tabindex","-1"),n.focus(),n.style.outline="none"),A.scrollTo(0,r)),L("scrollStop",u,a,s),!(S=f=null)},C=function(e){var t,n,r;b+=e-(f=f||e),d=c+v*(n=o=1<(o=0===x?0:b/x)?1:o,"easeInQuad"===(t=u).easing&&(r=n*n),"easeOutQuad"===t.easing&&(r=n*(2-n)),"easeInOutQuad"===t.easing&&(r=n<.5?2*n*n:(4-2*n)*n-1),"easeInCubic"===t.easing&&(r=n*n*n),"easeOutCubic"===t.easing&&(r=--n*n*n+1),"easeInOutCubic"===t.easing&&(r=n<.5?4*n*n*n:(n-1)*(2*n-2)*(2*n-2)+1),"easeInQuart"===t.easing&&(r=n*n*n*n),"easeOutQuart"===t.easing&&(r=1- --n*n*n*n),"easeInOutQuart"===t.easing&&(r=n<.5?8*n*n*n*n:1-8*--n*n*n*n),"easeInQuint"===t.easing&&(r=n*n*n*n*n),"easeOutQuint"===t.easing&&(r=1+--n*n*n*n*n),"easeInOutQuint"===t.easing&&(r=n<.5?16*n*n*n*n*n:1+16*--n*n*n*n*n),t.customEasing&&(r=t.customEasing(n)),r||n),A.scrollTo(0,Math.floor(d)),w(d,g)||(S=A.requestAnimationFrame(C),f=e)};0===A.pageYOffset&&A.scrollTo(0,0),p=a,h=u,l||history.pushState&&h.updateURL&&history.pushState({smoothScroll:JSON.stringify(h),anchor:p.id},document.title,p===document.documentElement?"#top":"#"+p.id),"matchMedia"in A&&A.matchMedia("(prefers-reduced-motion)").matches?A.scrollTo(0,Math.floor(g)):(L("scrollStart",u,a,s),k.cancelScroll(!0),A.requestAnimationFrame(C))}};function t(e){if(!e.defaultPrevented&&!(0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey)&&"closest"in e.target&&(i=e.target.closest(r))&&"a"===i.tagName.toLowerCase()&&!e.target.closest(T.ignore)&&i.hostname===A.location.hostname&&i.pathname===A.location.pathname&&/#/.test(i.href)){var t,n;try{t=o(decodeURIComponent(i.hash))}catch(e){t=o(i.hash)}if("#"===t){if(!T.topOnEmptyHash)return;n=document.documentElement}else n=document.querySelector(t);(n=n||"#top"!==t?n:document.documentElement)&&(e.preventDefault(),function(e){if(history.replaceState&&e.updateURL&&!history.state){var t=A.location.hash;t=t||",history.replaceState({smoothScroll:JSON.stringify(e),anchor:t||A.pageYOffset},document.title,t||A.location.href)}}(T),k.animateScroll(n,i))}}function n(e){if(null!==history.state&&history.state.smoothScroll&&history.state.smoothScroll===JSON.stringify(T)){var t=history.state.anchor;"string"==typeof t&&t&&!(t=document.querySelector(o(history.state.anchor)))||k.animateScroll(t,null,{updateURL:!1})}}k.destroy=function(){T&&(document.removeEventListener("click",t,!1),A.removeEventListener("popstate",n,!1),k.cancelScroll(),S=E=i=T=null)};return function(){if(!("querySelector"in document&&"addEventListener"in A&&"requestAnimationFrame"in A&&"closest"in A.Element.prototype))throw"Smooth Scroll: This browser does not support the required JavaScript methods and browser APIs.";k.destroy(),T=N(D,e||{}),E=T.header?document.querySelector(T.header):null,document.addEventListener("click",t,!1),T.updateURL&&T.popstate&&A.addEventListener("popstate",n,!1)}(),k}}),function(e,t){"function"==typeof define&&define.amd?define([],function(){return t(e)}):"object"==typeof exports?module.exports=t(e):e.Gumshoe=t(e)}("undefined"!=typeof global?global:"undefined"!=typeof window?window:this,function(c){"use strict";function f(e,t,n){if(n.settings.events){var r=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:n});t.dispatchEvent(r)}}function n(e){var t=0;if(e.offsetParent)for(;e;)t+=e.offsetTop,e=e.offsetParent;return 0<=t?t:0}function d(e){e&&e.sort(function(e,t){return n(e.content)<n(t.content)?-1:1})}function a(e,t,n){var r,i=e.getBoundingClientRect(),o="function"==typeof(r=t).offset?parseFloat(r.offset()):parseFloat(r.offset);return n?parseInt(i.bottom,10)<(c.innerHeight||document.documentElement.clientHeight):parseInt(i.top,10)<=o}function s(){return c.innerHeight+c.pageYOffset>=Math.max(document.body.scrollHeight,document.documentElement.scrollHeight,document.body.offsetHeight,document.documentElement.offsetHeight,document.body.clientHeight,document.documentElement.clientHeight)}function p(e,t){var n,r,i=e[e.length-1];if(n=i,r=t,s()&&a(n.content,r,!0))return i;for(var o=e.length-1;0<=o;o--)if(a(e[o].content,t))return e[o]}function h(e,t){if(e){var n=e.nav.closest("li");n&&(n.classList.remove(t.navClass),e.content.classList.remove(t.contentClass),r(n,t),f("gumshoeDeactivate",n,{link:e.nav,content:e.content,settings:t}))}}var m={navClass:"active",contentClass:"active",nested:!1,nestedClass:"active",offset:0,reflow:!1,events:!0},r=function(e,t){if(t.nested){var n=e.parentNode.closest("li");n&&(n.classList.remove(t.nestedClass),r(n,t))}},g=function(e,t){if(t.nested){var n=e.parentNode.closest("li");n&&(n.classList.add(t.nestedClass),g(n,t))}};return function(e,t){var n,r,i,o,a,s={};s.setup=function(){n=document.querySelectorAll(e),r=[],Array.prototype.forEach.call(n,function(e){var t=document.getElementById(decodeURIComponent(e.hash.substr(1)));t&&r.push({nav:e,content:t})}),d(r)},s.detect=function(){var e=p(r,a);e?i&&e.content===i.content||(h(i,a),function(e,t){if(e){var n=e.nav.closest("li");n&&(n.classList.add(t.navClass),e.content.classList.add(t.contentClass),g(n,t),f("gumshoeActivate",n,{link:e.nav,content:e.content,settings:t}))}}(e,a),i=e):i&&(h(i,a),i=null)};function u(e){o&&c.cancelAnimationFrame(o),o=c.requestAnimationFrame(s.detect)}function l(e){o&&c.cancelAnimationFrame(o),o=c.requestAnimationFrame(function(){d(r),s.detect()})}s.destroy=function(){i&&h(i,a),c.removeEventListener("scroll",u,!1),a.reflow&&c.removeEventListener("resize",l,!1),a=o=i=n=r=null};return a=function(){var n={};return Array.prototype.forEach.call(arguments,function(e){for(var t in e){if(!e.hasOwnProperty(t))return;n[t]=e[t]}}),n}(m,t||{}),s.setup(),s.detect(),c.addEventListener("scroll",u,!1),a.reflow&&c.addEventListener("resize",l,!1),s}}),$(document).ready(function(){$("#main").fitVids();function e(){(0===$(".author__urls-wrapper button").length?1024<$(window).width():!$(".author__urls-wrapper button").is(":visible"))?$(".sidebar").addClass("sticky"):$(".sidebar").removeClass("sticky")}e(),$(window).resize(function(){e()}),$(".author__urls-wrapper button").on("click",function(){$(".author__urls").toggleClass("is--visible"),$(".author__urls-wrapper button").toggleClass("open")}),$(document).keyup(function(e){27===e.keyCode&&$(".initial-content").hasClass("is--hidden")&&($(".search-content").toggleClass("is--visible"),$(".initial-content").toggleClass("is--hidden"))}),$(".search__toggle").on("click",function(){$(".search-content").toggleClass("is--visible"),$(".initial-content").toggleClass("is--hidden"),setTimeout(function(){$(".search-content input").focus()},400)});new SmoothScroll('a[href*="#"]',{offset:20,speed:400,speedAsDuration:!0,durationMax:500});if(0<$("nav.toc").length)new Gumshoe("nav.toc a",{navClass:"active",contentClass:"active",nested:!1,nestedClass:"active",offset:20,reflow:!0,events:!0});$("a[href$='.jpg'],a[href$='.jpeg'],a[href$='.JPG'],a[href$='.png'],a[href$='.gif']").addClass("image-popup"),$(".image-popup").magnificPopup({type:"image",tLoading:"Loading image #%curr%...",gallery:{enabled:!0,navigateByImgClick:!0,preload:[0,1]},image:{tError:'<a href="%url%">Image #%curr%</a> could not be loaded.'},removalDelay:500,mainClass:"mfp-zoom-in",callbacks:{beforeOpen:function(){this.st.image.markup=this.st.image.markup.replace("mfp-figure","mfp-figure mfp-with-anim")}},closeOnContentClick:!0,midClick:!0}),$(".page__content").find("h1, h2, h3, h4, h5, h6").each(function(){var e=$(this).attr("id");if(e){var t=document.createElement("a");t.className="header-link",t.href="#"+e,t.innerHTML='<span class="sr-only">Permalink</span><i class="fas fa-link"></i>',t.title="Permalink",$(this).append(t)}})});
import template from './sw-first-run-wizard-data-import.html.twig'; import './sw-first-run-wizard-data-import.scss'; const { Criteria } = Shopware.Data; const { Component } = Shopware; Component.register('sw-first-run-wizard-data-import', { template, inject: [ 'extensionStoreActionService', 'repositoryFactory', ], data() { return { plugins: { demodata: { name: 'SwagPlatformDemoData', isInstalled: false, }, migration: { name: 'SwagMigrationAssistant', isInstalled: false, }, }, demoDataPluginName: 'SwagPlatformDemoData', migrationPluginName: 'SwagMigrationAssistant', isPluginAlreadyInstalled: false, isInstallingPlugin: false, installationError: false, pluginError: null, pluginInstalledSuccessfully: { demodata: false, migration: false, }, }; }, computed: { pluginRepository() { return this.repositoryFactory.create('plugin'); }, buttonConfig() { return [ { key: 'skip', label: this.$tc('sw-first-run-wizard.general.buttonNext'), position: 'right', variant: 'primary', action: 'sw.first.run.wizard.index.defaults', disabled: this.isInstallingPlugin, }, ]; }, }, watch: { isInstallingPlugin() { this.updateButtons(); }, }, created() { this.createdComponent(); }, methods: { createdComponent() { this.updateButtons(); this.setTitle(); this.getInstalledPlugins(); }, updateButtons() { this.$emit('buttons-update', this.buttonConfig); }, setTitle() { this.$emit('frw-set-title', this.$tc('sw-first-run-wizard.dataImport.modalTitle')); }, notInstalled(pluginKey) { return !this.plugins[pluginKey].isInstalled; }, onInstall(pluginKey) { const plugin = this.plugins[pluginKey]; this.isInstallingPlugin = true; this.installationError = false; return this.extensionStoreActionService.downloadExtension(plugin.name) .then(() => { return this.extensionStoreActionService.installExtension(plugin.name, 'plugin'); }) .then(() => { return this.extensionStoreActionService.activateExtension(plugin.name, 'plugin'); }) .then(() => { this.isInstallingPlugin = false; this.plugins[pluginKey].isInstalled = true; return false; }) .catch((error) => { this.isInstallingPlugin = false; this.installationError = true; if (error.response?.data?.errors) { this.pluginError = error.response.data.errors.pop(); } return true; }); }, getInstalledPlugins() { const pluginNames = Object.values(this.plugins).map(plugin => plugin.name); const pluginCriteria = new Criteria(1, 5); pluginCriteria .addFilter( Criteria.equalsAny('plugin.name', pluginNames), ); this.pluginRepository.search(pluginCriteria) .then((result) => { if (result.total < 1) { return; } result.forEach((plugin) => { if (!plugin.active || plugin.installedAt === null) { return; } const key = this.findPluginKeyByName(plugin.name); this.plugins[key].isInstalled = true; }); }); }, findPluginKeyByName(name) { const [pluginKey] = Object.entries(this.plugins).find(([key, state]) => { if (state.name === name) { return key; } return ''; }); return pluginKey; }, }, });
import offers from '@/offers/api/offers' import { createMetaModule, withMeta } from '@/utils/datastore/helpers' function initialState () { return { current: null, id: null, } } export default { namespaced: true, modules: { meta: createMetaModule(), }, state: initialState(), getters: { value: (state, getters, rootState, rootGetters) => { return rootGetters['offers/enrich'](state.current) }, id: state => state.id, conversation: (state, getters, rootState, rootGetters) => { if (!state.current) return return rootGetters['conversations/getForOffer'](state.current.id) }, fetching (state, getters) { if (!state.id) return const status = getters['meta/status']('fetch', state.id) return status && status.pending }, saveStatus: (state, getters) => { const currentOffer = getters.value return currentOffer && currentOffer.saveStatus }, }, actions: { ...withMeta({ async fetch ({ state, commit, dispatch }, offerId) { commit('setId', offerId) const offer = await offers.get(offerId) // aborting, another offer has been loaded while we waited if (state.id !== offerId) return commit('set', offer) }, }), refresh ({ state, dispatch }) { if (state.current) { dispatch('fetch', state.current.id) } }, clear ({ commit }) { commit('clear') }, ...withMeta({ async select ({ dispatch, commit }, { offerId }) { // clear right drawer // TODO can be removed once detail are bound to routes dispatch('detail/clear', null, { root: true }) await dispatch('fetch', offerId) dispatch('conversations/fetchForOffer', { offerId }, { root: true }) }, }, { setCurrentId: ({ commit }, { offerId }) => commit('setId', offerId), getCurrentId: ({ state }) => state.id, findId: ({ offerId }) => offerId, }), }, mutations: { setId (state, value) { state.id = value }, set (state, offer) { state.current = Object.freeze(offer) }, clear (state) { Object.assign(state, initialState()) }, update (state, offer) { if (state.id === offer.id) { state.current = Object.freeze(offer) } }, delete (state, offerId) { if (state.id === offerId) Object.assign(state, initialState()) }, }, }
import { generateObjectId } from '../../src/utils/mogodb-objectid.generator'; test('generateSuccess', () => { const objectId = generateObjectId(); expect(typeof(objectId)).toBe('string'); expect(objectId.length).toBe(24); }); test('right objectId date', () => { const objectId = generateObjectId(); const seconds = parseInt(objectId.substr(0, 8), 16); expect(seconds).toBe(parseInt(Date.now()/1000)); });
export * from './analytics'; export * from './analytics.module'; export * from './analytics.service'; //# sourceMappingURL=public_api.js.map
//全局cli配置文件 /** * 1.该文件和 package.json 同级 会被 @vue/cli-service 加载 * */ module.exports = { //baseUrl :vue cli 3.3已弃用 请使用 publicPath //部署应用包时的基本 URL publicPath: "/", //当运行 vue-cli-service build 时生成的生产环境构建文件的目录 outputDir: "dist", //放置生成的静态资源 (js、css、img、fonts) 的 (相对于 outputDir 的) 目录 assetsDir: "", //指定生成的 index.html 的输出路径 (相对于 outputDir)。也可以是一个绝对路径 indexPath: "index.html", //默认情况下,生成的静态资源在它们的文件名中包含了 hash 以便更好的控制缓存 filenameHashing: true, //在 multi-page 模式下构建应用。每个“page”应该有一个对应的 JavaScript 入口文件 pages: { index:{ // page 的入口 entry: "src/main.js", //模版来源 template: "public/index.html", } }, //是否在开发环境下通过 eslint-loader 在每次保存时 lint 代码 lintOnSave: "default", //是否使用包含运行时编译器的 Vue 构建版本 runtimeCompiler: false, //默认情况下 babel-loader 会忽略所有 node_modules 中的文件。如果你想要通过 Babel 显式转译一个依赖,可以在这个选项中列出来 transpileDependencies: [], //如果你不需要生产环境的 source map,可以将其设置为 false 以加速生产环境构建 productionSourceMap: true, //设置生成的 HTML 中 <link rel="stylesheet"> 和 <script> 标签的 crossorigin 属性 crossorigin: undefined, //在生成的 HTML 中的 <link rel="stylesheet"> 和 <script> 标签上启用 Subresource Integrity (SRI)。如果你构建后的文件是部署在 CDN 上的,启用该选项可以提供额外的安全性 integrity: false, //如果这个值是一个对象,则会通过 webpack-merge 合并到最终的配置中 //如果这个值是一个函数,则会接收被解析的配置作为参 //configureWebpack //是一个函数,会接收一个基于 webpack-chain 的 ChainableConfig 实例。允许对内部的 webpack 配置进行更细粒度的修改 //chainWebpack devServer: { proxy: "http://localhost:8081" }, // chainWebpack: (config) => { // config.module // .rule() // .test(/\.s(c|a)ss$/) // .use("vue-style-loader") // .use("css-loader") // .loader("sass-loader") // .options({ // implementation: require('sass'), // }) // .sassOptions({ // indentedSyntax: true // }) // }, // module: { // rules: [ // { // test: /\.s(c|a)ss$/, // use: [ // 'vue-style-loader', // 'css-loader', // { // loader: 'sass-loader', // // Requires sass-loader@^7.0.0 // // options: { // // implementation: require('sass'), // // indentedSyntax: true // optional // // }, // // Requires >= sass-loader@^8.0.0 // options: { // implementation: require('sass'), // sassOptions: { // indentedSyntax: true // optional // }, // }, // }, // ], // }, // ], // } } //导入 webpack-chain 模块, 该模块导出一个用于创建一个webpack配置api的单一构造函数 // const Config = require("webpack-chain"); //对单一的构造函数创建一个新的配置实例 // const config = new Config(); //用链式api改变配置 //每个api的调用会跟踪对存储配置的更改 // config // .entry()
//React: Use Default Props /* * React also has an option to set default props. * You can assign default props to a component as a property on the component itself and React assigns the default prop if necessary * This allows you to specify what a prop value should be if no value is explicitly provided. */ /* The code editor shows a ShoppingCart component. Define default props on this component which specify a prop items with a value of 0 */ const ShoppingCart = (props) => { return ( <div> <h1>Shopping Cart Component</h1> </div> ); }; // change code below this line ShoppingCart.defaultProps = { items: 0 };
const zoomAdmin = { type: "app", app: "zoom_admin", }; module.exports = { name: "Webinar Created", version: "0.0.1", dedupe: "unique", // Dedupe based on webinar ID props: { zoomAdmin, zoomApphook: { type: "$.interface.apphook", appProp: "zoomAdmin", eventNames: ["webinar.created"], }, }, async run(event) { const { payload } = event; const { object } = payload; this.$emit( { event: "webinar.created", payload }, { summary: `Webinar ${object.topic} created`, id: object.uuid, ts: +new Date(object.start_time), } ); }, };
module.exports = { parser: "@typescript-eslint/parser", parserOptions: { sourceType: "module" } }
import Vue from 'vue' import App from './App' import util from '@/utils/index'; Vue.prototype.$callApi=util.callApi; Vue.config.productionTip = false App.mpType = 'app' const app = new Vue(App) app.$mount()
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; module.metadata = { "stability": "stable" }; const observers = require('./system/events'); const { contract: loaderContract } = require('./content/loader'); const { contract } = require('./util/contract'); const { getAttachEventType, WorkerHost } = require('./content/utils'); const { Class } = require('./core/heritage'); const { Disposable } = require('./core/disposable'); const { WeakReference } = require('./core/reference'); const { Worker } = require('./content/worker'); const { EventTarget } = require('./event/target'); const { on, emit, once, setListeners } = require('./event/core'); const { on: domOn, removeListener: domOff } = require('./dom/events'); const { pipe } = require('./event/utils'); const { isRegExp } = require('./lang/type'); const { merge } = require('./util/object'); const { windowIterator } = require('./deprecated/window-utils'); const { isBrowser, getFrames } = require('./window/utils'); const { getTabs, getTabContentWindow, getTabForContentWindow, getURI: getTabURI } = require('./tabs/utils'); const { ignoreWindow } = require('sdk/private-browsing/utils'); const { Style } = require("./stylesheet/style"); const { attach, detach } = require("./content/mod"); const { has, hasAny } = require("./util/array"); const { Rules } = require("./util/rules"); const { List, addListItem, removeListItem } = require('./util/list'); const { when: unload } = require("./system/unload"); // Valid values for `attachTo` option const VALID_ATTACHTO_OPTIONS = ['existing', 'top', 'frame']; const pagemods = new Set(); const workers = new WeakMap(); const styles = new WeakMap(); const models = new WeakMap(); let modelFor = (mod) => models.get(mod); let workerFor = (mod) => workers.get(mod); let styleFor = (mod) => styles.get(mod); // Bind observer observers.on('document-element-inserted', onContentWindow); unload(() => observers.off('document-element-inserted', onContentWindow)); let isRegExpOrString = (v) => isRegExp(v) || typeof v === 'string'; // Validation Contracts const modOptions = { // contentStyle* / contentScript* are sharing the same validation constraints, // so they can be mostly reused, except for the messages. contentStyle: merge(Object.create(loaderContract.rules.contentScript), { msg: 'The `contentStyle` option must be a string or an array of strings.' }), contentStyleFile: merge(Object.create(loaderContract.rules.contentScriptFile), { msg: 'The `contentStyleFile` option must be a local URL or an array of URLs' }), include: { is: ['string', 'array', 'regexp'], ok: (rule) => { if (isRegExpOrString(rule)) return true; if (Array.isArray(rule) && rule.length > 0) return rule.every(isRegExpOrString); return false; }, msg: 'The `include` option must always contain atleast one rule as a string, regular expression, or an array of strings and regular expressions.' }, attachTo: { is: ['string', 'array', 'undefined'], map: function (attachTo) { if (!attachTo) return ['top', 'frame']; if (typeof attachTo === 'string') return [attachTo]; return attachTo; }, ok: function (attachTo) { return hasAny(attachTo, ['top', 'frame']) && attachTo.every(has.bind(null, ['top', 'frame', 'existing'])); }, msg: 'The `attachTo` option must be a string or an array of strings. ' + 'The only valid options are "existing", "top" and "frame", and must ' + 'contain at least "top" or "frame" values.' }, }; const modContract = contract(merge({}, loaderContract.rules, modOptions)); /** * PageMod constructor (exported below). * @constructor */ const PageMod = Class({ implements: [ modContract.properties(modelFor), EventTarget, Disposable, WeakReference ], extends: WorkerHost(workerFor), setup: function PageMod(options) { let mod = this; let model = modContract(options); models.set(this, model); // Set listeners on {PageMod} itself, not the underlying worker, // like `onMessage`, as it'll get piped. setListeners(this, options); let include = model.include; model.include = Rules(); model.include.add.apply(model.include, [].concat(include)); if (model.contentStyle || model.contentStyleFile) { styles.set(mod, Style({ uri: model.contentStyleFile, source: model.contentStyle })); } pagemods.add(this); // `applyOnExistingDocuments` has to be called after `pagemods.add()` // otherwise its calls to `onContent` method won't do anything. if (has(model.attachTo, 'existing')) applyOnExistingDocuments(mod); }, dispose: function() { let style = styleFor(this); if (style) detach(style); for (let i in this.include) this.include.remove(this.include[i]); pagemods.delete(this); } }); exports.PageMod = PageMod; function onContentWindow({ subject: document }) { // Return if we have no pagemods if (pagemods.size === 0) return; let window = document.defaultView; // XML documents don't have windows, and we don't yet support them. if (!window) return; // We apply only on documents in tabs of Firefox if (!getTabForContentWindow(window)) return; // When the tab is private, only addons with 'private-browsing' flag in // their package.json can apply content script to private documents if (ignoreWindow(window)) return; for (let pagemod of pagemods) { if (pagemod.include.matchesAny(document.URL)) onContent(pagemod, window); } } // Returns all tabs on all currently opened windows function getAllTabs() { let tabs = []; // Iterate over all chrome windows for (let window in windowIterator()) { if (!isBrowser(window)) continue; tabs = tabs.concat(getTabs(window)); } return tabs; } function applyOnExistingDocuments (mod) { let tabs = getAllTabs(); tabs.forEach(function (tab) { // Fake a newly created document let window = getTabContentWindow(tab); if (has(mod.attachTo, "top") && mod.include.matchesAny(getTabURI(tab))) onContent(mod, window); if (has(mod.attachTo, "frame")) { getFrames(window). filter((iframe) => mod.include.matchesAny(iframe.location.href)). forEach((frame) => onContent(mod, frame)); } }); } function createWorker (mod, window) { let worker = Worker({ window: window, contentScript: mod.contentScript, contentScriptFile: mod.contentScriptFile, contentScriptOptions: mod.contentScriptOptions, // Bug 980468: Syntax errors from scripts can happen before the worker // can set up an error handler. They are per-mod rather than per-worker // so are best handled at the mod level. onError: (e) => emit(mod, 'error', e) }); workers.set(mod, worker); pipe(worker, mod); emit(mod, 'attach', worker); once(worker, 'detach', function detach() { worker.destroy(); }); } function onContent (mod, window) { // not registered yet if (!pagemods.has(mod)) return; let isTopDocument = window.top === window; // Is a top level document and `top` is not set, ignore if (isTopDocument && !has(mod.attachTo, "top")) return; // Is a frame document and `frame` is not set, ignore if (!isTopDocument && !has(mod.attachTo, "frame")) return; let style = styleFor(mod); if (style) attach(style, window); // Immediatly evaluate content script if the document state is already // matching contentScriptWhen expectations if (isMatchingAttachState(mod, window)) { createWorker(mod, window); return; } let eventName = getAttachEventType(mod) || 'load'; domOn(window, eventName, function onReady (e) { if (e.target.defaultView !== window) return; domOff(window, eventName, onReady, true); createWorker(mod, window); }, true); } function isMatchingAttachState (mod, window) { let state = window.document.readyState; return 'start' === mod.contentScriptWhen || // Is `load` event already dispatched? 'complete' === state || // Is DOMContentLoaded already dispatched and waiting for it? ('ready' === mod.contentScriptWhen && state === 'interactive') }
import { asyncComponent } from 'react-async-component'; export const log = (...args) => console.log(...args); export const logError = (...args) => console.error(...args); export const renderIf = (test, component) => test ? component : undefined; export const classToggler = (options) => Object.keys(options).filter(key => !!options[key]).join(' '); export const makeAsyncComponent = importStmt => { return asyncComponent({ resolve: () => importStmt }) };
'use strict'; const express = require('express'); const router = express.Router(); let Courses = require("../models").Courses; let Users = require("../models").Users; let sequelize = require("../models").sequelize; const { check, validationResult } = require('express-validator/check'); const bcryptjs = require('bcryptjs'); const atob = require('atob'); //getCredentials returns the user's credentials from the authorization header const getCredentials = (req) => { let credentials = null; const authHeaderVal = req.get('Authorization'); //if authorization is not empty and starts with the string 'basic ' then if (authHeaderVal && authHeaderVal.startsWith('Basic ')) { //the username and password are set to base64cred const base64Credentials = authHeaderVal.slice(6); //the username and password are converted from base64 ascii to binary const stringCredentials = atob(base64Credentials); //the username and password are split into an array const partsCredentials = stringCredentials.split(':'); //the credentials are set credentials = { email: partsCredentials[0], pass: partsCredentials[1], }; } return credentials; }; //returns list of all courses router.get('/courses', (req, res) => { Courses.findAll({ include: [ { model: Users, //Only send required attributes attributes: ["firstName", "lastName","emailAddress"] } ] }).then((courses)=>{ res.json({ courses }); }); }); //returns courses by id router.get('/courses/:id', (req, res, next) => { Courses.findOne({ where:{ id:req.params.id }, include: [ { model: Users, //Only send required attributes attributes: ["firstName", "lastName","emailAddress"] } ] }). then((course) => { //if it is found then is is returned if(course) { res.json({ course }); } else{ next(); } }); }); //posts a new course router.post('/courses', [ check('title') .exists({ checkNull: true, checkFalsy: true }) .withMessage('Please provide a value for title'), check('description') .exists({ checkNull: true, checkFalsy: true }) .withMessage('Please provide a value for description'), ], (req, res) => { // Attempt to get the validation result from the Request object. const courseErrors = validationResult(req); //user credentials are acquired from auth header const credentials = getCredentials(req); let newCourse = req.body; const checkTitleAndDescription = new Promise((resolve, reject) => { if(!courseErrors.isEmpty()) { const courseErrorMessages = courseErrors.array().map(error => error.msg); reject(Error(courseErrorMessages)); } else { console.log('Title and Description: passed'); resolve(); } }); const checkEmailAndPasswordProvided = new Promise((resolve, reject) => { if(credentials.pass && credentials.email) { console.log('Email Address and Password are present: passed'); resolve(); } else{ reject(Error('The Email Address/Password were not provided.')); } }); function checkEmailInDatabase(user) { return new Promise((resolve, reject) => { if(user == null) { reject(Error('The Email Address was not found.')); } else{ //validates if user is in database console.log('Email Address is present: passed'); resolve(user); } }); } function checkPassword(user){ return new Promise((resolve, reject) =>{ //the user password is compared with the database password const authenticated = bcryptjs.compareSync(credentials.pass, user[0].password); if(authenticated){ console.log('Password is a match: passed'); resolve(user); } else{ reject(Error('The Password is invalid.')); } }); } checkTitleAndDescription .then(()=>{return checkEmailAndPasswordProvided}) .then(()=>{return Users.findAll({ where: { emailAddress: credentials.email } }); }).then((user)=>{return checkEmailInDatabase(user); }) .then((user)=>{return checkPassword(user); }) .then((user)=>{ return Courses.build({ title: newCourse.title, description: newCourse.description, estimatedTime: newCourse.estimatedTime, materialsNeeded: newCourse.materialsNeeded, userId: user[0].id }).save() }).then((course)=>{ return res.redirect(201, '/courses/:course.id'); }) .catch((err)=>{ //err = 'There was an error processing your request.'; console.warn(err); return res.status(401).json({ error: err.message }); }); }); //updates a user's course router.put('/courses/:id', [ check('title') .exists({ checkNull: true, checkFalsy: true }) .withMessage('Please provide a value for title'), check('description') .exists({ checkNull: true, checkFalsy: true }) .withMessage('Please provide a value for description'), ], (req, res) => { // Attempt to get the validation result from the Request object. const courseErrors = validationResult(req); //user credentials are acquired from auth header const credentials = getCredentials(req); let newCourse = req.body; const checkTitleAndDescription = new Promise((resolve, reject) => { if(!courseErrors.isEmpty()) { const courseErrorMessages = courseErrors.array().map(error => error.msg); reject(Error(courseErrorMessages)); } else { console.log('Title and Description: passed'); resolve(); } }); const checkEmailAndPasswordProvided = new Promise((resolve, reject) => { if(credentials.pass && credentials.email) { console.log('Email Address and Password are present: passed'); resolve(); } else{ reject(Error('Email Address and Password are present: failed.')); } }); function checkEmailInDatabase(user) { return new Promise((resolve, reject) => { if(user == null) { reject(Error('Email Address is present: failed')); } else{ //validates if user is in database console.log('Email Address is present: passed'); resolve(user); } }); } function checkPassword(user){ return new Promise((resolve, reject) =>{ //the user password is compared with the database password const authenticated = bcryptjs.compareSync(credentials.pass, user[0].password); if(authenticated){ console.log('Password is a match: passed'); resolve(user); } else{ reject(Error('Password is a match: failed.')); } }); } function getCourseId(){ return Courses.findByPk(req.params.id); } //function to check if the course.userid matchs the user's id function checkCourseIDandUserID(courseAndUser){ return new Promise((resolve, reject) => { if(courseAndUser[0].userId === courseAndUser[1][0].id){ console.log('User and Course ID match: passed'); resolve(courseAndUser[0]); } else{ reject(Error('User and Course Id match: failed')); } }); } checkTitleAndDescription .then(()=>{return checkEmailAndPasswordProvided}) .then(()=>{return Users.findAll({ where: { emailAddress: credentials.email } }); }).then((user)=>{return checkEmailInDatabase(user); }) .then((user)=>{return checkPassword(user); }) .then((user)=>{ let courseId = getCourseId(); return Promise.all([courseId, user]); }).then((courseAndUser)=>{ return checkCourseIDandUserID(courseAndUser); }) .then((course)=>{ course.update(req.body); return res.status(204).json({ message: '' }); }) .catch((err)=>{ //err = 'There was an error processing your request.'; console.warn(err); return res.status(401).json({ error: err.message }); }); }); //delete's a user's course router.delete('/courses/:id', (req, res) => { //user credentials are acquired from auth header const credentials = getCredentials(req); const checkEmailAndPasswordProvided = new Promise((resolve, reject) => { if(credentials.pass && credentials.email) { console.log('Email Address and Password are present: passed'); resolve(); } else{ reject(Error('Email Address and Password are present: failed.')); } }); function checkEmailInDatabase(user) { return new Promise((resolve, reject) => { if(user == null) { reject(Error('Email Address is present: failed')); } else{ //validates if user is in database console.log('Email Address is present: passed'); resolve(user); } }); } function checkPassword(user){ return new Promise((resolve, reject) =>{ //the user password is compared with the database password const authenticated = bcryptjs.compareSync(credentials.pass, user[0].password); if(authenticated){ console.log('Password is a match: passed'); resolve(user); } else{ reject(Error('Password is a match: failed.')); } }); } function getCourseId(){ return Courses.findByPk(req.params.id); } //function to check if the course.userid matchs the user's id function checkCourseIDandUserID(courseAndUser){ return new Promise((resolve, reject) => { if(courseAndUser[0].userId === courseAndUser[1][0].id){ console.log('User and Course ID match: passed'); resolve(courseAndUser[0]); } else{ reject(Error('User and Course Id match: failed')); } }); } checkEmailAndPasswordProvided .then(()=>{return Users.findAll({ where: { emailAddress: credentials.email } }); }).then((user)=>{return checkEmailInDatabase(user); }) .then((user)=>{return checkPassword(user); }) .then((user)=>{ let courseId = getCourseId(); return Promise.all([courseId, user]); }).then((courseAndUser)=>{return checkCourseIDandUserID(courseAndUser); }) .then((course)=>{ course.destroy(); return res.status(204).json({ message: '' }); }).catch((err)=>{ //err = 'There was an error processing your request.'; console.warn(err); return res.status(401).json({ error: err.message }); }); }); module.exports = router;
module.exports = { html_attributions: [], next_page_token: 'some token', results: [ { business_status: 'OPERATIONAL', geometry: { location: { lat: 43.6465623, lng: -79.374578, }, viewport: { northeast: { lat: 43.64794098029149, lng: -79.37325551970848, }, southwest: { lat: 43.6452430197085, lng: -79.37595348029149, }, }, }, icon: 'https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/lodging-71.png', name: 'Novotel Toronto Centre', opening_hours: { open_now: true, }, photos: [ { height: 4910, html_attributions: [''], photo_reference: '', width: 6576, }, ], place_id: 'some place id 61', plus_code: { compound_code: '', global_code: '', }, rating: 4.2, reference: '', scope: '', types: [ 'lodging', 'restaurant', 'food', 'point_of_interest', 'establishment', ], user_ratings_total: 1822, vicinity: '45 The Esplanade, Toronto', }, { business_status: 'OPERATIONAL', geometry: { location: { lat: 43.6460303, lng: -79.381388, }, viewport: { northeast: { lat: 43.6471657802915, lng: -79.3799530197085, }, southwest: { lat: 43.6444678197085, lng: -79.3826509802915, }, }, }, icon: 'https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/lodging-71.png', name: 'Fairmont Royal York', opening_hours: { open_now: true, }, photos: [ { height: 2048, html_attributions: [''], photo_reference: '', width: 1621, }, ], place_id: 'some place id 62', plus_code: { compound_code: '', global_code: '', }, rating: 4.5, reference: '', scope: '', types: [ 'lodging', 'restaurant', 'food', 'point_of_interest', 'establishment', ], user_ratings_total: 8383, vicinity: '100 Front Street West, Toronto', }, { business_status: 'OPERATIONAL', geometry: { location: { lat: 43.65, lng: -79.39638889999999, }, viewport: { northeast: { lat: 43.6512747302915, lng: -79.39500986970849, }, southwest: { lat: 43.6485767697085, lng: -79.3977078302915, }, }, }, icon: 'https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/lodging-71.png', name: 'HOTEL OCHO', opening_hours: { open_now: true, }, photos: [ { height: 1924, html_attributions: [''], photo_reference: '', width: 3598, }, ], place_id: 'some place id 63', plus_code: { compound_code: '', global_code: '', }, rating: 4.3, reference: '', scope: '', types: [ 'lodging', 'bar', 'restaurant', 'food', 'point_of_interest', 'establishment', ], user_ratings_total: 502, vicinity: '195 Spadina Avenue, Toronto', }, { business_status: 'OPERATIONAL', geometry: { location: { lat: 43.64696989999999, lng: -79.3932324, }, viewport: { northeast: { lat: 43.64837233029149, lng: -79.3916331697085, }, southwest: { lat: 43.64567436970849, lng: -79.3943311302915, }, }, }, icon: 'https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/restaurant-71.png', name: 'Marquis Lounge and Bistro', photos: [ { height: 1500, html_attributions: [''], photo_reference: '', width: 2048, }, ], place_id: 'some place id 64', plus_code: { compound_code: '', global_code: '', }, rating: 4.4, reference: '', scope: '', types: [ 'restaurant', 'bar', 'food', 'point_of_interest', 'establishment', ], user_ratings_total: 9, vicinity: '92 Peter Street, Toronto', }, { business_status: 'OPERATIONAL', geometry: { location: { lat: 43.64723610000001, lng: -79.3765722, }, viewport: { northeast: { lat: 43.64853203029149, lng: -79.3754588697085, }, southwest: { lat: 43.64583406970849, lng: -79.3781568302915, }, }, }, icon: 'https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/restaurant-71.png', name: 'Oliver & Bonacini Café Grill, Yonge & Front', opening_hours: { open_now: false, }, photos: [ { height: 480, html_attributions: [''], photo_reference: '', width: 640, }, ], place_id: 'some place id 65', plus_code: { compound_code: '', global_code: '', }, price_level: 2, rating: 4, reference: '', scope: '', types: [ 'restaurant', 'night_club', 'bar', 'food', 'point_of_interest', 'establishment', ], user_ratings_total: 1382, vicinity: '33 Yonge Street, Toronto', }, { business_status: 'CLOSED_TEMPORARILY', geometry: { location: { lat: 43.6574337, lng: -79.3832666, }, viewport: { northeast: { lat: 43.6588368302915, lng: -79.38194011970849, }, southwest: { lat: 43.6561388697085, lng: -79.38463808029151, }, }, }, icon: 'https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/restaurant-71.png', name: 'Adega Restaurante', permanently_closed: true, photos: [ { height: 3456, html_attributions: [''], photo_reference: '', width: 4608, }, ], place_id: 'some place id 66', plus_code: { compound_code: '', global_code: '', }, price_level: 3, rating: 4.5, reference: '', scope: '', types: ['restaurant', 'food', 'point_of_interest', 'establishment'], user_ratings_total: 405, vicinity: '33 Elm Street, Toronto', }, { business_status: 'OPERATIONAL', geometry: { location: { lat: 43.650916, lng: -79.375685, }, viewport: { northeast: { lat: 43.6523067302915, lng: -79.3743523697085, }, southwest: { lat: 43.64960876970851, lng: -79.37705033029151, }, }, }, icon: 'https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/restaurant-71.png', name: 'Terroni', opening_hours: { open_now: true, }, photos: [ { height: 3840, html_attributions: [''], photo_reference: '', width: 5760, }, ], place_id: 'some place id 67', plus_code: { compound_code: '', global_code: '', }, price_level: 2, rating: 4.2, reference: '', scope: '', types: ['restaurant', 'food', 'point_of_interest', 'establishment'], user_ratings_total: 3698, vicinity: '57 Adelaide Street East, Toronto', }, { business_status: 'CLOSED_TEMPORARILY', geometry: { location: { lat: 43.6499945, lng: -79.3839517, }, viewport: { northeast: { lat: 43.6512935302915, lng: -79.3828103697085, }, southwest: { lat: 43.6485955697085, lng: -79.3855083302915, }, }, }, icon: 'https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/restaurant-71.png', name: 'The Keg Steakhouse + Bar - York Street', permanently_closed: true, photos: [ { height: 2268, html_attributions: [''], photo_reference: '', width: 4032, }, ], place_id: 'some place id 68', plus_code: { compound_code: '', global_code: '', }, price_level: 3, rating: 4.5, reference: '', scope: '', types: ['restaurant', 'food', 'point_of_interest', 'establishment'], user_ratings_total: 2954, vicinity: '165 York Street, Toronto', }, { business_status: 'CLOSED_TEMPORARILY', geometry: { location: { lat: 43.6479063, lng: -79.3780646, }, viewport: { northeast: { lat: 43.64915643029151, lng: -79.3766743197085, }, southwest: { lat: 43.64645846970851, lng: -79.3793722802915, }, }, }, icon: 'https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/restaurant-71.png', name: 'Jump Restaurant', permanently_closed: true, photos: [ { height: 636, html_attributions: [''], photo_reference: '', width: 960, }, ], place_id: 'some place id 69', plus_code: { compound_code: '', global_code: '', }, price_level: 3, rating: 4.2, reference: '', scope: '', types: [ 'bar', 'restaurant', 'food', 'point_of_interest', 'establishment', ], user_ratings_total: 781, vicinity: '18 Wellington Street West, Toronto', }, { business_status: 'OPERATIONAL', geometry: { location: { lat: 43.655701, lng: -79.37917499999999, }, viewport: { northeast: { lat: 43.6570138802915, lng: -79.37781131970848, }, southwest: { lat: 43.6543159197085, lng: -79.38050928029149, }, }, }, icon: 'https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/restaurant-71.png', name: 'The Senator', opening_hours: { open_now: false, }, photos: [ { height: 2048, html_attributions: [''], photo_reference: '', width: 2048, }, ], place_id: 'some place id 70', plus_code: { compound_code: '', global_code: '', }, price_level: 2, rating: 4.3, reference: '', scope: '', types: ['restaurant', 'food', 'point_of_interest', 'establishment'], user_ratings_total: 1371, vicinity: '249 Victoria Street, Toronto', }, { business_status: 'OPERATIONAL', geometry: { location: { lat: 43.6573753, lng: -79.383461, }, viewport: { northeast: { lat: 43.6587842802915, lng: -79.38213851970849, }, southwest: { lat: 43.6560863197085, lng: -79.3848364802915, }, }, }, icon: 'https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/restaurant-71.png', name: 'Donatello Restaurant', opening_hours: { open_now: false, }, photos: [ { height: 2048, html_attributions: [''], photo_reference: '', width: 1902, }, ], place_id: 'some place id 71', plus_code: { compound_code: '', global_code: '', }, price_level: 3, rating: 4.3, reference: '', scope: '', types: ['restaurant', 'food', 'point_of_interest', 'establishment'], user_ratings_total: 798, vicinity: '37 Elm Street, Toronto', }, { business_status: 'OPERATIONAL', geometry: { location: { lat: 43.6475793, lng: -79.38090369999999, }, viewport: { northeast: { lat: 43.6486975802915, lng: -79.3795757197085, }, southwest: { lat: 43.6459996197085, lng: -79.3822736802915, }, }, }, icon: 'https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/restaurant-71.png', name: 'Canoe', opening_hours: { open_now: false, }, photos: [ { height: 2988, html_attributions: [''], photo_reference: '', width: 5312, }, ], place_id: 'some place id 72', plus_code: { compound_code: '', global_code: '', }, price_level: 4, rating: 4.5, reference: '', scope: '', types: [ 'bar', 'restaurant', 'food', 'point_of_interest', 'establishment', ], user_ratings_total: 2019, vicinity: '66 Wellington Street West 54th floor, Toronto', }, { business_status: 'OPERATIONAL', geometry: { location: { lat: 43.64541, lng: -79.383865, }, viewport: { northeast: { lat: 43.6465791802915, lng: -79.3824437197085, }, southwest: { lat: 43.6438812197085, lng: -79.38514168029151, }, }, }, icon: 'https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/restaurant-71.png', name: "Jack Astor's Bar & Grill", opening_hours: { open_now: true, }, photos: [ { height: 3024, html_attributions: [''], photo_reference: '', width: 4032, }, ], place_id: 'some place id 73', plus_code: { compound_code: '', global_code: '', }, price_level: 2, rating: 4.1, reference: '', scope: '', types: [ 'bar', 'restaurant', 'food', 'point_of_interest', 'establishment', ], user_ratings_total: 4973, vicinity: '144 Front Street West, Toronto', }, { business_status: 'OPERATIONAL', geometry: { location: { lat: 43.6576597, lng: -79.381692, }, viewport: { northeast: { lat: 43.6590311302915, lng: -79.38024316970849, }, southwest: { lat: 43.6563331697085, lng: -79.3829411302915, }, }, }, icon: 'https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/restaurant-71.png', name: 'Salad King', opening_hours: { open_now: true, }, photos: [ { height: 1200, html_attributions: [''], photo_reference: '', width: 1343, }, ], place_id: 'some place id 74', plus_code: { compound_code: '', global_code: '', }, price_level: 1, rating: 4.3, reference: '', scope: '', types: ['restaurant', 'food', 'point_of_interest', 'establishment'], user_ratings_total: 3669, vicinity: '340 Yonge Street, Toronto', }, { business_status: 'CLOSED_TEMPORARILY', geometry: { location: { lat: 43.64735829999999, lng: -79.3866278, }, viewport: { northeast: { lat: 43.6486633302915, lng: -79.38526061970849, }, southwest: { lat: 43.6459653697085, lng: -79.38795858029151, }, }, }, icon: 'https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/restaurant-71.png', name: 'IL FORNELLO on King', permanently_closed: true, photos: [ { height: 1200, html_attributions: [''], photo_reference: '', width: 1800, }, ], place_id: 'some place id 75', plus_code: { compound_code: '', global_code: '', }, price_level: 2, rating: 4.1, reference: '', scope: '', types: [ 'meal_delivery', 'meal_takeaway', 'bar', 'restaurant', 'food', 'point_of_interest', 'establishment', ], user_ratings_total: 763, vicinity: '214 King Street West, Toronto', }, { business_status: 'OPERATIONAL', geometry: { location: { lat: 43.6502346, lng: -79.3889547, }, viewport: { northeast: { lat: 43.6516236302915, lng: -79.3876224697085, }, southwest: { lat: 43.6489256697085, lng: -79.39032043029151, }, }, }, icon: 'https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/restaurant-71.png', name: 'Little India Restaurant', opening_hours: { open_now: true, }, photos: [ { height: 1365, html_attributions: [''], photo_reference: '', width: 2048, }, ], place_id: 'some place id 76', plus_code: { compound_code: '', global_code: '', }, price_level: 2, rating: 4, reference: '', scope: '', types: [ 'meal_takeaway', 'restaurant', 'food', 'point_of_interest', 'establishment', ], user_ratings_total: 1976, vicinity: '255 Queen Street West, Toronto', }, { business_status: 'OPERATIONAL', geometry: { location: { lat: 43.6470917, lng: -79.37404169999999, }, viewport: { northeast: { lat: 43.6483725802915, lng: -79.37263056970849, }, southwest: { lat: 43.6456746197085, lng: -79.3753285302915, }, }, }, icon: 'https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/bar-71.png', name: 'Scotland Yard Pub', opening_hours: { open_now: true, }, photos: [ { height: 1055, html_attributions: [''], photo_reference: '', width: 2048, }, ], place_id: 'some place id 77', plus_code: { compound_code: '', global_code: '', }, price_level: 2, rating: 4.2, reference: '', scope: '', types: [ 'bar', 'restaurant', 'food', 'point_of_interest', 'establishment', ], user_ratings_total: 1202, vicinity: '56 The Esplanade, Toronto', }, { business_status: 'OPERATIONAL', geometry: { location: { lat: 43.64624899999999, lng: -79.390453, }, viewport: { northeast: { lat: 43.64768978029149, lng: -79.3891442697085, }, southwest: { lat: 43.64499181970849, lng: -79.3918422302915, }, }, }, icon: 'https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/restaurant-71.png', name: '309 Dhaba Indian Restaurant of Excellence', opening_hours: { open_now: true, }, photos: [ { height: 731, html_attributions: [''], photo_reference: '', width: 1024, }, ], place_id: 'some place id 78', plus_code: { compound_code: '', global_code: '', }, price_level: 2, rating: 3.3, reference: '', scope: '', types: [ 'meal_delivery', 'restaurant', 'food', 'point_of_interest', 'establishment', ], user_ratings_total: 1410, vicinity: '309 King Street West, Toronto', }, { business_status: 'CLOSED_TEMPORARILY', geometry: { location: { lat: 43.6503155, lng: -79.3847182, }, viewport: { northeast: { lat: 43.6517116802915, lng: -79.3833894197085, }, southwest: { lat: 43.6490137197085, lng: -79.3860873802915, }, }, }, icon: 'https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/restaurant-71.png', name: 'VOLOS', permanently_closed: true, photos: [ { height: 3522, html_attributions: [''], photo_reference: '', width: 5283, }, ], place_id: 'some place id 79', plus_code: { compound_code: '', global_code: '', }, price_level: 3, rating: 4.4, reference: '', scope: '', types: ['restaurant', 'food', 'point_of_interest', 'establishment'], user_ratings_total: 763, vicinity: '133 Richmond Street West, Toronto', }, { business_status: 'OPERATIONAL', geometry: { location: { lat: 43.6506177, lng: -79.3882088, }, viewport: { northeast: { lat: 43.65190503029149, lng: -79.3868345697085, }, southwest: { lat: 43.6492070697085, lng: -79.3895325302915, }, }, }, icon: 'https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/restaurant-71.png', name: 'PLANTA Queen', opening_hours: { open_now: true, }, photos: [ { height: 3840, html_attributions: [''], photo_reference: '', width: 5760, }, ], place_id: 'some place id 80', plus_code: { compound_code: '', global_code: '', }, price_level: 3, rating: 4.4, reference: '', scope: '', types: ['restaurant', 'food', 'point_of_interest', 'establishment'], user_ratings_total: 1064, vicinity: '180 Queen Street West, Toronto', }, ], status: 'OK', };
const dataFiles = [ 'test/images/*.jpg', 'test/images/*.png', 'test/data/*.json', 'test/media/*.mp4', 'weights/**/*', 'weights_uncompressed/**/*', 'weights_unused/**/*' ].map(pattern => ({ pattern, watched: false, included: false, served: true, nocache: false })) module.exports = function(config) { config.set({ frameworks: ['jasmine', 'karma-typescript'], files: [ 'src/**/*.ts', 'test/**/*.ts' ].concat(dataFiles), preprocessors: { '**/*.ts': ['karma-typescript'] }, karmaTypescriptConfig: { tsconfig: 'tsconfig.test.json' }, browsers: ['Chrome'], browserNoActivityTimeout: 120000, captureTimeout: 60000, client: { jasmine: { timeoutInterval: 60000 } } }) }
/** * <p>Title : 本地服务</p> * <p>Description : 开发类服务工具</p> * <p>Date : 2018/10/8 </p> * * @author : hejie */ const http = require('http') const path = require('path') const fs = require('fs') const child_process = require('child_process') const bodyParser = require('body-parser') const express = require('express') const apiRoutes = express.Router() let appConfig = require('../src/appConfig') const menuPath = 'menu/tree.json' const createFile = function(filePath, fs, callback) { // 1、创建目录 createDir(filePath, fs) // 2、创建文件 const writeStream = fs.createWriteStream(filePath) if (callback) writeStream.on('close', callback) } const createDir = function(filePath, fs) { const sep = path.sep const folders = path.dirname(filePath).split(sep) let p = '' while (folders.length) { p += folders.shift() + sep if (!fs.existsSync(p)) { fs.mkdirSync(p) } } } const getServerOption = function(_path) { const filePath = path.resolve(__dirname, '../src/appConfig.json') const data = JSON.parse(fs.readFileSync(filePath, { encoding: 'utf-8' })) const activeAPP = data[data.enable] const host = activeAPP['appUrl'].substring(7, activeAPP['appUrl'].indexOf(':', 7)) const port = activeAPP['appUrl'].substring(activeAPP['appUrl'].indexOf(':', 7) + 1, activeAPP['appUrl'].indexOf('/', 7)) return { host: host, port: port, path: '/' + activeAPP['code'] + _path, method: 'post', headers: { 'Content-Type': 'application/json' } } } module.exports = { appUrl: appConfig[appConfig.enable] ? appConfig[appConfig.enable].appUrl : 'http://localhost:8080/demo', before(app) { app.use('/', apiRoutes) // app.use(bodyParser.urlencoded({extended: true})) app.post('/getAppConfig', bodyParser.json(), (req, res) => { const filePath = path.resolve(__dirname, '../src/appConfig.json') const data = JSON.parse(fs.readFileSync(filePath, { encoding: 'utf-8' })) res.json(data) }) app.post('/activeApp', bodyParser.json(), (req, res) => { const filePath = path.resolve(__dirname, '../src/appConfig.json') const data = JSON.parse(fs.readFileSync(filePath, { encoding: 'utf-8' })) res.json(data[data.enable]) }) app.post('/setActive', bodyParser.json(), (req, res) => { const filePath = path.resolve(__dirname, '../src/appConfig.json') const data = JSON.parse(fs.readFileSync(filePath, { encoding: 'utf-8' })) data['enable'] = req.body.code const content = JSON.stringify(data, null, 2) fs.exists(filePath, function(exist) { if (!exist) createFile(filePath, fs) fs.writeFile(filePath, content, function(err) { if (err) { res.json({ status: false, msg: filePath + '保存失败' }) } appConfig = JSON.parse(content) res.json({ status: true, msg: '' }) }) }) }) app.post('/saveAppConfig', bodyParser.json(), (req, res) => { const filePath = path.resolve(__dirname, '../src/appConfig.json') const content = req.body.appConfig fs.exists(filePath, function(exist) { // 文件不存在,则创建文件 if (!exist) createFile(filePath, fs) // 写入内容 fs.writeFile(filePath, content, function(err) { if (err) { res.json({ status: false, msg: filePath + '保存失败' }) } appConfig = JSON.parse(content) res.json({ status: true, msg: '' }) }) }) }) app.post('/getMenu', bodyParser.json(), (req, res) => { const filePath = appConfig[appConfig.enable].baseDir + menuPath let result = { status: true } try { result.data = JSON.parse(fs.readFileSync(filePath, { encoding: 'utf-8' })) } catch (e) { result = { status: false, msg: filePath + '获取数据失败' } } res.json(result) }) app.post('/saveMenu', bodyParser.json(), (req, res) => { let filePath = appConfig[appConfig.enable].baseDir + menuPath let content = req.body.content if (req.body.create) { filePath = appConfig[appConfig.enable].baseDir + menuPath content = '[]' } fs.exists(filePath, function(exist) { // 文件不存在,则创建文件 if (!exist) createFile(filePath, fs) // 写入内容 console.error(content) fs.writeFile(filePath, content, function(err) { if (err) { res.json({ status: false, msg: filePath + 'menu保存失败' }) } res.json({ status: true, msg: '' }) }) }) }) app.post('/getJson', bodyParser.json(), (req, res) => { const filePath = appConfig[appConfig.enable].baseDir + req.body.jsonPath let result = { status: true } try { result.data = JSON.parse(fs.readFileSync(filePath, { encoding: 'utf-8' })) } catch (e) { result = { status: false, msg: filePath + '获取数据失败' } } res.json(result) }) app.post('/saveJson', bodyParser.json(), (req, res) => { const filePath = appConfig[appConfig.enable].baseDir + req.body.jsonPath const content = req.body.content fs.exists(filePath, function(exist) { // 文件不存在,则创建文件 if (!exist) createFile(filePath, fs) // 写入内容 fs.writeFile(filePath, content, function(err) { if (err) { res.json({ status: false, msg: filePath + '保存失败' }) } res.json({ status: true, msg: '' }) }) }) }) app.post('/generateScaffold', bodyParser.json(), (req, res) => { try { // 1、应用配置 const config = req.body const filePath = path.resolve(__dirname, '../src/appConfig.json') const data = JSON.parse(fs.readFileSync(filePath, { encoding: 'utf-8' })) if (data[config.code]) { res.json({ status: false, msg: config.code + ', 应用已存在。' }) return } data[config.code] = config // 2、copy工程样板 const projectDir = config.projectDir const appDir = projectDir + config.code + '/' const appScaffold = path.resolve(__dirname, '../scaffold/app') // 2.1、创建目标文件夹 createDir(appDir, fs) // 2.2、copy样板到目标文件夹 child_process.spawnSync('cp', ['-r', appScaffold, appDir]) // 2.3、修改配置 // 2.3.1、系统配置 const sysConfig = appDir + 'src/main/resources/config/application-app.yml' let src = fs.readFileSync(sysConfig, { encoding: 'utf-8' }) src = src.replace(/\${{code}}/g, config.code) src = src.replace(/\${{port}}/g, config.port) src = src.replace(/\${{appBizDir}}/g, config.appBizDir) fs.writeFileSync(sysConfig, src) // 2.3.2、mapper生成器 const gConfig = appDir + 'src/main/resources/generatorConfig.xml' let g_config = fs.readFileSync(gConfig, { encoding: 'utf-8' }) g_config = g_config.replace('${{appBizDir}}', config.appBizDir) fs.writeFileSync(gConfig, g_config) // 3、copy配置样板 const appBizDir = config.appBizDir const bizScaffold = path.resolve(__dirname, '../scaffold/biz') createDir(appBizDir, fs) child_process.spawnSync('cp', ['-r', bizScaffold, appBizDir]) const confFile = appBizDir + 'conf/' + config.code + '.yml' createFile(confFile, fs) // 4、copy开发数据样板 const baseDir = config.baseDir const dataScaffold = path.resolve(__dirname, '../scaffold/data') createDir(baseDir, fs) child_process.spawnSync('cp', ['-r', dataScaffold, baseDir]) // 5、保存应用配置 const content = JSON.stringify(data, null, 2) fs.exists(filePath, function(exist) { if (!exist) createFile(filePath, fs) fs.writeFile(filePath, content, function(err) { if (err) { res.json({ status: false, msg: filePath + '创建失败' }) } }) }) } catch (e) { console.error(e.message) res.json({ status: false, msg: '应用创建失败' }) } res.json({ status: true, msg: '' }) }) app.post('/api', bodyParser.json(), (req, resp) => { const _path = req.body['_path'] || '/' const iData = Object.assign({}, req.body) delete iData['_path'] const input = JSON.stringify(iData) let output = '' const options = getServerOption(_path) const connect = http.request(options, function(res) { res.setEncoding('utf8') res.on('data', function(chunk) { output += chunk }) res.on('end', function() { resp.json(JSON.parse(output)) }) }) connect.on('error', function(e) { console.error(e.message) }) connect.write(input) connect.end() }) } }
/* postal Author: Jim Cowart (http://freshbrewedcode.com/jimcowart) License: Dual licensed MIT (http://www.opensource.org/licenses/mit-license) & GPL (http://www.opensource.org/licenses/gpl-license) Version 0.7.3 */ (function ( root, factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define( ["underscore"], function ( _ ) { return factory( _, root ); } ); } else { // Browser globals factory( root._, root ); } }( this, function ( _, global, undefined ) { var DEFAULT_CHANNEL = "/", DEFAULT_PRIORITY = 50, DEFAULT_DISPOSEAFTER = 0, SYSTEM_CHANNEL = "postal", NO_OP = function () { }; var ConsecutiveDistinctPredicate = function () { var previous; return function ( data ) { var eq = false; if ( _.isString( data ) ) { eq = data === previous; previous = data; } else { eq = _.isEqual( data, previous ); previous = _.clone( data ); } return !eq; }; }; var DistinctPredicate = function () { var previous = []; return function (data) { var isDistinct = !_.any(previous, function (p) { if (_.isObject(data) || _.isArray(data)) { return _.isEqual(data, p); } return data === p; }); if (isDistinct) { previous.push(data); } return isDistinct; }; }; var ChannelDefinition = function ( channelName, defaultTopic ) { this.channel = channelName || DEFAULT_CHANNEL; this._topic = defaultTopic || ""; }; ChannelDefinition.prototype = { subscribe : function () { var len = arguments.length; if ( len === 1 ) { return new SubscriptionDefinition( this.channel, this._topic, arguments[0] ); } else if ( len === 2 ) { return new SubscriptionDefinition( this.channel, arguments[0], arguments[1] ); } }, publish : function ( obj ) { var _obj = obj || {}; var envelope = { channel : this.channel, topic : this._topic, data : _obj }; // If this is an envelope.... if ( _obj.topic && _obj.data ) { envelope = _obj; envelope.channel = envelope.channel || this.channel; } envelope.timeStamp = new Date(); postal.configuration.bus.publish( envelope ); return envelope; }, topic : function ( topic ) { if ( topic === this._topic ) { return this; } return new ChannelDefinition( this.channel, topic ); } }; var SubscriptionDefinition = function ( channel, topic, callback ) { this.channel = channel; this.topic = topic; this.callback = callback; this.priority = DEFAULT_PRIORITY; this.constraints = new Array( 0 ); this.maxCalls = DEFAULT_DISPOSEAFTER; this.onHandled = NO_OP; this.context = null; postal.configuration.bus.publish( { channel : SYSTEM_CHANNEL, topic : "subscription.created", timeStamp : new Date(), data : { event : "subscription.created", channel : channel, topic : topic } } ); postal.configuration.bus.subscribe( this ); }; SubscriptionDefinition.prototype = { unsubscribe : function () { postal.configuration.bus.unsubscribe( this ); postal.configuration.bus.publish( { channel : SYSTEM_CHANNEL, topic : "subscription.removed", timeStamp : new Date(), data : { event : "subscription.removed", channel : this.channel, topic : this.topic } } ); }, defer : function () { var fn = this.callback; this.callback = function ( data ) { setTimeout( fn, 0, data ); }; return this; }, disposeAfter : function ( maxCalls ) { if ( _.isNaN( maxCalls ) || maxCalls <= 0 ) { throw "The value provided to disposeAfter (maxCalls) must be a number greater than zero."; } var fn = this.onHandled; var dispose = _.after( maxCalls, _.bind( function () { this.unsubscribe( this ); }, this ) ); this.onHandled = function () { fn.apply( this.context, arguments ); dispose(); }; return this; }, distinctUntilChanged : function () { this.withConstraint( new ConsecutiveDistinctPredicate() ); return this; }, distinct : function () { this.withConstraint( new DistinctPredicate() ); return this; }, once: function() { this.disposeAfter(1); }, withConstraint : function ( predicate ) { if ( !_.isFunction( predicate ) ) { throw "Predicate constraint must be a function"; } this.constraints.push( predicate ); return this; }, withConstraints : function ( predicates ) { var self = this; if ( _.isArray( predicates ) ) { _.each( predicates, function ( predicate ) { self.withConstraint( predicate ); } ); } return self; }, withContext : function ( context ) { this.context = context; return this; }, withDebounce : function ( milliseconds ) { if ( _.isNaN( milliseconds ) ) { throw "Milliseconds must be a number"; } var fn = this.callback; this.callback = _.debounce( fn, milliseconds ); return this; }, withDelay : function ( milliseconds ) { if ( _.isNaN( milliseconds ) ) { throw "Milliseconds must be a number"; } var fn = this.callback; this.callback = function ( data ) { setTimeout( function () { fn( data ); }, milliseconds ); }; return this; }, withPriority : function ( priority ) { if ( _.isNaN( priority ) ) { throw "Priority must be a number"; } this.priority = priority; postal.configuration.bus.changePriority( this ); return this; }, withThrottle : function ( milliseconds ) { if ( _.isNaN( milliseconds ) ) { throw "Milliseconds must be a number"; } var fn = this.callback; this.callback = _.throttle( fn, milliseconds ); return this; }, subscribe : function ( callback ) { this.callback = callback; return this; } }; var bindingsResolver = { cache : { }, compare : function ( binding, topic ) { if ( this.cache[topic] && this.cache[topic][binding] ) { return true; } var pattern = ("^" + binding.replace( /\./g, "\\." ) // escape actual periods .replace( /\*/g, "[A-Z,a-z,0-9]*" ) // asterisks match any alpha-numeric 'word' .replace( /#/g, ".*" ) + "$") // hash matches 'n' # of words (+ optional on start/end of topic) .replace( "\\..*$", "(\\..*)*$" ) // fix end of topic matching on hash wildcards .replace( "^.*\\.", "^(.*\\.)*" ); // fix beginning of topic matching on hash wildcards var rgx = new RegExp( pattern ); var result = rgx.test( topic ); if ( result ) { if ( !this.cache[topic] ) { this.cache[topic] = {}; } this.cache[topic][binding] = true; } return result; }, reset : function () { this.cache = {}; } }; var localBus = { addWireTap : function ( callback ) { var self = this; self.wireTaps.push( callback ); return function () { var idx = self.wireTaps.indexOf( callback ); if ( idx !== -1 ) { self.wireTaps.splice( idx, 1 ); } }; }, changePriority : function ( subDef ) { var idx, found; if ( this.subscriptions[subDef.channel] && this.subscriptions[subDef.channel][subDef.topic] ) { this.subscriptions[subDef.channel][subDef.topic] = _.without( this.subscriptions[subDef.channel][subDef.topic], subDef ); idx = this.subscriptions[subDef.channel][subDef.topic].length - 1; for ( ; idx >= 0; idx-- ) { if ( this.subscriptions[subDef.channel][subDef.topic][idx].priority <= subDef.priority ) { this.subscriptions[subDef.channel][subDef.topic].splice( idx + 1, 0, subDef ); found = true; break; } } if ( !found ) { this.subscriptions[subDef.channel][subDef.topic].unshift( subDef ); } } }, publish : function ( envelope ) { _.each( this.wireTaps, function ( tap ) { tap( envelope.data, envelope ); } ); if ( this.subscriptions[envelope.channel] ) { _.each( this.subscriptions[envelope.channel], function ( topic ) { // TODO: research faster ways to handle this than _.clone _.each( _.clone( topic ), function ( subDef ) { if ( postal.configuration.resolver.compare( subDef.topic, envelope.topic ) ) { if ( _.all( subDef.constraints, function ( constraint ) { return constraint( envelope.data, envelope ); } ) ) { if ( typeof subDef.callback === 'function' ) { subDef.callback.apply( subDef.context, [envelope.data, envelope] ); subDef.onHandled(); } } } } ); } ); } }, reset : function () { if ( this.subscriptions ) { _.each( this.subscriptions, function ( channel ) { _.each( channel, function ( topic ) { while ( topic.length ) { topic.pop().unsubscribe(); } } ); } ); this.subscriptions = {}; } }, subscribe : function ( subDef ) { var idx, found, fn, channel = this.subscriptions[subDef.channel], subs; if ( !channel ) { channel = this.subscriptions[subDef.channel] = {}; } subs = this.subscriptions[subDef.channel][subDef.topic]; if ( !subs ) { subs = this.subscriptions[subDef.channel][subDef.topic] = new Array( 0 ); } subs.push( subDef ); return subDef; }, subscriptions : {}, wireTaps : new Array( 0 ), unsubscribe : function ( config ) { if ( this.subscriptions[config.channel][config.topic] ) { var len = this.subscriptions[config.channel][config.topic].length, idx = 0; for ( ; idx < len; idx++ ) { if ( this.subscriptions[config.channel][config.topic][idx] === config ) { this.subscriptions[config.channel][config.topic].splice( idx, 1 ); break; } } } } }; var publishPicker = { "1" : function ( envelope ) { if ( !envelope ) { throw new Error( "publishing from the 'global' postal.publish call requires a valid envelope." ); } envelope.channel = envelope.channel || DEFAULT_CHANNEL; envelope.timeStamp = new Date(); postal.configuration.bus.publish( envelope ); return envelope; }, "2" : function ( topic, data ) { var envelope = { channel : DEFAULT_CHANNEL, topic : topic, timeStamp : new Date(), data : data }; postal.configuration.bus.publish( envelope ); return envelope; }, "3" : function ( channel, topic, data ) { var envelope = { channel : channel, topic : topic, timeStamp : new Date(), data : data }; postal.configuration.bus.publish( envelope ); return envelope; } }, channelPicker = { "1" : function ( chn ) { var channel = chn, topic, options = {}; if ( Object.prototype.toString.call( channel ) === "[object String]" ) { channel = DEFAULT_CHANNEL; topic = chn; } else { channel = chn.channel || DEFAULT_CHANNEL; topic = chn.topic; options = chn.options || options; } return new postal.channelTypes[ options.type || "local" ]( channel, topic ); }, "2" : function ( chn, tpc ) { var channel = chn, topic = tpc, options = {}; if ( Object.prototype.toString.call( tpc ) === "[object Object]" ) { channel = DEFAULT_CHANNEL; topic = chn; options = tpc; } return new postal.channelTypes[ options.type || "local" ]( channel, topic ); }, "3" : function ( channel, topic, options ) { return new postal.channelTypes[ options.type || "local" ]( channel, topic ); } }, sessionInfo = {}; // save some setup time, albeit tiny localBus.subscriptions[SYSTEM_CHANNEL] = {}; var postal = { configuration : { bus : localBus, resolver : bindingsResolver, DEFAULT_CHANNEL : DEFAULT_CHANNEL, DEFAULT_PRIORITY : DEFAULT_PRIORITY, DEFAULT_DISPOSEAFTER : DEFAULT_DISPOSEAFTER, SYSTEM_CHANNEL : SYSTEM_CHANNEL }, channelTypes : { local : ChannelDefinition }, channel : function () { var len = arguments.length; if ( channelPicker[len] ) { return channelPicker[len].apply( this, arguments ); } }, subscribe : function ( options ) { var callback = options.callback, topic = options.topic, channel = options.channel || DEFAULT_CHANNEL; return new SubscriptionDefinition( channel, topic, callback ); }, publish : function () { var len = arguments.length; if ( publishPicker[len] ) { return publishPicker[len].apply( this, arguments ); } }, addWireTap : function ( callback ) { return this.configuration.bus.addWireTap( callback ); }, linkChannels : function ( sources, destinations ) { var result = []; if ( !_.isArray( sources ) ) { sources = [sources]; } if ( !_.isArray( destinations ) ) { destinations = [destinations]; } _.each( sources, function ( source ) { var sourceTopic = source.topic || "#"; _.each( destinations, function ( destination ) { var destChannel = destination.channel || DEFAULT_CHANNEL; result.push( postal.subscribe( { channel : source.channel || DEFAULT_CHANNEL, topic : source.topic || "#", callback : function ( data, env ) { var newEnv = _.clone( env ); newEnv.topic = _.isFunction( destination.topic ) ? destination.topic( env.topic ) : destination.topic || env.topic; newEnv.channel = destChannel; newEnv.data = data; postal.publish( newEnv ); } } ) ); } ); } ); return result; }, utils : { getSubscribersFor : function () { var channel = arguments[ 0 ], tpc = arguments[ 1 ], result = []; if ( arguments.length === 1 ) { if ( Object.prototype.toString.call( channel ) === "[object String]" ) { channel = postal.configuration.DEFAULT_CHANNEL; tpc = arguments[ 0 ]; } else { channel = arguments[ 0 ].channel || postal.configuration.DEFAULT_CHANNEL; tpc = arguments[ 0 ].topic; } } if ( postal.configuration.bus.subscriptions[ channel ] && postal.configuration.bus.subscriptions[ channel ].hasOwnProperty( tpc ) ) { result = postal.configuration.bus.subscriptions[ channel ][ tpc ]; } return result; }, reset : function () { postal.configuration.bus.reset(); postal.configuration.resolver.reset(); } } }; global.postal = postal; return postal; } ));
/** @jsx jsx */ import { jsx, Box } from "theme-ui" import { graphql } from "gatsby" export const fragment = graphql` fragment contentBlockFragment on WPGraphQL_Page_Flexlayouts_FlexibleLayouts_ContentBlock { content } ` export const ContentBlock = ({ content }) => ( <Box dangerouslySetInnerHTML={{ __html: content }} sx={{ maxWidth: `l`, mx: `auto`, mb: 7, mt: 5, }} /> )
import Dump from '@wesbos/dump' import axios from 'axios' import React, { useEffect, useState } from 'react' import styled from 'styled-components' import { CryptoCard } from '../components/crypto-card' import { Layout } from '../components/layout' import { useTimeDifference } from '../hooks/use-time-difference' export const autoGrid = (minColumnWidth = 250, gridGap = 0) => ({ display: 'grid', gridTemplateColumns: `repeat(auto-fill, minmax(${minColumnWidth}px,1fr))`, gridGap, }) const Gallery = styled.div({ ...autoGrid(220, 20), }) export default ({ data }) => { const { data: coinData } = data.coinloreCoinlore const timeDifference = useTimeDifference() const [runTimeData, setRunTimeData] = useState({}) const [loading, setLoading] = useState(true) useEffect(() => { async function getRunTimeData() { const res = await axios( 'https://api.coinlore.com/api/tickers/?start=1&limit=10' ) const { data } = res.data setRunTimeData(data) setLoading(false) } getRunTimeData() }, []) const timeSinceBuild = 3 if (loading && timeDifference > timeSinceBuild) return ( <Layout> <p>Build-time data stale fetching new data...</p> </Layout> ) let coinloreData = {} if (timeDifference > timeSinceBuild) { // use runtime data coinloreData = runTimeData } else { // use build time data coinloreData = coinData } return ( <Layout> <p>Minutes since build: {timeDifference}</p> <Gallery> {coinloreData.map(coin => ( <CryptoCard id={coin.id} symbol={coin.symbol} name={coin.name} price={coin.price_usd} pcChange1h={coin.percent_change_1h} pcChange24h={coin.percent_change_24h} pcChange7d={coin.percent_change_7d} /> ))} </Gallery> <Dump data={coinloreData} /> </Layout> ) } export const GatsbyQuery = graphql` query CoinloreQuery { coinloreCoinlore { data { symbol name nameid rank price_usd percent_change_24h percent_change_1h percent_change_7d price_btc market_cap_usd volume24 volume24a csupply tsupply msupply } } } `
/* eslint-disable no-param-reassign */ /** @typedef {import('./types').SpaOptions} SpaOptions */ /** @typedef {import('polyfills-loader').PolyfillsLoaderConfig} PolyfillsLoaderConfig */ const merge = require('deepmerge'); const html = require('@open-wc/rollup-plugin-html'); const polyfillsLoader = require('@open-wc/rollup-plugin-polyfills-loader'); const path = require('path'); const { generateSW } = require('rollup-plugin-workbox'); const { createBasicConfig } = require('./createBasicConfig'); const { pluginWithOptions, applyServiceWorkerRegistration, isFalsy } = require('./utils'); const { defaultPolyfills } = require('./polyfills'); /** * @param {SpaOptions} options */ function createSpaConfig(options) { const basicConfig = createBasicConfig(options); /** @type {SpaOptions} */ const userOptions = merge( { html: true, polyfillsLoader: true, workbox: true, injectServiceWorker: false, }, options, ); let outputDir = basicConfig.output.dir; let swPath; if (typeof userOptions.workbox === 'boolean') { swPath = './sw.js'; } else { swPath = userOptions.workbox.swDest.replace(`${outputDir}/`, ''); } const applySw = htmlString => applyServiceWorkerRegistration(htmlString, swPath); const htmlPlugin = pluginWithOptions(html, userOptions.html, { minify: !userOptions.developmentMode, transform: [userOptions.injectServiceWorker && applySw].filter(isFalsy), inject: false, }); let polyfillsLoaderConfig = { polyfills: {}, minify: !userOptions.developmentMode, }; if (userOptions.legacyBuild) { if (!htmlPlugin) { throw new Error('Cannot generate multi build outputs when html plugin is disabled'); } outputDir = basicConfig.output[0].dir; basicConfig.output[0].plugins.push(htmlPlugin.addOutput('module')); basicConfig.output[1].plugins.push(htmlPlugin.addOutput('nomodule')); polyfillsLoaderConfig = { modernOutput: { name: 'module', type: 'module', }, legacyOutput: { name: 'nomodule', type: 'systemjs', test: // test if browser supports dynamic imports (and thus modules). import.meta.url cannot be tested "(function(){try{Function('!function(){import(_)}').call();return false;}catch(_){return true}})()", }, minify: !userOptions.developmentMode, polyfills: defaultPolyfills, }; } const workboxPlugin = pluginWithOptions( generateSW, userOptions.workbox, { // Keep 'legacy-*.js' just for retro compatibility globIgnores: ['polyfills/*.js', 'legacy-*.js', 'nomodule-*.js'], navigateFallback: '/index.html', // where to output the generated sw swDest: path.join(process.cwd(), outputDir, 'sw.js'), // directory to match patterns against to be precached globDirectory: path.join(process.cwd(), outputDir), // cache any html js and css by default globPatterns: ['**/*.{html,js,css,webmanifest}'], skipWaiting: true, clientsClaim: true, runtimeCaching: [ { urlPattern: 'polyfills/*.js', handler: 'CacheFirst', }, ], }, () => {}, ); if (userOptions.workbox) { if (basicConfig.output.length > 1) { const lastOutput = basicConfig.output.length - 1; basicConfig.output[lastOutput].plugins.push(workboxPlugin); } else { basicConfig.output.plugins.push(workboxPlugin); } } return merge(basicConfig, { plugins: [ // create HTML file output htmlPlugin, // inject polyfills loader into HTML pluginWithOptions(polyfillsLoader, userOptions.polyfillsLoader, polyfillsLoaderConfig), ], }); } module.exports = { createSpaConfig };
(window["webpackJsonp"]=window["webpackJsonp"]||[]).push([["pages-index-index"],{"0234":function(t,e,a){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i={props:{facade:{type:[Object,Array]},content:{type:[Object,Array]}}};e.default=i},"0341":function(t,e,a){"use strict";var i;a.d(e,"b",(function(){return n})),a.d(e,"c",(function(){return o})),a.d(e,"a",(function(){return i}));var n=function(){var t=this,e=t.$createElement,a=t._self._c||e;return a("v-uni-view",{staticClass:"blank",style:{height:t.facade.height+"px",backgroundColor:t.facade.background_color}})},o=[]},"03ab":function(t,e,a){var i=a("e71b");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var n=a("5c0d").default;n("21549725",i,!0,{sourceMap:!1,shadowMode:!1})},"04a7":function(t,e,a){var i=a("e2e9");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var n=a("5c0d").default;n("551de361",i,!0,{sourceMap:!1,shadowMode:!1})},"05a7":function(t,e,a){"use strict";a.r(e);var i=a("5420"),n=a("d8ae");for(var o in n)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return n[t]}))}(o);a("541d");var r,s=a("5d80"),c=Object(s["a"])(n["default"],i["b"],i["c"],!1,null,"0723e115",null,!1,i["a"],r);e["default"]=c.exports},"06c3":function(t,e,a){"use strict";var i=a("65da"),n=a.n(i);n.a},"071a":function(t,e,a){"use strict";a.r(e);var i=a("dcf8"),n=a.n(i);for(var o in i)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return i[t]}))}(o);e["default"]=n.a},"07dd":function(t,e,a){"use strict";a.r(e);var i=a("9c91"),n=a("724d");for(var o in n)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return n[t]}))}(o);var r,s=a("5d80"),c=Object(s["a"])(n["default"],i["b"],i["c"],!1,null,null,null,!1,i["a"],r);e["default"]=c.exports},"0b2f":function(t,e,a){"use strict";var i;a.d(e,"b",(function(){return n})),a.d(e,"c",(function(){return o})),a.d(e,"a",(function(){return i}));var n=function(){var t=this,e=t.$createElement,a=t._self._c||e;return a("v-uni-view",{attrs:{"data-theme":t.theme}},[a("he-popup",{attrs:{mode:"center","border-radius":16,zoom:!1,width:"590rpx",height:"746rpx"},model:{value:t.showModal,callback:function(e){t.showModal=e},expression:"showModal"}},[a("v-uni-view",{staticClass:"he-login-box flex flex-direction align-center"},[a("v-uni-image",{staticClass:"login-bg",attrs:{src:t.ipAddress+"/login-model-bg.png"}}),a("v-uni-view",{staticClass:"title"},[t._v("请授权微信登录")]),a("v-uni-view",{staticClass:"assist-text"},[t._v("以便我们为您提供更好的服务")]),a("v-uni-button",{staticClass:"cu-btn",on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.decryptUserInfo.apply(void 0,arguments)}}},[t._v("微信一键授权登录")]),a("v-uni-view",{staticClass:"assist-text",on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.notLogIn.apply(void 0,arguments)}}},[t._v("暂不登录")])],1)],1),a("user-newuser-coupon",{attrs:{coupon:t.userInfo.register&&t.userInfo.register.coupon_list},model:{value:t.isNewuser,callback:function(e){t.isNewuser=e},expression:"isNewuser"}})],1)},o=[]},"0b7e":function(t,e,a){"use strict";var i=a("99ca").default;Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var n=i(a("c2c4")),o={name:"he-become-distributor",components:{hePopup:n.default},props:{value:Boolean},data:function(){return{}},computed:{showModal:{get:function(t){var e=t.$store;return e.state.user.showBecomeDistributor},set:function(t){this.$store.state.user.showBecomeDistributor=t}}},methods:{routerPromoter:function(){this.showModal=!1,this.$store.dispatch("user/getUserInfo").then((function(){uni.navigateTo({url:"/promoter/pages/index"})}))}}};e.default=o},"0d7c":function(t,e,a){"use strict";var i=a("b342"),n=a.n(i);n.a},"0e49":function(t,e,a){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0,a("4cfc"),a("f9ee"),a("58ec"),a("c342"),a("5f3f"),a("7091");var i={name:"UniNoticeBar",props:{text:{type:String,default:""},moreText:{type:String,default:""},backgroundColor:{type:String,default:"#fffbe8"},speed:{type:Number,default:100},color:{type:String,default:"#de8c17"},moreColor:{type:String,default:"#999999"},single:{type:[Boolean,String],default:!1},scrollable:{type:[Boolean,String],default:!1},showIcon:{type:[Boolean,String],default:!1},iconUrl:{type:String,default:""},showGetMore:{type:[Boolean,String],default:!1},showClose:{type:[Boolean,String],default:!1}},data:function(){var t="Uni_".concat(Math.ceil(1e6*Math.random()).toString(36)),e="Uni_".concat(Math.ceil(1e6*Math.random()).toString(36));return{textWidth:0,boxWidth:0,wrapWidth:"",webviewHide:!1,elId:t,elIdBox:e,show:!0,animationDuration:"none",animationPlayState:"paused",animationDelay:"0s"}},mounted:function(){var t=this;this.$nextTick((function(){t.initSize()}))},watch:{speed:function(){var t=this;this.$nextTick((function(){t.initSize()}))}},methods:{initSize:function(){var t=this;if(this.scrollable){var e=[],a=new Promise((function(e,a){uni.createSelectorQuery().in(t).select("#".concat(t.elId)).boundingClientRect().exec((function(a){t.textWidth=a[0].width,e()}))})),i=new Promise((function(e,a){uni.createSelectorQuery().in(t).select("#".concat(t.elIdBox)).boundingClientRect().exec((function(a){t.boxWidth=a[0].width,e()}))}));e.push(a),e.push(i),Promise.all(e).then((function(){t.animationDuration="".concat(t.textWidth/t.speed,"s"),t.animationDelay="-".concat(t.boxWidth/t.speed,"s"),setTimeout((function(){t.animationPlayState="running"}),1e3)}))}},loopAnimation:function(){},clickMore:function(){this.$emit("getmore")},close:function(){this.show=!1,this.$emit("close")},onClick:function(){this.$emit("click")}}};e.default=i},"0f7c":function(t,e,a){"use strict";var i;a.d(e,"b",(function(){return n})),a.d(e,"c",(function(){return o})),a.d(e,"a",(function(){return i}));var n=function(){var t=this,e=t.$createElement,a=t._self._c||e;return a("he-popup",{attrs:{mode:"center","background-color":"transparent",zoom:!1,width:"100%",height:"100%"},model:{value:t.showModal,callback:function(e){t.showModal=e},expression:"showModal"}},[a("v-uni-view",{staticClass:"le-popup",on:{touchmove:function(e){e.stopPropagation(),e.preventDefault(),arguments[0]=e=t.$handleEvent(e),function(){}.apply(void 0,arguments)}}},[a("v-uni-view",{staticClass:"he-box"},[a("v-uni-view",{staticClass:"he-box__close flex align-center justify-center",on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.closeModal.apply(void 0,arguments)}}},[a("v-uni-text",{staticClass:"iconfont iconpopup_close"})],1),a("v-uni-image",{staticClass:"le-box-image",attrs:{src:t.ipAddress+"/login-newuser-coupon.png"}}),a("v-uni-view",{staticClass:"le-content"},[a("v-uni-scroll-view",{staticClass:"le-body",attrs:{"scroll-y":!0}},t._l(t.coupon,(function(e,i){return a("v-uni-view",{key:i,staticClass:"he-item flex"},[a("v-uni-view",{staticClass:"he-left"},[a("v-uni-view",{staticClass:"le-price"},[t._v(t._s(t._f("setNumber")(e.coupon.sub_price)))]),a("v-uni-view",{staticClass:"le-limit"},[Number(e.coupon.min_price)>0?[t._v("满"+t._s(Number(e.coupon.min_price))+"可用")]:[t._v("无门槛使用")]],2)],1),a("v-uni-view",{staticClass:"he-center"},[a("v-uni-view",{staticClass:"he-dot"}),a("v-uni-view",{staticClass:"he-line"}),a("v-uni-view",{staticClass:"he-dot"})],1),a("v-uni-view",{staticClass:"le-right flex-sub"},[a("v-uni-view",{staticClass:"le-name"},[t._v(t._s(e.coupon.name))]),a("v-uni-view",{staticClass:"le-desc"},[t._v(t._s(1===e.coupon.appoint_type?"全部商品可用":"部分商品可用"))])],1)],1)})),1),a("v-uni-view",{staticClass:"le-footer"},[t._v("优惠券已发放,请在优惠券账户查看")])],1)],1)],1)],1)},o=[]},"0ff2":function(t,e,a){var i=a("a1a8");e=i(!1),e.push([t.i,".ad_element[data-v-6c97e4f4]{background:transparent!important}.ad[data-v-6c97e4f4]{position:fixed;left:0;top:0;z-index:100000;box-sizing:initial;width:100%;height:100vh}.ad .ad-pointer[data-v-6c97e4f4]{position:absolute;list-style:none;margin:0;padding:0;z-index:2;left:%?20?%;-webkit-transform:translateX(0);transform:translateX(0);bottom:%?20?%}.ad .ad-pointer .ad-pointer_number[data-v-6c97e4f4]{position:absolute;bottom:%?12?%;width:%?68?%;height:%?32?%;background:#000;border-radius:%?16?%;z-index:100;text-align:center;line-height:%?32?%;font-size:%?22?%;font-family:PingFang SC;font-weight:500;color:#d0b9bd;opacity:.5}.ad .ad-pointer .ad-pointer_item[data-v-6c97e4f4]{position:relative;list-style:none;margin:0;padding:0;z-index:2;display:inline-block;padding:%?12?% %?4?%;background-color:initial;cursor:pointer;text-align:-webkit-match-parent}.ad .ad-pointer .ad-pointer_item uni-button[data-v-6c97e4f4]{width:%?16?%;height:%?16?%;display:block;background-color:#fff;border:0;outline:0;padding:0;margin:0;cursor:pointer}.ad .circle.ad-pointer .ad-pointer_item uni-button[data-v-6c97e4f4]{width:%?16?%;height:%?16?%;border-radius:%?16?%}.ad .strip.ad-pointer .ad-pointer_item uni-button[data-v-6c97e4f4]{width:%?32?%;height:%?8?%;border-radius:0}.ad .ad-pointer.left[data-v-6c97e4f4]{left:%?20?%;-webkit-transform:translateX(0);transform:translateX(0)}.ad .ad-pointer.center[data-v-6c97e4f4]{left:50%;-webkit-transform:translateX(-50%);transform:translateX(-50%)}.ad .ad-pointer.center .ad-pointer_number[data-v-6c97e4f4]{margin-left:%?-32?%}.ad .ad-pointer.right[data-v-6c97e4f4]{left:auto;right:12%;-webkit-transform:translateX(0);transform:translateX(0)}.ad .is_skip[data-v-6c97e4f4]{width:%?120?%;height:%?68?%;font-size:%?12?%;font-family:Microsoft YaHei;font-weight:400;text-align:center;line-height:%?40?%;font-size:%?22?%;position:absolute;z-index:100;line-height:%?60?%;top:%?120?%;right:%?30?%}.ad .is_skip .is_skip_bg[data-v-6c97e4f4]{background:#000;opacity:.5;position:absolute;width:100%;height:100%;border-radius:%?34?%;z-index:100}.ad .is_skip .is_skip_txt[data-v-6c97e4f4]{font-size:%?30?%;font-family:PingFang SC;font-weight:500;color:#fff;line-height:%?68?%;position:absolute;z-index:200;width:100%;text-align:center}.ad .corner[data-v-6c97e4f4]{padding:%?32?%}.ad .corner .ad-item-cover[data-v-6c97e4f4]{background-color:#fff;box-sizing:initial;-webkit-appearance:none;-webkit-border-radius:%?16?%;-ms-border-radius:%?16?%;-o-border-radius:%?16?%;-moz-border-radius:%?16?%;border-radius:%?16?%;overflow:hidden}.ad .ad-item-image[data-v-6c97e4f4]{width:100%;height:100%}.ad .ad-item-photo[data-v-6c97e4f4]{position:relative;width:100%;height:100%;box-sizing:initial}",""]),t.exports=e},"166b":function(t,e,a){"use strict";var i=a("99ca").default;Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0,a("4cfc");var n=i(a("a5b4")),o={name:"he-index-cart",data:function(){return{isShopping:!1,goods:{}}},props:{goodsId:[Number],is_task:{type:Number,default:0}},components:{heCart:n.default},watch:{goodsId:{handler:function(t){t&&this.shopping(t)}},isShopping:function(t){t||this.$emit("update:goodsId",null)}},methods:{shopping:function(t){var e=this;this.$heshop.goods("get",t,{is_task:this.is_task}).then((function(t){t.hasOwnProperty("empty_status")||(e.goods=t,e.isShopping=!0)})).catch((function(t){e.$toError(t)}))}}};e.default=o},"17e4":function(t,e,a){var i=a("f545");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var n=a("5c0d").default;n("a776b068",i,!0,{sourceMap:!1,shadowMode:!1})},"1ab1":function(t,e,a){"use strict";a.r(e);var i=a("dfc4"),n=a.n(i);for(var o in i)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return i[t]}))}(o);e["default"]=n.a},"1b61":function(t,e,a){var i=a("a1a8");e=i(!1),e.push([t.i,'@charset "UTF-8";\n/* start--主题色--start */\n/* end--主题色--end */.uni-noticebar[data-v-123d0c79]{display:-webkit-box;display:-webkit-flex;display:flex;width:100%;box-sizing:border-box;-webkit-box-orient:horizontal;-webkit-box-direction:normal;-webkit-flex-direction:row;flex-direction:row;-webkit-box-align:center;-webkit-align-items:center;align-items:center;padding:%?12?% %?24?%}.uni-cursor-point[data-v-123d0c79]{cursor:pointer}.uni-noticebar-close[data-v-123d0c79]{margin-right:%?10?%}.uni-noticebar-icon[data-v-123d0c79]{margin-right:%?10?%}.uni-noticebar-icon uni-image[data-v-123d0c79]{margin-top:%?5?%;width:%?40?%;height:%?40?%}.uni-noticebar__content-wrapper[data-v-123d0c79]{-webkit-box-flex:1;-webkit-flex:1;flex:1;-webkit-box-orient:vertical;-webkit-box-direction:normal;-webkit-flex-direction:column;flex-direction:column;overflow:hidden}.uni-noticebar__content-wrapper--single[data-v-123d0c79]{line-height:%?40?%}.uni-noticebar__content-wrapper--single[data-v-123d0c79],\n.uni-noticebar__content-wrapper--scrollable[data-v-123d0c79]{-webkit-box-orient:horizontal;-webkit-box-direction:normal;-webkit-flex-direction:row;flex-direction:row}.uni-noticebar__content-wrapper--scrollable[data-v-123d0c79]{position:relative;height:%?40?%}.uni-noticebar__content--scrollable[data-v-123d0c79]{-webkit-box-flex:1;-webkit-flex:1;flex:1;display:block;overflow:hidden}.uni-noticebar__content--single[data-v-123d0c79]{display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-flex:0;-webkit-flex:none;flex:none;width:100%;-webkit-box-pack:center;-webkit-justify-content:center;justify-content:center}.uni-noticebar__content-text[data-v-123d0c79]{font-size:%?24?%;line-height:%?40?%;word-break:break-all}.uni-noticebar__content-text--single[data-v-123d0c79]{display:block;width:100%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.uni-noticebar__content-text--scrollable[data-v-123d0c79]{position:absolute;display:block;height:%?40?%;line-height:%?40?%;white-space:nowrap;padding-left:100%;-webkit-animation:notice-data-v-123d0c79 10s 0s linear infinite both;animation:notice-data-v-123d0c79 10s 0s linear infinite both;-webkit-animation-play-state:paused;animation-play-state:paused}.uni-noticebar__more[data-v-123d0c79]{display:-webkit-inline-box;display:-webkit-inline-flex;display:inline-flex;-webkit-box-orient:horizontal;-webkit-box-direction:normal;-webkit-flex-direction:row;flex-direction:row;-webkit-flex-wrap:nowrap;flex-wrap:nowrap;-webkit-box-align:center;-webkit-align-items:center;align-items:center;padding-left:%?10?%}.uni-noticebar__more-text[data-v-123d0c79]{font-size:%?24?%}@-webkit-keyframes notice-data-v-123d0c79{100%{-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0)}}@keyframes notice-data-v-123d0c79{100%{-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0)}}',""]),t.exports=e},"1d15":function(t,e,a){"use strict";a.r(e);var i=a("e44a"),n=a.n(i);for(var o in i)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return i[t]}))}(o);e["default"]=n.a},"1ff8":function(t,e,a){"use strict";a.r(e);var i=a("0234"),n=a.n(i);for(var o in i)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return i[t]}))}(o);e["default"]=n.a},2207:function(t,e,a){var i=a("ee94");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var n=a("5c0d").default;n("040306f7",i,!0,{sourceMap:!1,shadowMode:!1})},"23f8":function(t,e,a){"use strict";a.r(e);var i=a("0341"),n=a("c172");for(var o in n)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return n[t]}))}(o);var r,s=a("5d80"),c=Object(s["a"])(n["default"],i["b"],i["c"],!1,null,null,null,!1,i["a"],r);e["default"]=c.exports},2462:function(t,e,a){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i={props:{facade:{type:[Object,Array]},content:{type:[Object,Array]}}};e.default=i},2590:function(t,e,a){"use strict";var i=a("5191"),n=a.n(i);n.a},"26bf":function(t,e,a){var i=a("1b61");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var n=a("5c0d").default;n("7113424b",i,!0,{sourceMap:!1,shadowMode:!1})},"27e6":function(t,e,a){"use strict";var i;a.d(e,"b",(function(){return n})),a.d(e,"c",(function(){return o})),a.d(e,"a",(function(){return i}));var n=function(){var t=this,e=t.$createElement,a=t._self._c||e;return a("v-uni-view",{staticClass:"search",style:{"padding-top":t.facade.high_style/2+"px","padding-bottom":t.facade.high_style/2+"px","background-color":t.facade.background_color},attrs:{id:"search"},on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.navigateToDetail.apply(void 0,arguments)}}},[a("v-uni-view",{staticClass:"search-content",class:{angle:2==t.facade.border_style},style:{textAlign:t.facade.text_align,color:t.facade.text_color,"background-color":t.facade.border_color}},[a("v-uni-text",{staticClass:"iconfont iconsearchbar_search",style:{color:t.facade.icon_color}}),a("span",[t._v(t._s(t.content.text||"请输入关键字搜索"))])],1)],1)},o=[]},"29c6":function(t,e,a){"use strict";a.r(e);var i=a("df46"),n=a("2a86");for(var o in n)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return n[t]}))}(o);a("a4fa");var r,s=a("5d80"),c=Object(s["a"])(n["default"],i["b"],i["c"],!1,null,"4a3252cc",null,!1,i["a"],r);e["default"]=c.exports},"2a86":function(t,e,a){"use strict";a.r(e);var i=a("3d48"),n=a.n(i);for(var o in i)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return i[t]}))}(o);e["default"]=n.a},"2dab":function(t,e,a){"use strict";a.r(e);var i=a("32c0"),n=a("9570");for(var o in n)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return n[t]}))}(o);a("06c3");var r,s=a("5d80"),c=Object(s["a"])(n["default"],i["b"],i["c"],!1,null,"2e79a977",null,!1,i["a"],r);e["default"]=c.exports},"301f":function(t,e,a){"use strict";a.r(e);var i=a("ecb4"),n=a.n(i);for(var o in i)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return i[t]}))}(o);e["default"]=n.a},"305b":function(t,e,a){"use strict";a.r(e);var i=a("9a46"),n=a.n(i);for(var o in i)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return i[t]}))}(o);e["default"]=n.a},"30bc":function(t,e,a){"use strict";a.r(e);var i=a("3618"),n=a("99a5");for(var o in n)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return n[t]}))}(o);a("e6cd");var r,s=a("5d80"),c=Object(s["a"])(n["default"],i["b"],i["c"],!1,null,"0e77ce96",null,!1,i["a"],r);e["default"]=c.exports},"32c0":function(t,e,a){"use strict";var i;a.d(e,"b",(function(){return n})),a.d(e,"c",(function(){return o})),a.d(e,"a",(function(){return i}));var n=function(){var t=this,e=t.$createElement,a=t._self._c||e;return a("v-uni-view",{staticClass:"he-open-subscribe",on:{click:function(e){e.stopPropagation(),arguments[0]=e=t.$handleEvent(e),t.subscribe.apply(void 0,arguments)}}},[t._t("default"),t.isShow?[a("wx-open-subscribe",{staticStyle:{position:"absolute",width:"100%",height:"100%",top:"0",left:"0"},attrs:{template:t.templateId,id:t.subscribeId}},[a("script",{attrs:{type:"text/wxtag-template"}},[t._v('<style scoped>\n .btn {\n width: 100%;\n height: 500px;\n }\n </style>\n <div class="btn"></div>')])])]:t._e()],2)},o=[]},"34c7":function(t,e,a){var i=a("a1a8");e=i(!1),e.push([t.i,".video-container[data-v-6e7a2b50]{position:relative;width:100%;visibility:hidden}.video-container--visible[data-v-6e7a2b50]{visibility:visible}.video-container .video-container--box[data-v-6e7a2b50]{position:absolute;top:50%;left:50%;width:100%;height:100%;background:#000;-webkit-transform:translate(-50%,-50%);transform:translate(-50%,-50%)}",""]),t.exports=e},3618:function(t,e,a){"use strict";var i;a.d(e,"b",(function(){return n})),a.d(e,"c",(function(){return o})),a.d(e,"a",(function(){return i}));var n=function(){var t=this,e=t.$createElement,a=t._self._c||e;return a("v-uni-view",{staticClass:"rubik"},[t.size<7?a("v-uni-view",{staticClass:"advertising"},[1==t.size?[11===t.adverArray[0].link.index?[a("he-open-launch-weapp",{staticStyle:{height:"100%"},attrs:{username:t.adverArray[0].link.param.wechat.appId,path:t.adverArray[0].link.param.wechat.path}},[t.adverArray[0].url?a("v-uni-image",{staticClass:"advertising-item-1",staticStyle:{width:"100%"},attrs:{"lazy-load":!0,src:t.adverArray[0].url,mode:"widthFix"}}):t._e()],1)]:[t.adverArray[0].url?a("v-uni-image",{staticClass:"advertising-item-1",staticStyle:{width:"100%"},attrs:{"lazy-load":!0,src:t.adverArray[0].url,mode:"widthFix"},on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.navigateToDetail(t.adverArray[0].link)}}}):t._e()]]:t._e(),2==t.size?a("v-uni-view",{staticClass:"advertising-item-2"},[a("v-uni-view",{staticClass:"advertising-item-image",staticStyle:{width:"50%"}},[11===t.adverArray[0].link.index?[a("he-open-launch-weapp",{staticStyle:{height:"100%"},attrs:{username:t.adverArray[0].link.param.wechat.appId,path:t.adverArray[0].link.param.wechat.path}},[t.adverArray[0].url?a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{"lazy-load":!0,src:t.adverArray[0].url,mode:"widthFix"}}):t._e()],1)]:[t.adverArray[0].url?a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{"lazy-load":!0,src:t.adverArray[0].url,mode:"widthFix"},on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.navigateToDetail(t.adverArray[0].link)}}}):t._e()]],2),a("v-uni-view",{staticClass:"advertising-item-image",staticStyle:{width:"50%"}},[11===t.adverArray[1].link.index?[a("he-open-launch-weapp",{staticStyle:{height:"100%"},attrs:{username:t.adverArray[1].link.param.wechat.appId,path:t.adverArray[1].link.param.wechat.path}},[t.adverArray[0].url?a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{"lazy-load":!0,src:t.adverArray[1].url,mode:"widthFix"}}):t._e()],1)]:[t.adverArray[0].url?a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{"lazy-load":!0,src:t.adverArray[1].url,mode:"widthFix"},on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.navigateToDetail(t.adverArray[1].link)}}}):t._e()]],2)],1):t._e(),3==t.size?a("v-uni-view",{staticClass:"advertising-item-3"},[a("v-uni-view",{staticClass:"advertising-item-image",staticStyle:{width:"33.333%"}},[11===t.adverArray[0].link.index?[a("he-open-launch-weapp",{staticStyle:{height:"100%"},attrs:{username:t.adverArray[0].link.param.wechat.appId,path:t.adverArray[0].link.param.wechat.path}},[t.adverArray[0].url?a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{"lazy-load":!0,src:t.adverArray[0].url,mode:"widthFix"}}):t._e()],1)]:[t.adverArray[0].url?a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{"lazy-load":!0,src:t.adverArray[0].url,mode:"widthFix"},on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.navigateToDetail(t.adverArray[0].link)}}}):t._e()]],2),a("v-uni-view",{staticClass:"advertising-item-image",staticStyle:{width:"33.333%"}},[11===t.adverArray[1].link.index?[a("he-open-launch-weapp",{staticStyle:{height:"100%"},attrs:{username:t.adverArray[1].link.param.wechat.appId,path:t.adverArray[1].link.param.wechat.path}},[t.adverArray[1].url?a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{"lazy-load":!0,src:t.adverArray[1].url,mode:"widthFix"}}):t._e()],1)]:[t.adverArray[1].url?a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{"lazy-load":!0,src:t.adverArray[1].url,mode:"widthFix"},on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.navigateToDetail(t.adverArray[1].link)}}}):t._e()]],2),a("v-uni-view",{staticClass:"advertising-item-image",staticStyle:{width:"33.333%"}},[11===t.adverArray[2].link.index?[a("he-open-launch-weapp",{staticStyle:{height:"100%"},attrs:{username:t.adverArray[2].link.param.wechat.appId,path:t.adverArray[2].link.param.wechat.path}},[t.adverArray[2].url?a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{"lazy-load":!0,src:t.adverArray[2].url,mode:"widthFix"}}):t._e()],1)]:[t.adverArray[2].url?a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{"lazy-load":!0,src:t.adverArray[2].url,mode:"widthFix"},on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.navigateToDetail(t.adverArray[2].link)}}}):t._e()]],2)],1):t._e(),4==t.size?a("v-uni-view",{staticClass:"advertising-item-4"},[a("v-uni-view",{staticClass:"advertising-item-image",style:{width:"50%",height:"375rpx",top:0,left:0}},[11===t.adverArray[0].link.index?[a("he-open-launch-weapp",{staticStyle:{height:"100%"},attrs:{username:t.adverArray[0].link.param.wechat.appId,path:t.adverArray[0].link.param.wechat.path}},[t.adverArray[0].url?a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{"lazy-load":!0,src:t.adverArray[0].url,mode:"aspectFill"}}):t._e()],1)]:[t.adverArray[0].url?a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{"lazy-load":!0,src:t.adverArray[0].url,mode:"aspectFill"},on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.navigateToDetail(t.adverArray[0].link)}}}):t._e()]],2),a("v-uni-view",{staticClass:"advertising-item-image",style:{width:"50%",height:"188rpx",top:0,left:"375rpx"}},[11===t.adverArray[1].link.index?[a("he-open-launch-weapp",{staticStyle:{height:"100%"},attrs:{username:t.adverArray[1].link.param.wechat.appId,path:t.adverArray[1].link.param.wechat.path}},[t.adverArray[1].url?a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{"lazy-load":!0,src:t.adverArray[1].url,mode:"aspectFill"}}):t._e()],1)]:[t.adverArray[1].url?a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{"lazy-load":!0,src:t.adverArray[1].url,mode:"aspectFill"},on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.navigateToDetail(t.adverArray[1].link)}}}):t._e()]],2),a("v-uni-view",{staticClass:"advertising-item-image",style:{width:"50%",height:"188rpx",top:"188rpx",left:"375rpx"}},[11===t.adverArray[2].link.index?[a("he-open-launch-weapp",{staticStyle:{height:"100%"},attrs:{username:t.adverArray[2].link.param.wechat.appId,path:t.adverArray[2].link.param.wechat.path}},[t.adverArray[2].url?a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{"lazy-load":!0,src:t.adverArray[2].url,mode:"aspectFill"}}):t._e()],1)]:[t.adverArray[2].url?a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{"lazy-load":!0,src:t.adverArray[2].url,mode:"aspectFill"},on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.navigateToDetail(t.adverArray[2].link)}}}):t._e()]],2)],1):t._e(),5==t.size?a("v-uni-view",{staticClass:"advertising-item-5"},[a("v-uni-view",{staticClass:"advertising-item-image",staticStyle:{width:"25%"}},[11===t.adverArray[0].link.index?[a("he-open-launch-weapp",{staticStyle:{height:"100%"},attrs:{username:t.adverArray[0].link.param.wechat.appId,path:t.adverArray[0].link.param.wechat.path}},[t.adverArray[0].url?a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{src:t.adverArray[0].url,mode:"widthFix"}}):t._e()],1)]:[t.adverArray[0].url?a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{src:t.adverArray[0].url,mode:"widthFix"},on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.navigateToDetail(t.adverArray[0].link)}}}):t._e()]],2),a("v-uni-view",{staticClass:"advertising-item-image",staticStyle:{width:"25%"}},[11===t.adverArray[1].link.index?[a("he-open-launch-weapp",{staticStyle:{height:"100%"},attrs:{username:t.adverArray[1].link.param.wechat.appId,path:t.adverArray[1].link.param.wechat.path}},[t.adverArray[1].url?a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{src:t.adverArray[1].url,mode:"widthFix"}}):t._e()],1)]:[t.adverArray[1].url?a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{src:t.adverArray[1].url,mode:"widthFix"},on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.navigateToDetail(t.adverArray[1].link)}}}):t._e()]],2),a("v-uni-view",{staticClass:"advertising-item-image",staticStyle:{width:"25%"}},[11===t.adverArray[2].link.index?[a("he-open-launch-weapp",{staticStyle:{height:"100%"},attrs:{username:t.adverArray[2].link.param.wechat.appId,path:t.adverArray[2].link.param.wechat.path}},[t.adverArray[2].url?a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{src:t.adverArray[2].url,mode:"widthFix"}}):t._e()],1)]:[t.adverArray[2].url?a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{src:t.adverArray[2].url,mode:"widthFix"},on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.navigateToDetail(t.adverArray[2].link)}}}):t._e()]],2),a("v-uni-view",{staticClass:"advertising-item-image",staticStyle:{width:"25%"}},[11===t.adverArray[3].link.index?[a("he-open-launch-weapp",{staticStyle:{height:"100%"},attrs:{username:t.adverArray[3].link.param.wechat.appId,path:t.adverArray[3].link.param.wechat.path}},[t.adverArray[3].url?a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{src:t.adverArray[3].url,mode:"widthFix"}}):t._e()],1)]:[t.adverArray[3].url?a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{src:t.adverArray[3].url,mode:"widthFix"},on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.navigateToDetail(t.adverArray[3].link)}}}):t._e()]],2)],1):t._e(),6==t.size?a("v-uni-view",{staticClass:"advertising-item-6"},[a("v-uni-view",{staticClass:"advertising-item-image",style:{width:"50%",height:"188rpx",top:0,left:0}},[11===t.adverArray[0].link.index?[a("he-open-launch-weapp",{staticStyle:{height:"100%"},attrs:{username:t.adverArray[0].link.param.wechat.appId,path:t.adverArray[0].link.param.wechat.path}},[t.adverArray[0].url?a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{"lazy-load":!0,src:t.adverArray[0].url,mode:"aspectFill"}}):t._e()],1)]:[t.adverArray[0].url?a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{"lazy-load":!0,src:t.adverArray[0].url,mode:"aspectFill"},on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.navigateToDetail(t.adverArray[0].link)}}}):t._e()]],2),a("v-uni-view",{staticClass:"advertising-item-image",style:{width:"50%",height:"188rpx",top:"188rpx",left:0}},[11===t.adverArray[1].link.index?[a("he-open-launch-weapp",{staticStyle:{height:"100%"},attrs:{username:t.adverArray[1].link.param.wechat.appId,path:t.adverArray[1].link.param.wechat.path}},[t.adverArray[1].url?a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{"lazy-load":!0,src:t.adverArray[1].url,mode:"aspectFill"}}):t._e()],1)]:[t.adverArray[1].url?a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{"lazy-load":!0,src:t.adverArray[1].url,mode:"aspectFill"},on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.navigateToDetail(t.adverArray[1].link)}}}):t._e()]],2),a("v-uni-view",{staticClass:"advertising-item-image",style:{width:"50%",height:"188rpx",top:0,left:"50%"}},[11===t.adverArray[2].link.index?[a("he-open-launch-weapp",{staticStyle:{height:"100%"},attrs:{username:t.adverArray[2].link.param.wechat.appId,path:t.adverArray[2].link.param.wechat.path}},[t.adverArray[2].url?a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{"lazy-load":!0,src:t.adverArray[2].url,mode:"aspectFill"}}):t._e()],1)]:[t.adverArray[2].url?a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{"lazy-load":!0,src:t.adverArray[2].url,mode:"aspectFill"},on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.navigateToDetail(t.adverArray[2].link)}}}):t._e()]],2),a("v-uni-view",{staticClass:"advertising-item-image",style:{width:"50%",height:"188rpx",top:"188rpx",left:"50%"}},[11===t.adverArray[3].link.index?[a("he-open-launch-weapp",{staticStyle:{height:"100%"},attrs:{username:t.adverArray[3].link.param.wechat.appId,path:t.adverArray[3].link.param.wechat.path}},[t.adverArray[3].url?a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{"lazy-load":!0,src:t.adverArray[3].url,mode:"aspectFill"}}):t._e()],1)]:[t.adverArray[3].url?a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{"lazy-load":!0,src:t.adverArray[3].url,mode:"aspectFill"},on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.navigateToDetail(t.adverArray[3].link)}}}):t._e()]],2)],1):t._e()],2):t._e(),7==t.size?a("v-uni-view",{staticClass:"rubik-cube"},[t._l(t.adverArray,(function(e,i){return[a("v-uni-view",{key:i,staticClass:"rubik-cube__item",style:{width:t.getWidth(e)+"px",height:t.getHeight(e)+"px",top:t.getTop(e)+"px",left:t.getLeft(e)+"px"}},[11===e.link.index?[a("he-open-launch-weapp",{staticStyle:{height:"100%"},attrs:{username:e.link.param.wechat.appId,path:e.link.param.wechat.path}},[e.url?a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{"lazy-load":!0,src:e.url,mode:"aspectFill"}}):t._e()],1)]:[e.url?a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{"lazy-load":!0,src:e.url,mode:"aspectFill"},on:{click:function(a){arguments[0]=a=t.$handleEvent(a),t.navigateToDetail(e.link)}}}):t._e()]],2)]}))],2):t._e()],1)},o=[]},"3a20":function(t,e,a){"use strict";a.r(e);var i=a("6686"),n=a("a35f");for(var o in n)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return n[t]}))}(o);a("2590");var r,s=a("5d80"),c=Object(s["a"])(n["default"],i["b"],i["c"],!1,null,"6c97e4f4",null,!1,i["a"],r);e["default"]=c.exports},"3c2b":function(t,e,a){"use strict";a.r(e);var i=a("911a"),n=a("6741");for(var o in n)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return n[t]}))}(o);a("f228");var r,s=a("5d80"),c=Object(s["a"])(n["default"],i["b"],i["c"],!1,null,"eb7cd128",null,!1,i["a"],r);e["default"]=c.exports},"3d48":function(t,e,a){"use strict";var i=a("99ca").default;Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var n=i(a("06c4"));a("ba85"),a("bfcb"),a("54db");var o={props:{facade:{type:[Object,Array]},content:{type:[Object,Array]}},data:function(){return{url:this.ipAddress+"/le-default-goods-bg.png"}},computed:{window:function(){return uni.getSystemInfoSync()},width:function(){var t=uni.getSystemInfoSync(),e=0;switch(parseInt(this.content.style)){case 2:case 4:case 6:e=t.windowWidth/2;break;case 3:e=t.windowWidth/3;break;case 5:e=t.windowWidth/4;break;default:e=t.windowWidth;break}return e},height:function(){var t=uni.getSystemInfoSync();switch(this.content.style){case 2:case 6:return t.windowWidth/2;case 3:case 5:return t.windowWidth/3;default:return t.windowWidth}},picture:function(){var t="style"+this.content.style;return this[t].call(this)}},methods:{navigateToDetail:function(t){t.extend?(2==t.index&&uni.navigateTo({url:t.path+"?id="+t.param.id}),7==t.index&&uni.navigateTo({url:t.path+"?id="+t.param.id}),3==t.index&&uni.switchTab({url:t.path+"?id="+t.param.id})):-1==[3,4,5].indexOf(t.index)?uni.navigateTo({url:t.path}):uni.switchTab({url:t.path})},style1:function(){for(var t=[],e=0,a=0,i=0;i<1;i++){var o=this.content.data[i];t[i]=(0,n.default)((0,n.default)({},o),{},{left:e,top:a,width:this.width,height:this.height}),e+=parseFloat(this.width)}return t},style2:function(){for(var t=[],e=0,a=0,i=0;i<2;i++){var o=this.content.data[i];t[i]=(0,n.default)((0,n.default)({},o),{},{left:e,top:a,width:this.width,height:this.height}),e+=parseFloat(this.width)}return t},style3:function(){for(var t=[],e=0,a=0,i=0;i<3;i++){var o=this.content.data[i];t[i]=(0,n.default)((0,n.default)({},o),{},{left:e,top:a,width:this.width,height:this.height}),e+=parseFloat(this.width)}return t},style4:function(){for(var t=[],e=0,a=0,i=0;i<3;i++){var o=this.content.data[i];if(t[i]=(0,n.default)((0,n.default)({},o),{},{left:e,top:a,width:this.width,height:0===i?this.height:this.height/2}),0===i&&(e+=parseFloat(this.width)),1==i){var r=this.height/2;a+=parseFloat(r)}}return t},style5:function(){for(var t=[],e=0,a=0,i=0;i<4;i++){var o=this.content.data[i];t[i]=(0,n.default)((0,n.default)({},o),{},{left:e,top:a,width:this.width,height:this.height}),e+=parseFloat(this.width)}return t},style6:function(){for(var t=[],e=0,a=0,i=0;i<4;i++){var o=this.content.data[i];t[i]=(0,n.default)((0,n.default)({},o),{},{left:e,top:a,width:this.width,height:this.height/2}),0!==i&&2!=i||(e+=parseFloat(this.width)),1===i&&(a+=parseFloat(this.height/2),e=0)}return t}}};e.default=o},"3ec4":function(t,e,a){var i=a("45c9");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var n=a("5c0d").default;n("27b1d4b0",i,!0,{sourceMap:!1,shadowMode:!1})},"3f31":function(t,e,a){"use strict";var i=a("99ca").default;Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var n=i(a("06c4")),o=i(a("c2c4")),r=a("7736"),s=i(a("eca4")),c={name:"he-login-model",components:{hePopup:o.default,userNewuserCoupon:s.default},data:function(){return{isNewuser:!1}},computed:{showModal:{get:function(t){var e=t.$store;return e.state.apply.showLoginModel},set:function(t){this.$store.commit("apply/setLoginModel",t)}},userInfo:function(){return this.$store.state.apply.userInfo}},methods:(0,n.default)((0,n.default)({},(0,r.mapActions)({decryptUserInfo:"user/decryptUserInfo",getUserProfile:"user/getUserProfile"})),{},{notLogIn:function(){this.$store.commit("apply/setLoginModel",!1)},login:function(){var t=this;this.canIUseGetUserProfile?this.getUserProfile().then((function(){var e;t.$h.test.isEmpty(null===(e=t.userInfo)||void 0===e?void 0:e.register.coupon_list)||(t.isNewuser=!0),setTimeout((function(){var e=t.$store.getters["setting/getCartIndex"];t.$store.dispatch("cart/getCartNumber").then((function(t){0!==t?uni.setTabBarBadge({index:e,text:t+""}):uni.removeTabBarBadge({index:e})}))}),1e3),t.$store.commit("apply/setLoginModel",!1),"pages/user/index"!==t.$parent.__route__&&"pages/cart/index"!==t.$parent.__route__||t.$parent.getShowData();var a=uni.getStorageSync("promoterUid");a&&t.$store.dispatch("plugins/bindPromoterSuperior",{parent_id:a}).then((function(){uni.removeStorageSync("promoterUid")}))})):this.decryptUserInfo().then((function(){t.$h.test.isEmpty(t.userInfo.register.coupon_list)||(t.isNewuser=!0),setTimeout((function(){var e=t.$store.getters["setting/getCartIndex"];t.$store.dispatch("cart/getCartNumber").then((function(t){0!==t?uni.setTabBarBadge({index:e,text:t+""}):uni.removeTabBarBadge({index:e})}))}),1e3),t.$store.commit("apply/setLoginModel",!1),"pages/user/index"!==t.$parent.__route__&&"pages/cart/index"!==t.$parent.__route__||t.$parent.getShowData();var e=uni.getStorageSync("promoterUid");e&&t.$store.dispatch("plugins/bindPromoterSuperior",{parent_id:e}).then((function(){uni.removeStorageSync("promoterUid")}))}))}})};e.default=c},"3f77":function(t,e,a){"use strict";var i=a("99ca").default;Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var n=i(a("06c4"));a("c342"),a("ae75"),a("211d"),a("5950"),a("ba85");var o=i(a("4b77")),r=i(a("4bc6")),s=i(a("5830")),c=i(a("9990")),d=i(a("23f8")),l=i(a("ae01")),u=i(a("ed5e")),f=i(a("857d")),h=i(a("d545")),p=i(a("30bc")),v=i(a("05a7")),g=i(a("29c6")),m=i(a("b43a")),b=i(a("564e5")),w=i(a("d2d6")),y=i(a("eca4")),k=a("7736"),x=i(a("3a20")),_=i(a("9112")),C=i(a("f818")),S=i(a("8bb2")),z=i(a("fe9c")),A=i(a("3c2b")),$=i(a("9bf6")),O={},T={components:{videos:s.default,separate:c.default,blank:d.default,banner:l.default,search:u.default,goods:f.default,navigation:r.default,tabs:h.default,titles:o.default,rubik:p.default,notice:v.default,advertising:g.default,coupon:m.default,task:b.default,heNavbar:w.default,userNewuserCoupon:y.default,openidad:x.default,taskpopups:C.default,cartoon:_.default,HeLoginModel:S.default,heFloatWindow:z.default,heBecomeDistributor:A.default,float:$.default},data:function(){return{is_cartoon:1,popupsList:[],is_skip:!1,background:"#F7F7F7",page:[],empty:{name:"blank",icon:this.ipAddress+"/pageicon/blank-icon.png",title:"辅助空白",content:{},facade:{height:10,background_color:"#FFFFFF"}},menuButtonInfo:O,isNewuser:!1,wechatUrl:"/",isShareCount:null}},beforeCreate:function(){var t=this;this.is_skip=!0;var e=window.location.search.substring(1).split("_skip=")[1];if(e){var a=this.$h.getQueryVariable("code");a&&(this.$store.state.apply.is_login?this.is_skip=!1:(this.wechatUrl=e,this.$store.dispatch("user/weChatLogin",{code:a}).then((function(){t.is_skip=!1,t.$h.test.isEmpty(t.userInfo.register.coupon_list)?uni.redirectTo({url:e,fail:function(){uni.switchTab({url:e})}}):t.isNewuser=!0})).catch((function(){t.is_skip=!1}))))}else this.is_skip=!1},computed:(0,n.default)((0,n.default)({},(0,k.mapGetters)({searchTop:"components/getSearchTop",fixed:"components/getSearchFixed",searchHeight:"components/getSearchHeight",navbarHeight:"setting/getNavBarHeight",statusBarHeight:"setting/statusBarHeight",getPromoter:"setting/getPromoter"})),{},{is_ad:function(){return uni.getStorageSync("openingad")||!1},topHeight:function(){return{height:"".concat(this.statusBarHeight+this.navbarHeight,"px"),lineHeight:"".concat(this.statusBarHeight+this.navbarHeight,"px")}},userInfo:function(){return this.$store.state.apply.userInfo},shareData:function(){var t,e,a,i,n,o;return{title:null!==(t=this.shareSetting)&&void 0!==t&&t.describe?null===(e=this.shareSetting)||void 0===e?void 0:e.describe:"欢迎光临".concat(null===(a=this.storeSetting)||void 0===a?void 0:a.name," 挑选好物"),path:"/pages/index/index",imageUrl:null!==(i=this.shareSetting)&&void 0!==i&&i.cover_img?null===(n=this.shareSetting)||void 0===n?void 0:n.cover_img:null===(o=this.storeSetting)||void 0===o?void 0:o.logo}}}),onShow:function(){var t=this;this.$nextTick().then((function(){var e=uni.getStorageSync("openingad");e?(uni.showTabBar(),t.handlePageLoading()):(uni.hideTabBar(),setTimeout((function(){t.handlePageLoading()}),1e3))})),this.isLogin&&this.setCartNumber()},methods:(0,n.default)((0,n.default)({handler:function(){}},(0,k.mapActions)({setCartNumber:"cart/setCartNumber"})),{},{handleConfirm:function(t){uni.showTabBar(),this.handlePageLoading()},handleTaskShare:function(){var t=this,e=uni.getStorageSync("handleTaskShare");if(e)return this.binding={},!0;this.$heshop.plugin("get",{include:"task",model:"score",type:"single",keyword:"share",status:0}).then((function(e){e&&0===e.status&&t.$nextTick((function(){t.popupsList.push({display:!0,remark:e.remark}),clearInterval(t.isShareCount),uni.setStorageSync("handleTaskShare",1)}))}))},handlePageLoading:function(){try{var t=this.getStorageSync("micropage");if(t){uni.setNavigationBarTitle({title:t.name}),this.background=t.background,this.page=JSON.parse(t.content);var e=this.page.findIndex((function(t){return"search"===t.name}));this.$store.commit("components/setSearchIndex",e),this.$store.commit("components/setPage",this.page),this.handleLoadData(t)}else this.handleLoadData()}catch(a){this.handleLoadData()}},handleLoadData:function(t){var e=this;this.$heshop.pages("GET").then((function(a){if(e.background=a.background,!t||e.$heshop.MD5(t)!=e.$heshop.MD5(a)){e.page=JSON.parse(a.content);var i=e.page.findIndex((function(t){return"search"===t.name}));e.$store.commit("components/setSearchIndex",i),e.$store.commit("components/setPage",e.page),uni.setStorageSync("micropage",a),uni.setNavigationBarTitle({title:a.name})}})).catch((function(t){e.$toError(t)}))},navigateToDetail:function(){uni.navigateTo({url:"/pages/goods/search"})}}),onLoad:function(){this.$wechat.updateShareData(this.$shareAppMessage())},beforeDestroy:function(){this.$wechat.showMenuItems({menuList:menuList}),this.$wechat.updateShareData(this.$shareAppMessage())},onPageScroll:function(t){var e=this,a=parseInt(t.scrollTop),i=a>=e.searchTop+this.navbarHeight;if(e.searchFixed===i)return!1;this.$store.commit("components/setSearchFixed",i)}};e.default=T},"3f8d":function(t,e,a){"use strict";var i=a("99ca").default;Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0,a("f9ee");var n=i(a("11226")),o={components:{heOpenLaunchWeapp:n.default},props:{facade:{type:[Object,Array]},content:{type:[Object,Array]}},computed:{adverArray:function(){return this.content.data},size:function(){return this.content.style},windowWidth:function(){var t=uni.getSystemInfoSync();return t.windowWidth}},methods:{navigateToDetail:function(t){this.$h.MPageNavigate(t)},getHeight:function(t){var e=this.windowWidth/this.content.density;return(t.rowEnd-t.rowStart+1)*e},getWidth:function(t){var e=this.windowWidth/this.content.density;return(t.columnEnd-t.columnStart+1)*e},getLeft:function(t){var e=this.windowWidth/this.content.density;return(t.columnStart-1)*e},getTop:function(t){var e=this.windowWidth/this.content.density;return(t.rowStart-1)*e},getCover:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",e="";return t&&"[object Array]"===Object.prototype.toString.call(t)&&t[0]?t[0].url:e}}};e.default=o},"401a":function(t,e,a){"use strict";var i=a("99ca").default;Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0,a("7423");var n=i(a("2dab")),o=i(a("a0ae")),r={components:{heOpenSubscribe:n.default,item:o.default},computed:{couponBox:function(){return 1===this.facade.list_style?"":2===this.facade.list_style?"flex flex-wrap":3===this.facade.list_style?"flex":void 0},subTemplateId:function(){return[this.$store.getters["setting/subscribe"].coupon_expire]},couponItem:function(){var t="";return 3===this.content.style&&(t+=" fillet "),1===this.facade.list_style?t+="":2===this.facade.list_style?t+="le-item-marginRight-odd ":3===this.facade.list_style&&(t+="le-item-marginRight "),t},itemStyle:function(){var t=this;return function(){var e={};return 1===t.facade.list_style?(e.width="710rpx",e.marginBottom="10rpx"):2===t.facade.list_style?(e.width="349rpx",e.marginBottom="10rpx"):3===t.facade.list_style&&(e.width="280rpx"),e}}},props:{facade:{type:[Object,Array]},content:{type:[Object,Array]}},data:function(){return{list:[]}},methods:{getList:function(){var t=this,e=this.content,a=e.data,i=e.autoplay,n=e.number;if(0===i){if(0!==a.length){var o=[];o=a.map((function(t){return t.id})),this.$heshop.coupon("get",{behavior:"coupon",coupon_id:o}).then((function(e){t.list=e.data})).catch((function(e){t.$toError(e)}))}}else 1===i&&this.$heshop.coupon("get",{behavior:"coupon"}).page(1,n).then((function(e){t.list=e.data})).catch((function(e){t.$toError(e)}))},receive:function(t){var e=this;t.can_obtain&&(this.isLogin?e.$heshop.coupon("post",{id:t.id}).then((function(){t.can_obtain=!1})).catch((function(t){e.$toError(t)})):this.$store.commit("apply/setLoginModel",!0))}},watch:{"content.data":{handler:function(){this.getList()},deep:!0,immediate:!0}}};e.default=r},"415b":function(t,e,a){"use strict";var i=a("d0b7"),n=a.n(i);n.a},"41a8":function(t,e,a){"use strict";var i=a("99ca").default;Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0,a("f9ee");var n=i(a("639e")),o=i(a("11226")),r={components:{pointer:n.default,heOpenLaunchWeapp:o.default},props:{facade:{type:[Object,Array]},content:{type:[Object,Array]}},data:function(){return{current:0,autoplay:!0,circular:!0}},computed:{height:function(){var t=uni.getSystemInfoSync(),e=.4;return t.windowWidth*e+"px"},contentData:function(){var t=[];for(var e in this.content){var a=this.content[e];a.url&&t.push(a)}return t},margin:function(){return 1==this.facade.chamfer_style?10:20}},methods:{navigateToDetail:function(t){this.$h.MPageNavigate(t)},handleChange:function(t){this.current=t.detail.current},getCover:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",e="";return t&&"[object Array]"===Object.prototype.toString.call(t)&&t[0]?t[0].url:e}}};e.default=r},"42cb":function(t,e,a){"use strict";var i;a.d(e,"b",(function(){return n})),a.d(e,"c",(function(){return o})),a.d(e,"a",(function(){return i}));var n=function(){var t=this,e=t.$createElement,a=t._self._c||e;return a("v-uni-view",{staticClass:"tabs"},[a("v-uni-scroll-view",{staticClass:"tabs-header",style:{top:t.top+"px",background:t.facade.background_color?t.facade.background_color:"#fff"},attrs:{"scroll-left":t.scrollWdith,"scroll-with-animation":!0,"scroll-x":"true"}},[a("v-uni-view",{staticClass:"he-scroll-box flex"},t._l(t.content.data,(function(e,i){return a("v-uni-view",{key:i,staticClass:"he-tab-item",class:[{active:i===t.select},"he-tab-item_"+i],attrs:{id:"he-tab-item_"+i},on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.radioChange(i)}}},[t._v(t._s(e.title)),t.select===i?a("v-uni-view",{staticClass:"he-tab-line"}):t._e()],1)})),1)],1),a("v-uni-view",{staticClass:"tabs-content",class:{"tabs-content-active":t.active}},[t._l(t.content.data,(function(e,i){return[a("v-uni-view",{directives:[{name:"show",rawName:"v-show",value:t.select===i,expression:"select === index"}],key:i,staticClass:"tabs-content-item"},[a("Goods",{attrs:{facade:t.facade,content:t.getContent(e)}})],1)]}))],2)],1)},o=[]},"42f0":function(t,e,a){"use strict";var i;a.d(e,"b",(function(){return n})),a.d(e,"c",(function(){return o})),a.d(e,"a",(function(){return i}));var n=function(){var t=this,e=t.$createElement,a=t._self._c||e;return t.is_skip?t._e():a("v-uni-view",{staticClass:"pages fitment-pages",style:{background:t.background}},[a("openidad",{on:{confirm:function(e){arguments[0]=e=t.$handleEvent(e),t.handleConfirm.apply(void 0,arguments)}}}),t.fixed?a("he-navbar",{attrs:{"is-back":!1,"title-bold":!0,"title-size":"32",background:{background:"#fff"}}},[a("v-uni-view",{staticClass:"he-search flex align-center",on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.navigateToDetail.apply(void 0,arguments)}}},[a("v-uni-text",{staticClass:"iconfont iconsearchbar_search"}),a("v-uni-text",{staticClass:"he-search-text"},[t._v("请输入关键字搜索")])],1)],1):t._e(),t._l(t.page,(function(e,i){return a("v-uni-view",{key:i},["notice"===e.name?a("v-uni-view",{attrs:{id:e.name+"_"+i}},[a("notice",{tag:"component",attrs:{facade:e.facade,content:e.content,"data-index":i}})],1):"rubik"===e.name?a("v-uni-view",{attrs:{id:e.name+"_"+i}},[a("rubik",{tag:"component",attrs:{facade:e.facade,content:e.content,"data-index":i}})],1):"title"===e.name?a("v-uni-view",{attrs:{id:e.name+"_"+i}},[a("titles",{tag:"component",attrs:{facade:e.facade,content:e.content,"data-index":i}})],1):"navigation"===e.name?a("v-uni-view",{attrs:{id:e.name+"_"+i}},[a("navigation",{tag:"component",attrs:{facade:e.facade,content:e.content,"data-index":i}})],1):"video"===e.name?a("v-uni-view",{attrs:{id:e.name+"_"+i}},[a("videos",{tag:"component",attrs:{facade:e.facade,content:e.content,"data-index":i}})],1):"separate"===e.name?a("v-uni-view",{attrs:{id:e.name+"_"+i}},[a("separate",{tag:"component",attrs:{facade:e.facade,content:e.content,"data-index":i}})],1):"banner"===e.name?a("v-uni-view",{attrs:{id:e.name+"_"+i}},[a("banner",{tag:"component",attrs:{facade:e.facade,content:e.content,"data-index":i}})],1):"search"===e.name?a("v-uni-view",{attrs:{id:"search"}},[a("search",{tag:"component",attrs:{facade:e.facade,content:e.content,"data-index":i}})],1):"goods"===e.name?a("v-uni-view",{attrs:{id:e.name+"_"+i}},[a("goods",{tag:"component",attrs:{facade:e.facade,content:e.content,"data-index":i}})],1):"blank"===e.name?a("v-uni-view",{attrs:{id:e.name+"_"+i}},[a("blank",{tag:"component",attrs:{facade:e.facade,content:e.content,"data-index":i}})],1):"tabs"===e.name?a("v-uni-view",{attrs:{id:e.name+"_"+i}},[a("tabs",{tag:"component",attrs:{background:t.background,"page-index":i,facade:e.facade,content:e.content,"data-index":i}})],1):"coupon"===e.name?a("v-uni-view",{attrs:{id:e.name+"_"+i}},[a("coupon",{tag:"component",attrs:{background:t.background,"page-index":i,facade:e.facade,content:e.content,"data-index":i}})],1):"task"===e.name?a("v-uni-view",{attrs:{id:e.name+"_"+i}},[a("task",{tag:"component",attrs:{background:t.background,"page-index":i,facade:e.facade,content:e.content,"data-index":i}})],1):t._e()],1)})),a("user-newuser-coupon",{attrs:{coupon:t.userInfo.register&&t.userInfo.register.coupon_list,wechatUrl:t.wechatUrl},model:{value:t.isNewuser,callback:function(e){t.isNewuser=e},expression:"isNewuser"}}),t._l(t.popupsList,(function(e,i){return a("taskpopups",{key:i,attrs:{title:e.remark,index:i},model:{value:e.display,callback:function(a){t.$set(e,"display",a)},expression:"item.display"}})})),a("HeLoginModel"),a("he-float-window",{attrs:{bottom:100,"pages-url":"index"}}),1!==t.getPromoter.status||t.getPromoter.need_check||t.getPromoter.need_apply||1!==t.getPromoter.conditions.type||!t.isLogin?t._e():a("he-become-distributor")],2)},o=[]},"43ae":function(t,e,a){"use strict";var i=a("67a8"),n=a.n(i);n.a},4411:function(t,e,a){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i={name:"float",data:function(){return{x:150,y:150,old:{x:150,y:150},isShow:!1,list:[]}},methods:{onChange:function(t){this.old.x=t.detail.x,this.old.y=t.detail.y},onClick:function(){this.isShow=!0},touchend:function(){var t=this;this.x=this.old.x,this.y=this.old.y;var e=wx.getSystemInfoSync().windowWidth;this.$nextTick((function(){t.x<e/2?t.x=uni.upx2px(24):t.x>e/2&&(t.x=e-uni.upx2px(88)-uni.upx2px(24))}))}}};e.default=i},"448f":function(t,e,a){"use strict";var i=a("85da"),n=a.n(i);n.a},"449c":function(t,e,a){"use strict";a.r(e);var i=a("9d37"),n=a.n(i);for(var o in i)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return i[t]}))}(o);e["default"]=n.a},"45c9":function(t,e,a){var i=a("a1a8");e=i(!1),e.push([t.i,".navigation[data-v-1fa750b1]{background-color:#fff;position:relative}.navigation[data-v-1fa750b1] ::-webkit-scrollbar{display:none}.navigation .one[data-v-1fa750b1]{white-space:nowrap;overflow-x:auto;overflow-y:hidden;padding:0 %?32?%}.navigation .navigation-indicator[data-v-1fa750b1]{position:absolute;width:100%;height:%?20?%;bottom:%?10?%}.navigation .navigation-image-item[data-v-1fa750b1]{display:inline-block;vertical-align:middle;margin-top:%?16?%;margin-bottom:%?10?%}.navigation .navigation-image-item .navigation-image-item__cover[data-v-1fa750b1]{width:%?100?%;height:%?100?%;background-position:50%;background-size:cover;display:block;margin:0 auto;border:0}.navigation .navigation-image-item .navigation-image-item__title[data-v-1fa750b1]{width:100%;font-size:%?24?%;line-height:%?40?%;text-align:center;overflow:hidden;\n /*超出部分隐藏*/white-space:nowrap;\n /*不换行*/text-overflow:ellipsis\n /*超出部分文字以...显示*/}.navigation .navigation-text-item[data-v-1fa750b1]{display:inline-block;padding:%?16?% 0;color:#333;width:25%;text-decoration:none;box-sizing:border-box}.navigation .navigation-text-item .navigation-text-item__title[data-v-1fa750b1]{display:block;width:100%;position:relative;height:%?30?%;font-size:%?24?%;line-height:%?30?%;text-align:center;overflow:hidden;box-sizing:border-box;\n /*超出部分隐藏*/white-space:nowrap;\n /*不换行*/text-overflow:ellipsis;\n /*超出部分文字以...显示*/padding:0 %?20?%;border-right:%?1?% solid #eee}.navigation .one .navigation-text-item:last-child .navigation-text-item__title[data-v-1fa750b1]{border-right:0}.navigation .two .navigation-text-item:last-child .navigation-text-item__title[data-v-1fa750b1]{border-right:0}",""]),t.exports=e},"48dd":function(t,e,a){var i=a("a1a8");e=i(!1),e.push([t.i,".wrap[data-v-3996b947]{width:100%;height:100%;background:rgba(0,0,0,.5)}.wrap .wrap-box[data-v-3996b947]{width:%?600?%;height:%?600?%;position:absolute;left:50%;top:50%;margin-left:%?-300?%;margin-top:%?-400?%}.wrap .close[data-v-3996b947]{display:block;position:absolute;width:%?52?%;height:%?52?%;top:0;right:0;z-index:100}.wrap .close .iconfont[data-v-3996b947]{width:%?52?%;height:%?52?%;font-size:%?52?%;line-height:%?52?%;color:#fff}.wrap .icon[data-v-3996b947]{width:100%;height:100%;position:relative}.wrap .icon .bg[data-v-3996b947]{position:absolute;top:0;left:0;right:0;bottom:0;width:100%;height:100%;display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-align:center;-webkit-align-items:center;align-items:center;-webkit-box-pack:center;-webkit-justify-content:center;justify-content:center}.wrap .icon .bg img[data-v-3996b947]{opacity:0;width:100%;height:100%;-webkit-animation-duration:.6s;animation-duration:.6s;-webkit-animation-name:bg-data-v-3996b947;animation-name:bg-data-v-3996b947;-webkit-animation-fill-mode:forwards;animation-fill-mode:forwards}.wrap .icon .gold[data-v-3996b947]{position:absolute;left:50%;top:50%;margin-top:%?-80?%;margin-left:%?-80?%;display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-align:center;-webkit-align-items:center;align-items:center;-webkit-box-pack:center;-webkit-justify-content:center;justify-content:center;width:%?160?%;height:%?160?%}.wrap .icon .gold img[data-v-3996b947]{opacity:0;-webkit-animation-duration:1.6s;animation-duration:1.6s;-webkit-animation-name:icon-data-v-3996b947;animation-name:icon-data-v-3996b947;-webkit-animation-fill-mode:forwards;animation-fill-mode:forwards;width:100%;height:100%}.wrap .text[data-v-3996b947]{position:absolute;text-align:center;top:%?400?%;left:0;width:100%;opacity:0;-webkit-animation-delay:1.2s;animation-delay:1.2s;-webkit-animation-duration:.4s;animation-duration:.4s;-webkit-animation-name:text-data-v-3996b947;animation-name:text-data-v-3996b947;-webkit-animation-fill-mode:forwards;animation-fill-mode:forwards}.wrap .text .score[data-v-3996b947]{font-size:%?48?%;font-family:PingFang SC;color:#feb805;color:#e29c04;font-weight:800}.wrap .text .tip[data-v-3996b947]{font-size:%?26?%;font-family:PingFang SC;font-weight:500;color:#fff;line-height:%?36?%;color:#fff}@-webkit-keyframes icon-data-v-3996b947{0%{opacity:0;-webkit-transform:scale3d(.8,.8,1);transform:scale3d(.8,.8,1)}25%{opacity:1;-webkit-transform:scaleX(1);transform:scaleX(1)}37.5%{opacity:1;-webkit-transform:scaleX(.05);transform:scaleX(.05)}50%{opacity:1;-webkit-transform:scaleX(1);transform:scaleX(1)}62.5%{opacity:1;-webkit-transform:scaleX(.05);transform:scaleX(.05)}75%{opacity:1;-webkit-transform:scaleX(1);transform:scaleX(1)}100%{opacity:1;-webkit-transform:scaleX(1);transform:scaleX(1)}}@keyframes icon-data-v-3996b947{0%{opacity:0;-webkit-transform:scale3d(.8,.8,1);transform:scale3d(.8,.8,1)}25%{opacity:1;-webkit-transform:scaleX(1);transform:scaleX(1)}37.5%{opacity:1;-webkit-transform:scaleX(.05);transform:scaleX(.05)}50%{opacity:1;-webkit-transform:scaleX(1);transform:scaleX(1)}62.5%{opacity:1;-webkit-transform:scaleX(.05);transform:scaleX(.05)}75%{opacity:1;-webkit-transform:scaleX(1);transform:scaleX(1)}100%{opacity:1;-webkit-transform:scaleX(1);transform:scaleX(1)}}@-webkit-keyframes bg-data-v-3996b947{0%{opacity:0;-webkit-transform:scale3d(.6,.6,1);transform:scale3d(.6,.6,1)}100%{opacity:1;ransform:scale3d(1,1,1)}}@keyframes bg-data-v-3996b947{0%{opacity:0;-webkit-transform:scale3d(.6,.6,1);transform:scale3d(.6,.6,1)}100%{opacity:1;ransform:scale3d(1,1,1)}}@-webkit-keyframes text-data-v-3996b947{0%{opacity:0}100%{opacity:1}}@keyframes text-data-v-3996b947{0%{opacity:0}100%{opacity:1}}",""]),t.exports=e},"4b77":function(t,e,a){"use strict";a.r(e);var i=a("cffc"),n=a("301f");for(var o in n)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return n[t]}))}(o);a("ee59");var r,s=a("5d80"),c=Object(s["a"])(n["default"],i["b"],i["c"],!1,null,"248b002e",null,!1,i["a"],r);e["default"]=c.exports},"4b8b":function(t,e,a){"use strict";var i=a("26bf"),n=a.n(i);n.a},"4bc6":function(t,e,a){"use strict";a.r(e);var i=a("609f"),n=a("bdad");for(var o in n)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return n[t]}))}(o);a("4bc9");var r,s=a("5d80"),c=Object(s["a"])(n["default"],i["b"],i["c"],!1,null,"1fa750b1",null,!1,i["a"],r);e["default"]=c.exports},"4bc9":function(t,e,a){"use strict";var i=a("3ec4"),n=a.n(i);n.a},"4d2e":function(t,e,a){var i=a("a1a8");e=i(!1),e.push([t.i,".he-open-subscribe[data-v-2e79a977]{position:relative;overflow:hidden}",""]),t.exports=e},"4f43":function(t,e,a){"use strict";var i;a.d(e,"b",(function(){return n})),a.d(e,"c",(function(){return o})),a.d(e,"a",(function(){return i}));var n=function(){var t=this,e=t.$createElement,a=t._self._c||e;return a("v-uni-view",{staticClass:"goods",style:{backgroundColor:t.facade.background_color},attrs:{"data-theme":t.theme}},[a("v-uni-view",{staticClass:"goods-layout",class:{larger:1==t.facade.list_style,small:2==t.facade.list_style,list:3==t.facade.list_style,swipe:4==t.facade.list_style},style:{paddingLeft:t.facade.padding+"px",paddingRight:t.facade.padding+"px",marginLeft:-t.facade.margin/2+"px",marginRight:-t.facade.margin/2+"px"}},[t._l(t.goodsData,(function(e,i){return a("v-uni-view",{key:i,staticClass:"goods-wrapper",class:{white:1==t.facade.card_style,card:2==t.facade.card_style,stroke:3==t.facade.card_style,lucency:4==t.facade.card_style,chamfer:t.facade.chamfer_style}},["商品名称"!==e.name?a("v-uni-view",{staticClass:"goods-item",style:{margin:t.facade.margin/2+"px"},on:{click:function(a){arguments[0]=a=t.$handleEvent(a),t.navigateToDetail(e.id)}}},[a("v-uni-view",{staticClass:"goods-item-photo"},[a("v-uni-view",{staticClass:"goods-item-image"},[a("v-uni-view",{staticClass:"goods-item-cover"},[a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{"lazy-load":!0,src:t.getGoodsCover(e.slideshow),mode:t.mode}})],1)],1)],1),t.is_hide?a("v-uni-view",{staticClass:"goods-item-detail"},[t.content.is_title?a("v-uni-view",{staticClass:"goods-item-title"},[t._v(t._s(e.name))]):t._e(),a("v-uni-view",{staticClass:"goods-item-info"},[a("v-uni-view",{staticClass:"goods-item-price"},[t.content.is_price?a("v-uni-view",[a("span",{staticClass:"goods-item-price__tag"},[t._v("¥")]),a("span",{staticClass:"goods-item-price__val"},[t._v(t._s(e.price))])]):t._e()],1),t.content.is_button?a("v-uni-view",{staticClass:"goods-item-button",on:{click:function(a){a.stopPropagation(),arguments[0]=a=t.$handleEvent(a),t.cart(e)}}},[a("v-uni-text",{staticClass:"iconfont iconbtn_addtocart"})],1):t._e()],1)],1):t._e()],1):t._e()],1)})),a("v-uni-view",{staticClass:"clear"})],2),a("he-index-cart",{attrs:{"goods-id":t.goodsId},on:{"update:goodsId":function(e){arguments[0]=e=t.$handleEvent(e),t.goodsId=e},"update:goods-id":function(e){arguments[0]=e=t.$handleEvent(e),t.goodsId=e}}})],1)},o=[]},5191:function(t,e,a){var i=a("0ff2");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var n=a("5c0d").default;n("21793f9a",i,!0,{sourceMap:!1,shadowMode:!1})},"51fa":function(t,e,a){var i=a("a8fb");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var n=a("5c0d").default;n("9579a6dc",i,!0,{sourceMap:!1,shadowMode:!1})},5242:function(t,e,a){var i=a("a1a8");e=i(!1),e.push([t.i,".pointer[data-v-79120b0a]{position:absolute;bottom:0;display:-webkit-box;display:-webkit-flex;display:flex;width:100%}.pointer .circle .pointer-item[data-v-79120b0a]{display:inline-block;width:%?12?%;height:%?12?%;background-color:rgba(0,0,0,.3);border-radius:100%}.pointer .strip .pointer-item[data-v-79120b0a]{display:inline-block;width:%?24?%;height:%?4?%;background-color:#c5c5c5}.pointer .pointer-item + .pointer-item[data-v-79120b0a]{margin-left:%?12?%}.pointer .pointer-content[data-v-79120b0a]{margin:0 %?40?%;width:100%;box-sizing:border-box;text-align:right}.pointer .pointer-content[data-v-79120b0a] .active{background-color:#f44;opacity:1}.pointer .pointer-text[data-v-79120b0a]{margin:0 %?40?%;width:100%;text-align:center}.pointer .pointer-text span[data-v-79120b0a]{display:inline-block;min-width:%?32?%;height:%?32?%;padding:0 %?10?%;color:#fff;font-size:%?24?%;line-height:%?32?%;background:#000;border-radius:%?16?%;opacity:.3}",""]),t.exports=e},"541d":function(t,e,a){"use strict";var i=a("ac5d"),n=a.n(i);n.a},5420:function(t,e,a){"use strict";var i;a.d(e,"b",(function(){return n})),a.d(e,"c",(function(){return o})),a.d(e,"a",(function(){return i}));var n=function(){var t=this,e=t.$createElement,a=t._self._c||e;return a("v-uni-view",{staticClass:"le-notice"},[t.content.title?a("item",{attrs:{speed:t.facade.speed||80,"icon-url":t.content.icon,text:t.content.title,showIcon:!0,scrollable:!0,"background-color":t.facade.background_color,color:t.facade.title_color}}):t._e()],1)},o=[]},"564e5":function(t,e,a){"use strict";a.r(e);var i=a("f2f1"),n=a("071a");for(var o in n)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return n[t]}))}(o);a("6e21");var r,s=a("5d80"),c=Object(s["a"])(n["default"],i["b"],i["c"],!1,null,"cecbda32",null,!1,i["a"],r);e["default"]=c.exports},"57e7":function(t,e,a){"use strict";var i;a.d(e,"b",(function(){return n})),a.d(e,"c",(function(){return o})),a.d(e,"a",(function(){return i}));var n=function(){var t=this,e=t.$createElement,a=t._self._c||e;return a("v-uni-scroll-view",{staticClass:"coupon",attrs:{"scroll-x":!0}},[a("v-uni-view",{staticClass:"le-coupon-box",class:[t.couponBox]},t._l(t.list,(function(e,i){return a("v-uni-view",{key:i,class:[t.couponItem],style:[t.itemStyle(e)]},[e.can_obtain?a("he-open-subscribe",{key:i,attrs:{"template-id":t.subTemplateId,digital:e},on:{"open-subscribe-success":function(e){arguments[0]=e=t.$handleEvent(e),t.receive.apply(void 0,arguments)}}},[a("item",{attrs:{facade:t.facade,content:t.content,item:e}})],1):a("item",{attrs:{facade:t.facade,content:t.content,item:e}})],1)})),1)],1)},o=[]},5815:function(t,e,a){"use strict";a.r(e);var i=a("41a8"),n=a.n(i);for(var o in i)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return i[t]}))}(o);e["default"]=n.a},5830:function(t,e,a){"use strict";a.r(e);var i=a("db8e"),n=a("1ff8");for(var o in n)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return n[t]}))}(o);a("b4cc");var r,s=a("5d80"),c=Object(s["a"])(n["default"],i["b"],i["c"],!1,null,"6e7a2b50",null,!1,i["a"],r);e["default"]=c.exports},"5a7d":function(t,e,a){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0,a("4cfc");var i=uni.getSystemInfoSync(),n={},o={name:"u-navbar",props:{height:{type:[String,Number],default:""},backIconColor:{type:String,default:"#606266"},backIconName:{type:String,default:"nav-back"},backIconSize:{type:[String,Number],default:"44"},backText:{type:String,default:""},backTextStyle:{type:Object,default:function(){return{color:"#606266"}}},title:{type:String,default:""},titleWidth:{type:[String,Number],default:"250"},titleColor:{type:String,default:"#000"},titleBold:{type:Boolean,default:!1},titleSize:{type:[String,Number],default:32},isBack:{type:[Boolean,String],default:!0},background:{type:Object,default:function(){return{background:"transparent"}}},isFixed:{type:Boolean,default:!0},immersive:{type:Boolean,default:!1},borderBottom:{type:Boolean,default:!0},zIndex:{type:[String,Number],default:""},customBack:{type:Function,default:null}},data:function(){return{menuButtonInfo:n,statusBarHeight:i.statusBarHeight}},computed:{navbarInnerStyle:function(){var t={};return t.height=this.navbarHeight+"px",t},navbarStyle:function(){var t={};return Object.assign(t,this.background),t},titleStyle:function(){var t={};return t.left=(i.windowWidth-uni.upx2px(this.titleWidth))/2+"px",t.right=(i.windowWidth-uni.upx2px(this.titleWidth))/2+"px",t.width=uni.upx2px(this.titleWidth)+"px",t},navbarHeight:function(){return this.height?this.height:44}},created:function(){},methods:{goBack:function(){"function"===typeof this.customBack||uni.navigateBack({delta:1,fail:function(){uni.switchTab({url:"/pages/index/index"})}})}}};e.default=o},"5b2a":function(t,e,a){"use strict";var i=a("99ca").default;Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0,a("c342"),a("211d"),a("f9ee");var n=i(a("06c4")),o=i(a("639e")),r=a("7736"),s={components:{pointer:o.default},props:{value:{type:Boolean,default:!1}},data:function(){return{display:!0,def_content:[],facade:{},content:{},step:1,current:0,autoplay:!1,circular:!1}},computed:(0,n.default)({header:function(){var t=uni.getSystemInfoSync();return t.statusBarHeight+55+"px"},height:function(){var t=uni.getSystemInfoSync();return t.windowHeight+"px"},contentData:function(){var t=[];for(var e in this.content){var a=this.content[e];a.url&&t.push(a)}return t},margin:function(){return 1==this.facade.chamfer_style?10:20}},(0,r.mapGetters)("setting",{openingad:"getOpeningad"})),mounted:function(){var t,e,a=uni.getStorageSync("openingad"),i=null!==(t=this.openingad)&&void 0!==t&&t.type?this.openingad.type:1,n=null===(e=this.openingad)||void 0===e?void 0:e.days;if(1===i)a?this.display=!1:(this.display=!0,this.handleLoadData());else{var o=uni.getStorageSync("openingad_create_time"),r=Date.parse(new Date);!o||o<r?(uni.removeStorageSync("openingad"),this.display=!0,uni.setStorageSync("openingad_create_time",Date.parse(new Date)+86400*n*1e3),this.handleLoadData()):(this.display=!1,uni.setStorageSync("openingad","1"))}},methods:{handleLoadData:function(){var t=this;this.$heshop.search("POST",{include:"setting"},{keyword:"openingad"}).then((function(e){if(e&&e.content){t.display=!0,t.content=e.content.content,t.facade=e.content.facade;var a=[];for(var i in t.content){var n=t.content[i];n.url&&a.push(n)}0===a.length&&t.toSkip()}else t.toSkip()})).catch((function(e){t.display=!1,t.$message.error("加载配置信息失败,请检查网络")}))},handleChange:function(t){var e=this;t.detail.current>=this.contentData.length?this.current=this.contentData.length-1:this.current=t.detail.current,this.step++,t.detail.current===this.contentData.length&&setTimeout((function(){e.toSkip()}),1e3)},getCover:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",e="";return t&&"[object Array]"===Object.prototype.toString.call(t)&&t[0]?t[0].url:e},toSkip:function(){uni.setStorageSync("openingad","1"),this.display=!1,this.$emit("confirm",!0)},touchStart:function(t){},touchEnd:function(t){1===this.contentData.length&&this.toSkip()}}};e.default=s},"5f35":function(t,e,a){"use strict";a.r(e);var i=a("cf78"),n=a("80f1");for(var o in n)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return n[t]}))}(o);a("4b8b");var r,s=a("5d80"),c=Object(s["a"])(n["default"],i["b"],i["c"],!1,null,"123d0c79",null,!1,i["a"],r);e["default"]=c.exports},"5f42":function(t,e,a){var i=a("34c7");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var n=a("5c0d").default;n("6872ea14",i,!0,{sourceMap:!1,shadowMode:!1})},"609f":function(t,e,a){"use strict";var i;a.d(e,"b",(function(){return n})),a.d(e,"c",(function(){return o})),a.d(e,"a",(function(){return i}));var n=function(){var t=this,e=t.$createElement,a=t._self._c||e;return a("v-uni-view",{staticClass:"navigation",style:{"background-color":t.facade.background_color}},[2==t.content.style&&1==t.facade.nav_style?a("v-uni-view",{staticClass:"navigation-text",class:{one:1==t.facade.nav_style}},[t._l(t.navigation,(function(e,i){return[11===e.link.index?[a("v-uni-view",{key:i,staticClass:"navigation-text-item",style:{width:t.width}},[a("he-open-launch-weapp",{attrs:{username:e.link.param.wechat.appId,path:e.link.param.wechat.path}},[a("v-uni-text",{staticClass:"navigation-text-item__title",style:{color:t.facade.text_color}},[t._v(t._s(e.title))])],1)],1)]:[a("v-uni-view",{key:i,staticClass:"navigation-text-item",style:{width:t.width}},[a("v-uni-text",{staticClass:"navigation-text-item__title",style:{color:t.facade.text_color},on:{click:function(a){arguments[0]=a=t.$handleEvent(a),t.navigateToDetail(e.link)}}},[t._v(t._s(e.title))])],1)]]}))],2):t._e(),2==t.content.style&&2==t.facade.nav_style?a("v-uni-swiper",{style:{height:t.swiperHeight},on:{change:function(e){arguments[0]=e=t.$handleEvent(e),t.onCurrent.apply(void 0,arguments)}}},t._l(t.number,(function(e,i){return a("v-uni-swiper-item",{key:e,staticClass:"navigation-text",class:{one:1==t.facade.nav_style,two:2==t.facade.nav_style}},[t._l(t.getNavigateList(i),(function(e,n){return[11===e.link.index?[a("v-uni-view",{key:n,staticClass:"navigation-text-item",style:{width:t.width}},[a("he-open-launch-weapp",{attrs:{username:e.link.param.wechat.appId,path:e.link.param.wechat.path}},[a("v-uni-text",{staticClass:"navigation-text-item__title",style:{color:t.facade.text_color}},[t._v(t._s(e.title))])],1)],1)]:[a("v-uni-view",{key:n,staticClass:"navigation-text-item",style:{width:t.width}},[a("v-uni-text",{staticClass:"navigation-text-item__title",style:{color:t.facade.text_color},on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.getNavigateToDetail(i,n)}}},[t._v(t._s(e.title))])],1)]]}))],2)})),1):t._e(),1==t.content.style&&1==t.facade.nav_style?a("v-uni-view",{staticClass:"navigation-image",class:{one:1==t.facade.nav_style}},[t._l(t.navigation,(function(e,i){return[11===e.link.index?[a("v-uni-view",{key:i,staticClass:"navigation-image-item",style:{width:t.width}},[a("he-open-launch-weapp",{attrs:{username:e.link.param.wechat.appId,path:e.link.param.wechat.path}},[a("v-uni-view",{staticClass:"navigation-image-item__cover",style:{"background-image":"url("+t.getCover(e.url)+")"}}),a("v-uni-view",{staticClass:"navigation-image-item__title",style:{color:t.facade.text_color}},[t._v(t._s(e.title))])],1)],1)]:[a("v-uni-view",{key:i,staticClass:"navigation-image-item",style:{width:t.width},on:{click:function(a){arguments[0]=a=t.$handleEvent(a),t.navigateToDetail(e.link)}}},[a("v-uni-view",{staticClass:"navigation-image-item__cover",style:{"background-image":"url("+t.getCover(e.url)+")"}}),a("v-uni-view",{staticClass:"navigation-image-item__title",style:{color:t.facade.text_color}},[t._v(t._s(e.title))])],1)]]}))],2):t._e(),1==t.content.style&&2==t.facade.nav_style?a("v-uni-swiper",{staticStyle:{height:"220px"},style:{height:t.swiperHeight},on:{change:function(e){arguments[0]=e=t.$handleEvent(e),t.onCurrent.apply(void 0,arguments)}}},t._l(t.number,(function(e,i){return a("v-uni-swiper-item",{key:e,staticClass:"navigation-image two"},[t._l(t.getNavigateList(i),(function(e,n){return[11===e.link.index?[a("v-uni-view",{key:n,staticClass:"navigation-image-item",style:{width:t.width}},[a("he-open-launch-weapp",{attrs:{username:e.link.param.wechat.appId,path:e.link.param.wechat.path}},[a("v-uni-view",{staticClass:"navigation-image-item__cover",style:{"background-image":"url("+t.getCover(e.url)+")"}}),a("v-uni-view",{staticClass:"navigation-image-item__title",style:{color:t.facade.text_color}},[t._v(t._s(e.title))])],1)],1)]:[a("v-uni-view",{key:n,staticClass:"navigation-image-item",style:{width:t.width},on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.getNavigateToDetail(i,n)}}},[a("v-uni-view",{staticClass:"navigation-image-item__cover",style:{"background-image":"url("+t.getCover(e.url)+")"}}),a("v-uni-view",{staticClass:"navigation-image-item__title",style:{color:t.facade.text_color}},[t._v(t._s(e.title))])],1)]]}))],2)})),1):t._e(),2==t.facade.nav_style?a("v-uni-view",{staticClass:"navigation-indicator"},[t.number>1?a("pointer",{attrs:{current:t.current,number:t.number,margin:t.margin,color:t.facade.active_color,type:"facade.indicator_style",align:"center"}}):t._e()],1):t._e()],1)},o=[]},"624a":function(t,e,a){var i=a("a1a8");e=i(!1),e.push([t.i,".box[data-v-eb7cd128]{width:%?590?%;height:%?576?%;background-color:#fff;margin-bottom:%?48?%;border-radius:%?16?%}.image[data-v-eb7cd128]{width:%?317?%;height:%?320?%}.text[data-v-eb7cd128]{font-size:%?28?%;font-family:PingFang SC;font-weight:500;color:#222;line-height:%?40?%;width:%?410?%;text-align:center}.cu-btn[data-v-eb7cd128]{width:%?242?%;height:%?72?%;background:#e60b30;border-radius:%?36?%;margin-top:%?48?%;font-size:%?28?%;font-family:PingFang SC;font-weight:500;color:#fff}.iconpopup_close2[data-v-eb7cd128]{font-size:%?52?%;color:#fff}",""]),t.exports=e},"639e":function(t,e,a){"use strict";a.r(e);var i=a("eef1"),n=a("85f9");for(var o in n)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return n[t]}))}(o);a("43ae");var r,s=a("5d80"),c=Object(s["a"])(n["default"],i["b"],i["c"],!1,null,"79120b0a",null,!1,i["a"],r);e["default"]=c.exports},"642e":function(t,e,a){var i=a("a1a8");e=i(!1),e.push([t.i,'.le-coupon-item[data-v-885244ce]{height:%?160?%;border-radius:%?16?%;position:relative}.le-coupon-item .le-coupon-item-content[data-v-885244ce]{height:100%}.le-coupon-item .le-coupon-item-content .le-coupon-item-left[data-v-885244ce]{border-top-left-radius:%?16?%;border-bottom-left-radius:%?16?%;margin:%?10?% 0 %?10?% %?10?%}.le-coupon-item .le-coupon-item-content .le-coupon-item-center[data-v-885244ce]{width:%?28?%;position:relative;overflow:hidden;height:100%}.le-coupon-item .le-coupon-item-content .le-coupon-item-center .le-item-doc[data-v-885244ce]{position:absolute;border-radius:50%;left:50%;width:%?16?%;height:%?16?%;background:#fff}.le-coupon-item .le-coupon-item-content .le-coupon-item-center .le-item-doc-a[data-v-885244ce]{-webkit-transform:translate(-50%,-50%);transform:translate(-50%,-50%)}.le-coupon-item .le-coupon-item-content .le-coupon-item-center .le-item-doc-b[data-v-885244ce]{bottom:0;-webkit-transform:translate(-50%,50%);transform:translate(-50%,50%)}.le-coupon-item .le-coupon-item-content .le-coupon-item-center .le-item-center[data-v-885244ce]{width:%?28?%;height:calc(100% - %?20?%);margin:%?10?% 0;position:relative;overflow:hidden}.le-coupon-item .le-coupon-item-content .le-coupon-item-center .le-item-center .sawtooth[data-v-885244ce]{display:block;width:%?16?%;height:%?110?%;background-image:-webkit-radial-gradient(circle,#fff 30%,transparent 35%);background-image:radial-gradient(circle,#fff 30%,transparent 35%);background-size:%?16?% %?22?%;background-repeat:repeat-y;position:relative;top:50%;left:50%;-webkit-transform:translate(-50%,-50%);transform:translate(-50%,-50%)}.le-coupon-item .le-coupon-item-content .le-coupon-item-center .le-item-center .le-item-center-doc[data-v-885244ce]{width:%?32?%;height:%?32?%;border:%?2?% solid transparent;border-radius:50%;position:absolute;left:50%;-webkit-transform:translateX(-50%);transform:translateX(-50%)}.le-coupon-item .le-coupon-item-content .le-coupon-item-center .le-item-center .le-item-center-doc-a[data-v-885244ce]{top:%?-22?%}.le-coupon-item .le-coupon-item-content .le-coupon-item-center .le-item-center .le-item-center-doc-b[data-v-885244ce]{bottom:%?-22?%}.le-coupon-item .le-coupon-item-content .le-coupon-item-center .le-coupon-item-center-line[data-v-885244ce]{position:absolute;width:%?2?%;height:%?100?%;top:50%;left:50%;background-size:%?2?% %?20?%;background-repeat:repeat-y;background-position:50%;-webkit-transform:translate(-50%,-50%);transform:translate(-50%,-50%)}.le-coupon-item .le-coupon-item-content .le-coupon-item-right[data-v-885244ce]{margin:%?10?% %?10?% %?10?% 0;border-top-right-radius:%?16?%;border-bottom-right-radius:%?16?%;padding:%?7?% 0}.le-coupon-item .le-coupon-item-content .le-coupon-item-price[data-v-885244ce]{font-family:DIN;font-weight:700;text-align:center}.le-coupon-item .le-coupon-item-content .le-coupon-item-price[data-v-885244ce]:before{content:"¥";font-size:%?24?%;font-family:PingFang SC;font-weight:500}.le-coupon-item .le-coupon-item-content .le-coupon-item-min[data-v-885244ce]{font-family:PingFang SC;font-weight:500;text-align:center}.le-coupon-item .le-coupon-item-content .le-coupon-iem-appoint[data-v-885244ce]{font-size:%?22?%;font-family:PingFang SC;font-weight:500;line-height:%?28?%}.le-coupon-item .le-coupon-item-content .le-coupon-btn[data-v-885244ce]{text-align:center}.le-coupon-item .le-coupon-item-content .le-coupon-item-text[data-v-885244ce]{padding:%?22?% 0 %?22?% %?26?%}.le-coupon-item .le-coupon-item-content .le-coupon-item-name[data-v-885244ce]{font-size:%?30?%;font-family:PingFang SC;font-weight:500;line-height:%?40?%}.le-item-marginRight-odd[data-v-885244ce]:nth-child(odd),\n.le-item-marginRight[data-v-885244ce]{margin-right:%?12?%}.le-item-Jagged[data-v-885244ce]{position:absolute;width:%?16?%;height:%?140?%;background-image:-webkit-radial-gradient(circle,#fff 40%,transparent 45%);background-image:radial-gradient(circle,#fff 40%,transparent 45%);background-size:%?16?% %?36?%;background-repeat:repeat-y;top:50%}.le-item-Jagged[data-v-885244ce]:first-child{left:0;-webkit-transform:translate(-50%,-50%);transform:translate(-50%,-50%)}.le-item-Jagged[data-v-885244ce]:last-child{right:0;-webkit-transform:translate(50%,-50%);transform:translate(50%,-50%)}.le-coupon-item.fillet .le-coupon-item-left[data-v-885244ce]:before,\n.le-coupon-item.fillet .le-coupon-item-left[data-v-885244ce]:after{content:"";display:block;position:absolute;width:%?30?%;height:%?30?%;background-image:-webkit-radial-gradient(circle,#fff 70%,transparent 0);background-image:radial-gradient(circle,#fff 70%,transparent 0);background-size:%?30?% %?30?%;background-repeat:no-repeat}.le-coupon-item.fillet .le-coupon-item-left[data-v-885244ce]:before{left:0;top:0;-webkit-transform:translate(-45%,-45%);transform:translate(-45%,-45%)}.le-coupon-item.fillet .le-coupon-item-left[data-v-885244ce]:after{left:0;bottom:0;-webkit-transform:translate(-45%,45%);transform:translate(-45%,45%)}.le-coupon-item.fillet .le-coupon-item-right[data-v-885244ce]:before,\n.le-coupon-item.fillet .le-coupon-item-right[data-v-885244ce]:after{content:"";display:block;position:absolute;width:%?30?%;height:%?30?%;background-image:-webkit-radial-gradient(circle,#fff 70%,transparent 0);background-image:radial-gradient(circle,#fff 70%,transparent 0);background-size:%?30?% %?30?%;background-repeat:no-repeat}.le-coupon-item.fillet .le-coupon-item-right[data-v-885244ce]:before{right:0;top:0;-webkit-transform:translate(45%,-45%);transform:translate(45%,-45%)}.le-coupon-item.fillet .le-coupon-item-right[data-v-885244ce]:after{right:0;bottom:0;-webkit-transform:translate(45%,45%);transform:translate(45%,45%)}',""]),t.exports=e},"64f7":function(t,e,a){"use strict";a.r(e);var i=a("cd93"),n=a.n(i);for(var o in i)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return i[t]}))}(o);e["default"]=n.a},"65da":function(t,e,a){var i=a("4d2e");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var n=a("5c0d").default;n("565fa0fe",i,!0,{sourceMap:!1,shadowMode:!1})},6686:function(t,e,a){"use strict";var i;a.d(e,"b",(function(){return n})),a.d(e,"c",(function(){return o})),a.d(e,"a",(function(){return i}));var n=function(){var t=this,e=t.$createElement,a=t._self._c||e;return t.display?a("v-uni-view",{staticClass:"ad",class:{ad_element:t.current>0}},[t.contentData.length?a("v-uni-view",{staticClass:"ad-item-photo",style:{width:"100%",height:"100vh"}},[a("v-uni-swiper",{staticClass:"ad-item-image",attrs:{circular:t.circular,autoplay:t.autoplay,"easing-function":"easeOutCubic"},on:{change:function(e){arguments[0]=e=t.$handleEvent(e),t.handleChange.apply(void 0,arguments)}}},[t._l(t.contentData,(function(e,i){return a("v-uni-swiper-item",{key:i,staticClass:"ad-item-cover",staticStyle:{"background-color":"#ffffff"}},[a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{"lazy-load":!0,src:e.url,mode:"aspectFill"},on:{touchstart:function(e){arguments[0]=e=t.$handleEvent(e),t.touchStart.apply(void 0,arguments)},touchend:function(e){arguments[0]=e=t.$handleEvent(e),t.touchEnd.apply(void 0,arguments)}}})],1)})),a("v-uni-swiper-item",[a("v-uni-view",{staticStyle:{width:"100%",height:"100vh","background-color":"rgba(0, 0, 0, 0)"}})],1)],2),t.facade.chamfer_skip?a("v-uni-view",{staticClass:"is_skip",style:{top:t.header},on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.toSkip.apply(void 0,arguments)}}},[a("v-uni-view",{staticClass:"is_skip_bg"}),a("v-uni-view",{staticClass:"is_skip_txt"},[t._v("跳过")])],1):t._e(),a("v-uni-view",{staticClass:"ad-pointer",class:{circle:1==t.facade.indicator_style,strip:2==t.facade.indicator_style,number:3==t.facade.indicator_style,left:"left"===t.facade.indicator_align,center:"center"===t.facade.indicator_align,right:"right"===t.facade.indicator_align}},[t._l(t.contentData,(function(e,i){return 3!=t.facade.indicator_style?a("v-uni-view",{key:i,staticClass:"ad-pointer_item"},[a("v-uni-button",{class:{is_active:i===t.current},style:{backgroundColor:i===t.current?t.facade.indicator_color:"none"}})],1):t._e()})),3==t.facade.indicator_style?a("v-uni-view",{staticClass:"ad-pointer_number"},[t._v(t._s(t.current+1+"/"+t.contentData.length))]):t._e()],2)],1):t._e()],1):t._e()},o=[]},6741:function(t,e,a){"use strict";a.r(e);var i=a("0b7e"),n=a.n(i);for(var o in i)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return i[t]}))}(o);e["default"]=n.a},"67a8":function(t,e,a){var i=a("5242");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var n=a("5c0d").default;n("2aabcdd8",i,!0,{sourceMap:!1,shadowMode:!1})},"6b60":function(t,e,a){"use strict";var i;a.d(e,"b",(function(){return n})),a.d(e,"c",(function(){return o})),a.d(e,"a",(function(){return i}));var n=function(){var t=this,e=t.$createElement,a=t._self._c||e;return a("v-uni-view",{staticClass:"separate",style:{paddingTop:t.facade.margin+"px",paddingBottom:t.facade.margin+"px"}},[a("v-uni-view",{style:{borderTopWidth:"1px",borderTopStyle:t.content.style,borderTopColor:t.facade.fill_color}})],1)},o=[]},"6ce5":function(t,e,a){"use strict";a.r(e);var i=a("7d67"),n=a.n(i);for(var o in i)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return i[t]}))}(o);e["default"]=n.a},"6db9":function(t,e,a){"use strict";var i=a("74b9"),n=a.n(i);n.a},"6e21":function(t,e,a){"use strict";var i=a("770c"),n=a.n(i);n.a},"708d":function(t,e,a){var i=a("a1a8");e=i(!1),e.push([t.i,'@charset "UTF-8";\n/* start--主题色--start */\n/* end--主题色--end */.pages[data-v-ddf4ab52]{width:100%;min-height:100vh;background-color:#f5f5f5}.he-page-title[data-v-ddf4ab52]{background-color:#fff;position:fixed;z-index:10;width:100%;top:0;text-align:center}.he-search[data-v-ddf4ab52]{background:#fff;border:%?2?% solid #e5e5e5;border-radius:%?32?%;margin:0 %?20?%;width:100%;padding-left:%?24?%;height:%?63?%}.he-search-text[data-v-ddf4ab52]{display:inline-block;font-size:%?26?%;font-family:PingFang SC;font-weight:500;color:#999;margin-left:%?12?%}.iconsearchbar_search[data-v-ddf4ab52]{font-size:%?24?%}',""]),t.exports=e},7100:function(t,e,a){"use strict";a.r(e);var i=a("d3f9"),n=a.n(i);for(var o in i)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return i[t]}))}(o);e["default"]=n.a},"724d":function(t,e,a){"use strict";a.r(e);var i=a("166b"),n=a.n(i);for(var o in i)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return i[t]}))}(o);e["default"]=n.a},"73e4":function(t,e,a){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0,a("4cfc");var i={name:"he-open-subscribe",props:{templateId:{type:Array,default:function(){return[]}},digital:{type:[Array,Object,Number],default:function(){return{}}}},data:function(){return{subscribeId:this.$h.guid()+"_subscribe",isShow:!0}},methods:{subscribe:function(){this.isShow||this.$emit("open-subscribe-success",this.digital)}},mounted:function(){var t=this,e=document.getElementById(t.subscribeId);e.addEventListener("success",(function(){t.$emit("open-subscribe-success",t.digital)})),e.addEventListener("error",(function(e){e.detail.errCode;t.isShow=!1}))}};e.default=i},7423:function(t,e,a){"use strict";var i=a("e3bf"),n=a("aacd").map,o=a("8907"),r=o("map");i({target:"Array",proto:!0,forced:!r},{map:function(t){return n(this,t,arguments.length>1?arguments[1]:void 0)}})},"74b9":function(t,e,a){var i=a("f4ca");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var n=a("5c0d").default;n("418fc35a",i,!0,{sourceMap:!1,shadowMode:!1})},"770c":function(t,e,a){var i=a("df35");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var n=a("5c0d").default;n("23d82fd4",i,!0,{sourceMap:!1,shadowMode:!1})},"779c":function(t,e,a){"use strict";var i;a.d(e,"b",(function(){return n})),a.d(e,"c",(function(){return o})),a.d(e,"a",(function(){return i}));var n=function(){var t=this,e=t.$createElement,a=t._self._c||e;return a("v-uni-view",{staticClass:"le-coupon-item",class:[t.couponItem],style:[t.itemStyle(t.item)]},[2===t.content.style?a("v-uni-view",{staticClass:"le-item-Jagged"}):t._e(),a("v-uni-view",{staticClass:"le-coupon-item-content flex"},[a("v-uni-view",{staticClass:"le-coupon-item-left",style:[t.borderStyle(t.item),t.leftStyle(t.item)]},[a("v-uni-view",{staticClass:"le-coupon-item-price",style:[t.textStyle(t.item),t.priceStyle]},[t._v(t._s(t._f("setNumber")(t.item.sub_price)))]),1!==t.facade.list_style?a("v-uni-view",{staticClass:"le-coupon-iem-appoint",style:[t.textStyle(t.item),t.appointStyle]},[t._v(t._s(1===t.item.appoint_type?"全部商品可用":"部分商品可用"))]):t._e(),a("v-uni-view",{staticClass:"le-coupon-item-min",style:[t.textStyle(t.item),t.minStyle]},[0!==Number(t.item.min_price)?[t._v("满"+t._s(t._f("setNumber")(t.item.min_price))+"可用")]:[t._v("无门槛")]],2)],1),a("v-uni-view",{staticClass:"le-coupon-item-center"},[1===t.content.style?[a("v-uni-view",{staticClass:"le-item-doc le-item-doc-a"}),a("v-uni-view",{staticClass:"le-item-doc le-item-doc-b"}),a("v-uni-view",{staticClass:"le-item-center"},[a("v-uni-view",{staticClass:"sawtooth"}),a("v-uni-view",{staticClass:"le-item-center-doc le-item-center-doc-a",style:[t.borderStyle(t.item)]}),a("v-uni-view",{staticClass:"le-item-center-doc le-item-center-doc-b",style:[t.borderStyle(t.item)]})],1)]:2===t.content.style?a("v-uni-view",{staticClass:"le-coupon-item-center-line",style:[t.lineColor]}):t._e()],2),a("v-uni-view",{staticClass:"le-coupon-item-right",class:[t.rightClass],style:[t.borderStyle(t.item),t.rightStyle(t.item)]},[1===t.facade.list_style?a("v-uni-view",{staticClass:"flex flex-sub flex-direction justify-between le-coupon-item-text"},[a("v-uni-view",{staticClass:"le-coupon-item-name",style:[t.textStyle(t.item)]},[t._v(t._s(t.item.name))]),a("v-uni-view",{staticClass:"le-coupon-iem-appoint",style:[t.textStyle(t.item),t.appointStyle]},[t._v(t._s(1===t.item.appoint_type?"全部商品可用":"部分商品可用"))])],1):t._e(),a("v-uni-view",{staticClass:"le-coupon-btn",style:[t.textStyle(t.item),t.couponBtn]},[t._v(t._s(t.item.can_obtain?"领取":"已领取"))])],1)],1),2===t.content.style?a("v-uni-view",{staticClass:"le-item-Jagged"}):t._e()],1)},o=[]},"7b62":function(t,e,a){var i=a("c441");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var n=a("5c0d").default;n("0ff5ac18",i,!0,{sourceMap:!1,shadowMode:!1})},"7d67":function(t,e,a){"use strict";var i=a("99ca").default;Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0,a("b5aa");var n=i(a("e9ff")),o=i(a("06c4"));a("4cfc"),a("f9ee"),a("c342");var r=i(a("857d")),s=a("7736"),c={components:{Goods:r.default},props:{facade:{type:[Object,Array],default:function(){return{background_color:"#7f7f7f"}}},content:{type:[Object,Array]},dataIndex:{type:Number},pageIndex:{type:Number}},data:function(){return{is_arrow:!1,active:!1,select:0,scrollWdith:0,halfWidth:null}},computed:(0,o.default)((0,o.default)({goodsContent:function(){if(this.content.data.length>0){var t=this.content.data[this.select];return(0,o.default)((0,o.default)({},t),{},{is_title:this.content.is_title,is_price:this.content.is_price,is_button:this.content.is_button})}return{type:1,goods:[],group:{},is_title:this.content.is_title,is_price:this.content.is_price,is_button:this.content.is_button}}},(0,s.mapGetters)({searchHeight:"components/getSearchHeight",searchIndex:"components/getSearchIndex",navbarHeight:"setting/getNavBarHeight",statusBarHeight:"setting/statusBarHeight"})),{},{top:function(){return this.navbarHeight+this.statusBarHeight}}),mounted:function(){var t=this;return(0,n.default)(regeneratorRuntime.mark((function e(){var a,i;return regeneratorRuntime.wrap((function(e){while(1)switch(e.prev=e.next){case 0:for(t.getElRect("tabs-header").then((function(e){t.halfWidth=e.width/2})),a=function(e){t.getElRect("he-tab-item_"+e).then((function(a){t.content.data[e].rect=a}))},i=0;i<t.content.data.length;i++)a(i);case 3:case"end":return e.stop()}}),e)})))()},methods:{getContent:function(t){return(0,o.default)((0,o.default)({},t),{},{is_title:this.content.is_title,is_price:this.content.is_price,is_button:this.content.is_button})},radioChange:function(t){if(t!=this.select){this.select=t;var e=this.content.data[t].rect,a=e.left,i=e.width;a+i/2<=this.halfWidth?this.scrollWdith=0:this.scrollWdith=a+i/2-this.halfWidth}},getElRect:function(t){var e=this;return new Promise((function(a){var i=uni.createSelectorQuery().in(e);i.select("."+t).boundingClientRect((function(i){i?a(i):setTimeout((function(){e.getElRect(t)}),10)})).exec()}))}}};e.default=c},8069:function(t,e,a){"use strict";a.r(e);var i=a("3f77"),n=a.n(i);for(var o in i)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return i[t]}))}(o);e["default"]=n.a},"80f1":function(t,e,a){"use strict";a.r(e);var i=a("0e49"),n=a.n(i);for(var o in i)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return i[t]}))}(o);e["default"]=n.a},8252:function(t,e,a){var i=a("a1a8");e=i(!1),e.push([t.i,".banner[data-v-35a9e36c]{box-sizing:initial}.banner .corner[data-v-35a9e36c]{padding:%?32?%}.banner .corner .banner-item-cover[data-v-35a9e36c]{box-sizing:initial;-webkit-appearance:none;-webkit-border-radius:%?16?%;-ms-border-radius:%?16?%;-o-border-radius:%?16?%;-moz-border-radius:%?16?%;border-radius:%?16?%;overflow:hidden}.banner .banner-item-image[data-v-35a9e36c]{width:100%;height:100%}.banner .banner-item-photo[data-v-35a9e36c]{position:relative;width:%?750?%;box-sizing:initial}",""]),t.exports=e},"829d":function(t,e,a){"use strict";var i;a.d(e,"b",(function(){return n})),a.d(e,"c",(function(){return o})),a.d(e,"a",(function(){return i}));var n=function(){var t=this,e=t.$createElement,a=t._self._c||e;return a("v-uni-view",{},[a("v-uni-view",{staticClass:"u-navbar",class:{"u-navbar-fixed":t.isFixed,"u-border-bottom":t.borderBottom},style:[t.navbarStyle]},[a("v-uni-view",{staticClass:"u-status-bar",style:{height:t.statusBarHeight+"px"}}),a("v-uni-view",{staticClass:"u-navbar-inner",style:[t.navbarInnerStyle]},[t.isBack?a("v-uni-view",{staticClass:"u-back-wrap",on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.goBack.apply(void 0,arguments)}}},[a("v-uni-view",{staticClass:"u-icon-wrap flex justify-center align-center"},[a("v-uni-text",{staticClass:"iconfont iconbtn_back"})],1),t.backText?a("v-uni-view",{staticClass:"u-icon-wrap u-back-text u-line-1",style:[t.backTextStyle]},[t._v(t._s(t.backText))]):t._e()],1):t._e(),t.title?a("v-uni-view",{staticClass:"u-navbar-content-title",style:[t.titleStyle]},[a("v-uni-view",{staticClass:"u-title u-line-1",style:{color:t.titleColor,fontSize:t.titleSize+"rpx",fontWeight:t.titleBold?"600":"normal"}},[t._v(t._s(t.title))])],1):t._e(),a("v-uni-view",{staticClass:"u-slot-content"},[t._t("default")],2),a("v-uni-view",{staticClass:"u-slot-right"},[t._t("right")],2)],1)],1)],1)},o=[]},"84ec":function(t,e,a){"use strict";var i=a("99ca").default;Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0,a("b5aa");var n=i(a("e9ff"));a("4cfc");var o={components:{},props:{title:{type:[String],default:"已完善个人信息,获得10积分"},value:{type:[String,Boolean],default:!1},top:{type:Number,default:0},index:{type:Number,default:0}},data:function(){return{time:1e4}},computed:{width:function(){return this.title.length>18?"75%":this.title.length>17?"70%":this.title.length>16?"65%":this.title.length>15?"60%":this.title.length>14?"65%":this.title.length>13?"55%":"50%"},display:{get:function(){var t=this;return this.value&&setTimeout((function(){t.display=!1}),this.time),this.value},set:function(t){this.$emit("input",t)}},topStyle:function(){var t=108*(this.index+1),e=this.top;return e?{top:"".concat(t+e,"rpx")}:{bottom:"".concat(t+120,"rpx")}}},created:function(){},watch:{display:function(t){}},mounted:function(){return(0,n.default)(regeneratorRuntime.mark((function t(){return regeneratorRuntime.wrap((function(t){while(1)switch(t.prev=t.next){case 0:case"end":return t.stop()}}),t)})))()},methods:{toclose:function(){this.display=!1},tolink:function(){uni.navigateTo({url:"/plugins/task/index"})}}};e.default=o},"857d":function(t,e,a){"use strict";a.r(e);var i=a("4f43"),n=a("1ab1");for(var o in n)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return n[t]}))}(o);a("f6e2");var r,s=a("5d80"),c=Object(s["a"])(n["default"],i["b"],i["c"],!1,null,"11869f80",null,!1,i["a"],r);e["default"]=c.exports},"85da":function(t,e,a){var i=a("94e7");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var n=a("5c0d").default;n("c1c4f0ea",i,!0,{sourceMap:!1,shadowMode:!1})},"85f9":function(t,e,a){"use strict";a.r(e);var i=a("a888"),n=a.n(i);for(var o in i)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return i[t]}))}(o);e["default"]=n.a},"87d3":function(t,e,a){var i=a("624a");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var n=a("5c0d").default;n("0f9b5c60",i,!0,{sourceMap:!1,shadowMode:!1})},"899d":function(t,e,a){"use strict";var i;a.d(e,"b",(function(){return n})),a.d(e,"c",(function(){return o})),a.d(e,"a",(function(){return i}));var n=function(){var t=this,e=t.$createElement,a=t._self._c||e;return t.display?a("div",{staticClass:"task-popups",class:{"task-popups-active":t.display},style:[t.topStyle],on:{click:function(e){e.stopPropagation(),arguments[0]=e=t.$handleEvent(e),t.tolink.apply(void 0,arguments)}}},[a("div",{staticClass:"task-popups__bg"}),a("div",{staticClass:"task-popups__icon"},[a("v-uni-text",{staticClass:"iconfont iconbtn_select"})],1),a("div",{staticClass:"task-popups__title"},[t._v(t._s(t.title))]),a("div",{staticClass:"task-popups__close",on:{click:function(e){e.stopPropagation(),arguments[0]=e=t.$handleEvent(e),t.toclose.apply(void 0,arguments)}}},[a("v-uni-text",{staticClass:"iconfont iconpopup_close"})],1),a("div",{staticClass:"task-popups__link",on:{click:function(e){e.stopPropagation(),arguments[0]=e=t.$handleEvent(e),t.tolink.apply(void 0,arguments)}}},[t._v("去领取"),a("v-uni-text",{staticClass:"iconfont iconbtn_arrow"})],1)]):t._e()},o=[]},"8b30":function(t,e,a){t.exports=a.p+"static/img/icon.b113a47e.png"},"8bb2":function(t,e,a){"use strict";a.r(e);var i=a("0b2f"),n=a("cbad");for(var o in n)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return n[t]}))}(o);a("9888");var r,s=a("5d80"),c=Object(s["a"])(n["default"],i["b"],i["c"],!1,null,"2ed3e676",null,!1,i["a"],r);e["default"]=c.exports},"8bec":function(t,e,a){"use strict";a.r(e);var i=a("84ec"),n=a.n(i);for(var o in i)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return i[t]}))}(o);e["default"]=n.a},"90c6":function(t,e,a){"use strict";var i=a("99ca").default;Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var n=i(a("5f35")),o={components:{item:n.default},props:{facade:{type:[Object,Array]},content:{type:[Object,Array]}},name:"notice"};e.default=o},9112:function(t,e,a){"use strict";a.r(e);var i=a("bd2b"),n=a("7100");for(var o in n)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return n[t]}))}(o);a("e9cd");var r,s=a("5d80"),c=Object(s["a"])(n["default"],i["b"],i["c"],!1,null,"3996b947",null,!1,i["a"],r);e["default"]=c.exports},"911a":function(t,e,a){"use strict";var i;a.d(e,"b",(function(){return n})),a.d(e,"c",(function(){return o})),a.d(e,"a",(function(){return i}));var n=function(){var t=this,e=t.$createElement,a=t._self._c||e;return a("he-popup",{attrs:{mode:"center","border-radius":16,zoom:!1,"background-color":"transparent"},model:{value:t.showModal,callback:function(e){t.showModal=e},expression:"showModal"}},[a("v-uni-view",{staticClass:"flex flex-direction align-center"},[a("v-uni-view",{staticClass:"box flex align-center flex-direction"},[a("v-uni-image",{staticClass:"image",attrs:{src:t.ipAddress+"/become-distributor.png"}}),a("v-uni-text",{staticClass:"text"},[t._v("恭喜,您已成为本商城的分销商! 一起推广赚钱吧!")]),a("v-uni-button",{staticClass:"cu-btn",on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.routerPromoter.apply(void 0,arguments)}}},[t._v("分销商中心")])],1),a("v-uni-view",{staticClass:"iconfont iconpopup_close2",on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.showModal=!1}}})],1)],1)},o=[]},9231:function(t,e,a){var i=a("8252");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var n=a("5c0d").default;n("753f8458",i,!0,{sourceMap:!1,shadowMode:!1})},"930f":function(t,e,a){var i=a("a1a8");e=i(!1),e.push([t.i,'@charset "UTF-8";\n/* start--主题色--start */\n/* end--主题色--end */.task-popups[data-v-41c96624]{position:fixed;z-index:1000;height:%?104?%;min-width:%?300?%;border-radius:0 %?52?% %?52?% 0;left:0;overflow:hidden}.task-popups .task-popups__bg[data-v-41c96624]{position:absolute;background:#000;opacity:.5;width:100%;height:100%;left:0;top:0;right:0;bottom:0;z-index:1000}.task-popups__link[data-v-41c96624]{font-size:%?24?%;font-family:PingFang SC;font-weight:400;color:#fff;line-height:%?36?%;position:absolute;z-index:10002;bottom:%?12?%;left:%?91?%}.task-popups__link .iconfont[data-v-41c96624]{font-size:%?22?%}.task-popups__title[data-v-41c96624]{position:relative;z-index:10002;min-width:50%;max-width:80%;margin-right:%?84?%;margin-top:%?22?%;margin-left:%?91?%;font-size:%?24?%;font-family:PingFang SC;font-weight:400;color:#fff;line-height:%?36?%;overflow:hidden;white-space:nowrap;text-overflow:ellipsis}.task-popups__icon[data-v-41c96624]{width:%?48?%;height:%?48?%;background:#53c41a;border-radius:50%;position:absolute;z-index:10002;text-align:center;line-height:%?48?%;left:%?28?%;top:%?28?%}.task-popups__icon .iconbtn_select[data-v-41c96624]{font-size:%?32?%;color:#fff;line-height:%?48?%}.task-popups__close[data-v-41c96624]{width:%?24?%;height:%?24?%;position:absolute;z-index:10002;text-align:center;line-height:%?24?%;right:%?40?%;top:%?40?%}.task-popups__close .iconfont[data-v-41c96624]{font-size:%?24?%;color:#fff;line-height:%?24?%}.task-popups-active[data-v-41c96624]{animation:bounceInLeft-data-v-41c96624 2s cubic-bezier(.215,.61,.355,1) 0s 1 alternate forwards;-webkit-animation:bounceInLeft-data-v-41c96624 2s cubic-bezier(.215,.61,.355,1) 0s 1 alternate forwards}@-webkit-keyframes bounceInLeft-data-v-41c96624{0%{opacity:0;-webkit-transform:translate3d(%?-3000?%,0,0);transform:translate3d(%?-3000?%,0,0)}100%{opacity:1;-webkit-transform:none;transform:none}}@keyframes bounceInLeft-data-v-41c96624{0%{opacity:0;-webkit-transform:translate3d(%?-3000?%,0,0);transform:translate3d(%?-3000?%,0,0)}100%{opacity:1;-webkit-transform:none;transform:none}}',""]),t.exports=e},"94e7":function(t,e,a){var i=a("a1a8");e=i(!1),e.push([t.i,'@charset "UTF-8";\n/* start--主题色--start */\n/* end--主题色--end */.le-popup[data-v-f78c898c]{width:100%;height:100%}.he-box[data-v-f78c898c]{width:%?660?%;height:%?804?%;margin:10vh auto 0 auto;position:relative}.he-box__close[data-v-f78c898c]{width:%?52?%;height:%?52?%;border:%?2?% solid #fff;border-radius:50%;position:absolute;right:0;top:%?-84?%}.iconpopup_close[data-v-f78c898c]{font-size:%?20?%;color:#fff}.le-box-image[data-v-f78c898c]{height:%?252?%;width:100%;display:block}.le-content[data-v-f78c898c]{width:%?630?%;margin:0 auto;background:#e44;border-radius:0 0 %?16?% %?16?%;padding:%?32?% %?32?% 0 %?32?%}.le-content .le-body[data-v-f78c898c]{min-height:%?160?%;max-height:%?440?%}.le-content .he-item[data-v-f78c898c]{height:%?160?%;margin-bottom:%?16?%}.le-content .he-left[data-v-f78c898c]{width:%?217?%;height:100%;background:#fff;border-top-left-radius:%?16?%;border-bottom-left-radius:%?16?%;padding-left:%?17?%;text-align:center}.le-content .he-left .le-price[data-v-f78c898c]{font-size:%?66?%;font-family:PingFang SC;font-weight:700;color:#e60b30;line-height:%?52?%;margin-top:%?37?%}.le-content .he-left .le-price[data-v-f78c898c]::before{content:"¥";font-size:%?24?%;font-weight:500}.le-content .he-left .le-limit[data-v-f78c898c]{font-size:%?24?%;font-family:PingFang SC;font-weight:500;color:#e60b30;line-height:%?36?%}.le-content .he-center[data-v-f78c898c]{width:%?16?%;height:100%;position:relative;background-color:#fff}.le-content .he-center .he-dot[data-v-f78c898c]{position:absolute;width:%?16?%;height:%?16?%;border-radius:50%;background-color:#e44}.le-content .he-center .he-dot[data-v-f78c898c]:first-child{top:0;-webkit-transform:translateY(-50%);transform:translateY(-50%)}.le-content .he-center .he-dot[data-v-f78c898c]:last-child{bottom:0;-webkit-transform:translateY(50%);transform:translateY(50%)}.le-content .he-center .he-line[data-v-f78c898c]{width:%?2?%;height:96%;position:absolute;top:50%;left:50%;-webkit-transform:translate(-50%,-50%);transform:translate(-50%,-50%);background-position:50%;background-size:%?2?% %?14?%;background-repeat:repeat-y;background-image:-webkit-linear-gradient(bottom,#e44,#e44 50%,transparent 0);background-image:linear-gradient(0deg,#e44 0,#e44 50%,transparent 0)}.le-content .le-right[data-v-f78c898c]{height:100%;background:#fff;border-top-right-radius:%?16?%;border-bottom-right-radius:%?16?%;padding-left:%?32?%;font-weight:500;font-family:PingFang SC}.le-content .le-right .le-name[data-v-f78c898c]{font-size:%?30?%;font-family:PingFang SC;font-weight:500;color:#222;line-height:%?40?%;margin-top:%?43?%}.le-content .le-right .le-desc[data-v-f78c898c]{font-size:%?22?%;font-family:PingFang SC;font-weight:500;color:#999;line-height:%?28?%;margin-top:%?5?%}.le-content .le-footer[data-v-f78c898c]{height:%?80?%;line-height:%?80?%;font-size:%?22?%;font-family:PingFang SC;font-weight:500;color:#fefefe;text-align:center}',""]),t.exports=e},9570:function(t,e,a){"use strict";a.r(e);var i=a("73e4"),n=a.n(i);for(var o in i)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return i[t]}))}(o);e["default"]=n.a},"96ca":function(t,e,a){var i=a("9d60");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var n=a("5c0d").default;n("306a4d09",i,!0,{sourceMap:!1,shadowMode:!1})},9888:function(t,e,a){"use strict";var i=a("96ca"),n=a.n(i);n.a},9990:function(t,e,a){"use strict";a.r(e);var i=a("6b60"),n=a("64f7");for(var o in n)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return n[t]}))}(o);var r,s=a("5d80"),c=Object(s["a"])(n["default"],i["b"],i["c"],!1,null,null,null,!1,i["a"],r);e["default"]=c.exports},"99a5":function(t,e,a){"use strict";a.r(e);var i=a("3f8d"),n=a.n(i);for(var o in i)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return i[t]}))}(o);e["default"]=n.a},"9a46":function(t,e,a){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0,a("2c7c"),a("4cfc");var i={props:{facade:{type:[Object,Array]},content:{type:[Object,Array]},item:{type:Object}},data:function(){return{list:[]}},computed:{newData:function(){if(0===this.content.data.length){var t={expire_type:2,appoint_type:1,name:"优惠券名称",sub_price:88,can_obtain:!0},e=[t,t,t];return 2===this.facade.list_style&&e.push(t),e}return this.content.data},couponItem:function(){var t="";return 3===this.content.style&&(t+=" fillet "),t},rightClass:function(){return 1===this.facade.list_style?"flex ":2===this.facade.list_style||3===this.facade.list_style?"":void 0},itemStyle:function(){var t=this;return function(e){var a={backgroundColor:t.facade.background_color};return e.can_obtain||(a.backgroundColor="#F5F5F5"),1===t.facade.list_style?a.width="710rpx":2===t.facade.list_style?a.width="349rpx":3===t.facade.list_style&&(a.width="280rpx"),a}},textStyle:function(){var t=this;return function(e){var a={color:t.facade.title_color};return e.can_obtain||(a.color="#666666"),a}},borderStyle:function(){var t=this;return function(e){var a={borderColor:t.facade.title_color};return e.can_obtain||(a.borderColor="#666666"),a}},leftStyle:function(){var t=this;return function(e){var a="1px solid "+t.facade.title_color,i={};return 1===t.content.style&&(e.can_obtain||(a="1px solid #666666"),i={borderTop:a,borderBottom:a,borderLeft:a}),1===t.facade.list_style?i.width="200rpx":2===t.facade.list_style?i.width="238rpx":3===t.facade.list_style&&(i.width="170rpx"),i}},rightStyle:function(){var t=this;return function(e){var a="1px solid "+t.facade.title_color,i={};return 1===t.content.style&&(e.can_obtain||(a="1px solid #666666"),i={borderTop:a,borderBottom:a,borderRight:a}),1===t.facade.list_style?i.width="460rpx":(2===t.facade.list_style||3===t.facade.list_style)&&(i.width="64rpx"),i}},priceStyle:function(){var t={};return 1===this.facade.list_style?(t.lineHeight="52rpx",t.marginTop="25rpx",t.fontSize="50rpx"):(2===this.facade.list_style||3===this.facade.list_style)&&(t.lineHeight="44rpx",t.marginTop="16rpx",t.fontSize="44rpx"),t},minStyle:function(){var t={};return 1===this.facade.list_style?(t.lineHeight="16rpx",t.fontSize="24rpx"):(2===this.facade.list_style||3===this.facade.list_style)&&(t.lineHeight="28rpx",t.fontSize="20rpx"),t},couponBtn:function(){var t={};return 1===this.facade.list_style?(t.width="126rpx",t.height="126rpx",t.lineHeight="126rpx"):(2===this.facade.list_style||3===this.facade.list_style)&&(t.writingMode="vertical-rl",t.height="126rpx",t.lineHeight="60rpx",t.width="60rpx"),t},appointStyle:function(){var t={};return 1===this.facade.list_style||(2===this.facade.list_style||3===this.facade.list_style)&&(t.textAlign="center"),t},lineColor:function(){return{backgroundImage:"repeating-linear-gradient(180deg, ".concat(this.facade.title_color,", ").concat(this.facade.title_color," 4rpx, transparent 0, transparent 8rpx)")}}},filters:{setNumber:function(t){return Number(t)}}};e.default=i},"9af3":function(t,e,a){"use strict";var i=a("a92f"),n=a.n(i);n.a},"9bf6":function(t,e,a){"use strict";a.r(e);var i=a("ed0a"),n=a("c72c");for(var o in n)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return n[t]}))}(o);a("db44");var r,s=a("5d80"),c=Object(s["a"])(n["default"],i["b"],i["c"],!1,null,"03826ed1",null,!1,i["a"],r);e["default"]=c.exports},"9c91":function(t,e,a){"use strict";var i;a.d(e,"b",(function(){return n})),a.d(e,"c",(function(){return o})),a.d(e,"a",(function(){return i}));var n=function(){var t=this,e=t.$createElement,a=t._self._c||e;return a("he-cart",{attrs:{show:t.isShopping,goods:t.goods,is_task:t.is_task},on:{"update:show":function(e){arguments[0]=e=t.$handleEvent(e),t.isShopping=e}}})},o=[]},"9d37":function(t,e,a){"use strict";var i=a("99ca").default;Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0,a("b5aa");var n=i(a("e9ff")),o={props:{facade:{type:[Object,Array]},content:{type:[Object,Array]}},data:function(){return{}},computed:{},created:function(){},watch:{},mounted:function(){var t=this;return(0,n.default)(regeneratorRuntime.mark((function e(){var a;return regeneratorRuntime.wrap((function(e){while(1)switch(e.prev=e.next){case 0:a=t,setTimeout((function(){a.$store.dispatch("components/getSearch")}),1500);case 2:case"end":return e.stop()}}),e)})))()},methods:{navigateToDetail:function(){uni.navigateTo({url:"/pages/goods/search"})}}};e.default=o},"9d60":function(t,e,a){var i=a("a1a8");e=i(!1),e.push([t.i,'@charset "UTF-8";\n/* start--主题色--start */\n/* end--主题色--end */.he-login-box[data-v-2ed3e676]{padding:%?80?% %?87?% %?51?% %?87?%;height:100%}.he-login-box .title[data-v-2ed3e676]{font-size:%?32?%;font-family:PingFang SC;font-weight:500;color:#222;line-height:%?32?%;margin-top:%?64?%;margin-bottom:%?24?%}.he-login-box .login-bg[data-v-2ed3e676]{width:%?416?%;height:%?280?%}.he-login-box .cu-btn[data-v-2ed3e676]{width:%?420?%;height:%?80?%;border-radius:%?40?%;margin-top:%?40?%;font-size:%?30?%;font-family:PingFang SC;font-weight:500;color:#fff;margin-bottom:%?43?%}[data-theme="red_theme"] .he-login-box .cu-btn[data-v-2ed3e676]{background-color:#e60b30!important}[data-theme="purple_theme"] .he-login-box .cu-btn[data-v-2ed3e676]{background-color:#8f2df3!important}[data-theme="blue_theme"] .he-login-box .cu-btn[data-v-2ed3e676]{background-color:#33a7ff!important}[data-theme="green_theme"] .he-login-box .cu-btn[data-v-2ed3e676]{background-color:#1fc551!important}[data-theme="orange_theme"] .he-login-box .cu-btn[data-v-2ed3e676]{background-color:#ff7f00!important}[data-theme="golden_theme"] .he-login-box .cu-btn[data-v-2ed3e676]{background-color:#caa45a!important}.he-login-box .assist-text[data-v-2ed3e676]{font-size:%?26?%;font-family:PingFang SC;font-weight:500;color:#999;line-height:%?26?%}',""]),t.exports=e},"9f90":function(t,e,a){var i=a("a1a8");e=i(!1),e.push([t.i,'@charset "UTF-8";\n/* start--主题色--start */\n/* end--主题色--end */.u-navbar[data-v-61c50dd2]{width:100%}.u-navbar-fixed[data-v-61c50dd2]{position:fixed;left:0;right:0;top:0;z-index:991}.u-status-bar[data-v-61c50dd2]{width:100%}.u-navbar-inner[data-v-61c50dd2]{display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-pack:justify;-webkit-justify-content:space-between;justify-content:space-between;position:relative;-webkit-box-align:center;-webkit-align-items:center;align-items:center}.u-back-wrap[data-v-61c50dd2]{display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-align:center;-webkit-align-items:center;align-items:center;-webkit-box-flex:1;-webkit-flex:1;flex:1;-webkit-box-flex:0;-webkit-flex-grow:0;flex-grow:0;padding:%?14?% %?14?% %?14?% %?24?%}.u-back-text[data-v-61c50dd2]{padding-left:%?4?%;font-size:%?30?%}.u-navbar-content-title[data-v-61c50dd2]{display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-align:center;-webkit-align-items:center;align-items:center;-webkit-box-pack:center;-webkit-justify-content:center;justify-content:center;-webkit-box-flex:1;-webkit-flex:1;flex:1;position:absolute;left:0;right:0;height:%?60?%;text-align:center;-webkit-flex-shrink:0;flex-shrink:0}.u-navbar-centent-slot[data-v-61c50dd2]{-webkit-box-flex:1;-webkit-flex:1;flex:1}.u-title[data-v-61c50dd2]{line-height:%?60?%;font-size:%?32?%;-webkit-box-flex:1;-webkit-flex:1;flex:1}.u-navbar-right[data-v-61c50dd2]{-webkit-box-flex:1;-webkit-flex:1;flex:1;display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-align:center;-webkit-align-items:center;align-items:center;-webkit-box-pack:end;-webkit-justify-content:flex-end;justify-content:flex-end}.u-slot-content[data-v-61c50dd2]{-webkit-box-flex:1;-webkit-flex:1;flex:1;display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-align:center;-webkit-align-items:center;align-items:center}.u-icon-wrap[data-v-61c50dd2]{width:%?64?%;height:%?64?%;background:hsla(0,0%,100%,.5);border-radius:50%}.iconbtn_back[data-v-61c50dd2]{color:#191919;font-size:%?40?%}',""]),t.exports=e},a0ae:function(t,e,a){"use strict";a.r(e);var i=a("779c"),n=a("305b");for(var o in n)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return n[t]}))}(o);a("0d7c");var r,s=a("5d80"),c=Object(s["a"])(n["default"],i["b"],i["c"],!1,null,"885244ce",null,!1,i["a"],r);e["default"]=c.exports},a35f:function(t,e,a){"use strict";a.r(e);var i=a("5b2a"),n=a.n(i);for(var o in i)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return i[t]}))}(o);e["default"]=n.a},a4fa:function(t,e,a){"use strict";var i=a("17e4"),n=a.n(i);n.a},a5c4:function(t,e,a){var i=a("9f90");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var n=a("5c0d").default;n("1ed1db90",i,!0,{sourceMap:!1,shadowMode:!1})},a73f:function(t,e,a){"use strict";a.r(e);var i=a("401a"),n=a.n(i);for(var o in i)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return i[t]}))}(o);e["default"]=n.a},a888:function(t,e,a){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0,a("4cfc");var i={props:{current:{type:[String,Number,Boolean],default:1},number:{type:[String,Number,Boolean],default:""},margin:{type:[Number],default:8},type:{type:[String,Number,Boolean],default:1},align:{type:[String,Number,Boolean],default:"left"},color:{type:[String,Number,Boolean],default:"#f44"}},methods:{activeColor:function(t){return this.current==t?this.color:"rgba(0,0,0,.3)"}}};e.default=i},a8fb:function(t,e,a){var i=a("a1a8");e=i(!1),e.push([t.i,".rubik[data-v-0e77ce96]{overflow:hidden;position:relative}.rubik-cube[data-v-0e77ce96]{position:relative;width:%?750?%;height:%?750?%;font-size:%?28?%}.rubik-cube .rubik-cube__item[data-v-0e77ce96]{position:absolute}.advertising[data-v-0e77ce96]{-webkit-touch-callout:none;-webkit-user-select:none;-khtml-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;font-size:%?12?%;margin-bottom:%?-4?%}.advertising .advertising-item-1[data-v-0e77ce96]{position:relative;text-align:center;font-weight:400;color:#8c8c8c;width:%?750?%;margin-bottom:%?-2?%}.advertising .advertising-item-1 .advertising-item-tips[data-v-0e77ce96]{width:%?750?%;height:%?750?%;line-height:%?750?%;background:#f7f5fe}.advertising .advertising-item-1 img[data-v-0e77ce96]{width:100%;height:auto}.advertising .advertising-item-2[data-v-0e77ce96]{position:relative;width:100%;display:-webkit-box;display:-webkit-flex;display:flex}.advertising .advertising-item-2 .advertising-item-image[data-v-0e77ce96]{margin-bottom:%?-2?%;-webkit-box-flex:1;-webkit-flex:1 1 auto;flex:1 1 auto;width:%?375?%}.advertising .advertising-item-2 .advertising-item-image:first-child .advertising-item-tips[data-v-0e77ce96]{border-right:0}.advertising .advertising-item-2 .advertising-item-image img[data-v-0e77ce96]{width:100%;height:auto}.advertising .advertising-item-3[data-v-0e77ce96]{position:relative;width:100%;display:-webkit-box;display:-webkit-flex;display:flex}.advertising .advertising-item-3 .advertising-item-image[data-v-0e77ce96]{margin-bottom:%?-2?%;-webkit-box-flex:1;-webkit-flex:1 1 1;flex:1 1 1;width:%?250?%}.advertising .advertising-item-3 .advertising-item-image img[data-v-0e77ce96]{width:100%;height:auto}.advertising .advertising-item-4[data-v-0e77ce96]{position:relative;width:%?750?%;height:%?375?%}.advertising .advertising-item-4 .advertising-item-image[data-v-0e77ce96]{margin-bottom:%?-2?%;position:absolute;width:100%;height:100%}.advertising .advertising-item-4 .advertising-item-image img[data-v-0e77ce96]{width:100%;height:100%}.advertising .advertising-item-5[data-v-0e77ce96]{position:relative;width:100%;display:-webkit-box;display:-webkit-flex;display:flex}.advertising .advertising-item-5 .advertising-item-image[data-v-0e77ce96]{margin-bottom:%?-2?%;margin-right:%?-2?%;-webkit-box-flex:1;-webkit-flex:1;flex:1;width:%?187.5?%}.advertising .advertising-item-5 .advertising-item-image img[data-v-0e77ce96]{width:100%;height:auto}.advertising .advertising-item-6[data-v-0e77ce96]{position:relative;width:100%;height:%?376?%}.advertising .advertising-item-6 .advertising-item-image[data-v-0e77ce96]{margin-bottom:%?-2?%;position:absolute}",""]),t.exports=e},a92f:function(t,e,a){var i=a("e3e7");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var n=a("5c0d").default;n("ed55be5a",i,!0,{sourceMap:!1,shadowMode:!1})},ac5d:function(t,e,a){var i=a("fc3d");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var n=a("5c0d").default;n("fd069908",i,!0,{sourceMap:!1,shadowMode:!1})},ae01:function(t,e,a){"use strict";a.r(e);var i=a("ce8c"),n=a("5815");for(var o in n)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return n[t]}))}(o);a("e721");var r,s=a("5d80"),c=Object(s["a"])(n["default"],i["b"],i["c"],!1,null,"35a9e36c",null,!1,i["a"],r);e["default"]=c.exports},aebf:function(t,e,a){"use strict";var i=a("a5c4"),n=a.n(i);n.a},b342:function(t,e,a){var i=a("642e");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var n=a("5c0d").default;n("19652508",i,!0,{sourceMap:!1,shadowMode:!1})},b43a:function(t,e,a){"use strict";a.r(e);var i=a("57e7"),n=a("a73f");for(var o in n)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return n[t]}))}(o);a("d06e");var r,s=a("5d80"),c=Object(s["a"])(n["default"],i["b"],i["c"],!1,null,"b8ff14b4",null,!1,i["a"],r);e["default"]=c.exports},b4cc:function(t,e,a){"use strict";var i=a("5f42"),n=a.n(i);n.a},bd2b:function(t,e,a){"use strict";var i;a.d(e,"b",(function(){return n})),a.d(e,"c",(function(){return o})),a.d(e,"a",(function(){return i}));var n=function(){var t=this,e=t.$createElement,i=t._self._c||e;return t.display?i("v-uni-view",{staticClass:"wrap"},[i("v-uni-view",{staticClass:"wrap-box"},[i("v-uni-view",{staticClass:"close",on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.toclose.apply(void 0,arguments)}}},[i("v-uni-text",{staticClass:"iconfont iconpopup_close2"})],1),i("v-uni-view",{staticClass:"icon"},[i("v-uni-view",{staticClass:"bg"},[i("img",{attrs:{src:a("e547"),alt:""}})]),i("v-uni-view",{staticClass:"gold"},[i("img",{attrs:{src:a("8b30"),alt:""}})])],1),i("v-uni-view",{staticClass:"text"},[i("v-uni-view",{staticClass:"score"},[t._v("+"+t._s(t.score)+"积分")]),i("v-uni-view",{staticClass:"tip"})],1)],1)],1):t._e()},o=[]},bdad:function(t,e,a){"use strict";a.r(e);var i=a("d1b7"),n=a.n(i);for(var o in i)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return i[t]}))}(o);e["default"]=n.a},c172:function(t,e,a){"use strict";a.r(e);var i=a("2462"),n=a.n(i);for(var o in i)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return i[t]}))}(o);e["default"]=n.a},c441:function(t,e,a){var i=a("a1a8");e=i(!1),e.push([t.i,'.title[data-v-248b002e]{background:#fff}.title .title-style1[data-v-248b002e],\n.title .title-style2[data-v-248b002e],\n.title .title-style3[data-v-248b002e]{width:100%;padding:0 %?32?%;box-sizing:border-box;position:relative}.title .title-style3 .title-content[data-v-248b002e]{font-size:%?32?%;font-weight:500;color:#333}.title .title-style3 .title-more[data-v-248b002e]{position:absolute;font-size:%?28?%;font-weight:400;color:#333;right:%?16?%;top:0;height:100%;line-height:100%;display:-webkit-box;display:-webkit-flex;display:flex;-webkit-box-align:center;-webkit-align-items:center;align-items:center;-webkit-box-pack:center;-webkit-justify-content:center;justify-content:center}.title .title-style3 .title-subtitle[data-v-248b002e]{margin-top:%?8?%;font-size:%?24?%;height:%?40?%;font-weight:400;color:#333}.title .title-style1[data-v-248b002e]{text-align:center}.title .title-style1 .title-content-before[data-v-248b002e]{display:inline-block;content:"";width:20%;height:%?10?%;border-top:%?2?% solid #898989;margin-right:%?20?%}.title .title-style1 .title-content-after[data-v-248b002e]{display:inline-block;content:"";width:20%;height:%?10?%;border-top:%?2?% solid #898989;margin-left:%?20?%}.title .title-style2[data-v-248b002e]{width:85%;box-sizing:border-box;text-align:center;line-height:%?40?%;position:relative;margin:0 auto}.title .title-style2 .title-content[data-v-248b002e]{font-weight:400}.title .title-style2 .title-decorate-before[data-v-248b002e]{position:absolute;content:"";width:45%;border-bottom:%?2?% solid #898989;right:0;top:%?60?%}.title .title-style2 .title-decorate-after[data-v-248b002e]{position:absolute;content:"";width:45%;border-bottom:%?2?% solid #898989;left:0;top:%?60?%}',""]),t.exports=e},c4ba:function(t,e,a){var i=a("708d");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var n=a("5c0d").default;n("1ca24837",i,!0,{sourceMap:!1,shadowMode:!1})},c723:function(t,e,a){"use strict";var i=a("c4ba"),n=a.n(i);n.a},c72c:function(t,e,a){"use strict";a.r(e);var i=a("4411"),n=a.n(i);for(var o in i)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return i[t]}))}(o);e["default"]=n.a},cbad:function(t,e,a){"use strict";a.r(e);var i=a("3f31"),n=a.n(i);for(var o in i)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return i[t]}))}(o);e["default"]=n.a},cd93:function(t,e,a){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i={props:{facade:{type:[Object,Array]},content:{type:[Object,Array]}},computed:{margin:function(){return 1==this.facade.chamfer_style?0:10}}};e.default=i},ce8c:function(t,e,a){"use strict";var i;a.d(e,"b",(function(){return n})),a.d(e,"c",(function(){return o})),a.d(e,"a",(function(){return i}));var n=function(){var t=this,e=t.$createElement,a=t._self._c||e;return a("v-uni-view",{staticClass:"banner"},[a("v-uni-view",{staticClass:"banner-item-photo",style:{width:"100%",height:t.height}},[a("v-uni-swiper",{staticClass:"banner-item-image",class:{corner:2==t.facade.chamfer_style},attrs:{circular:t.circular,autoplay:t.autoplay},on:{change:function(e){arguments[0]=e=t.$handleEvent(e),t.handleChange.apply(void 0,arguments)}}},t._l(t.contentData,(function(e,i){return a("v-uni-swiper-item",{key:i,staticClass:"banner-item-cover"},[11===e.link.index?[a("he-open-launch-weapp",{staticStyle:{height:"100%"},attrs:{username:e.link.param.wechat.appId,path:e.link.param.wechat.path}},[a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{"lazy-load":!0,src:e.url,mode:"aspectFill"}})],1)]:[a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{"lazy-load":!0,src:e.url,mode:"aspectFill"},on:{click:function(a){arguments[0]=a=t.$handleEvent(a),t.navigateToDetail(e.link)}}})]],2)})),1),a("pointer",{attrs:{current:t.current,number:t.contentData.length,margin:t.margin,color:t.facade.indicator_color,type:t.facade.indicator_style,align:t.facade.indicator_align}})],1)],1)},o=[]},cf78:function(t,e,a){"use strict";var i;a.d(e,"b",(function(){return n})),a.d(e,"c",(function(){return o})),a.d(e,"a",(function(){return i}));var n=function(){var t=this,e=t.$createElement,a=t._self._c||e;return t.show?a("v-uni-view",{staticClass:"uni-noticebar",style:{backgroundColor:t.backgroundColor},on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.onClick.apply(void 0,arguments)}}},[!0===t.showIcon||"true"===t.showIcon?a("v-uni-view",{staticClass:"uni-noticebar-icon"},[a("v-uni-image",{attrs:{src:t.iconUrl}})],1):t._e(),a("v-uni-view",{ref:"textBox",staticClass:"uni-noticebar__content-wrapper",class:{"uni-noticebar__content-wrapper--scrollable":t.scrollable,"uni-noticebar__content-wrapper--single":!t.scrollable&&(t.single||t.moreText)}},[a("v-uni-view",{staticClass:"uni-noticebar__content",class:{"uni-noticebar__content--scrollable":t.scrollable,"uni-noticebar__content--single":!t.scrollable&&(t.single||t.moreText)},attrs:{id:t.elIdBox}},[a("v-uni-text",{ref:"animationEle",staticClass:"uni-noticebar__content-text",class:{"uni-noticebar__content-text--scrollable":t.scrollable,"uni-noticebar__content-text--single":!t.scrollable&&(t.single||t.moreText)},style:{color:t.color,width:t.wrapWidth+"px",animationDuration:t.animationDuration,"-webkit-animationDuration":t.animationDuration,animationPlayState:t.webviewHide?"paused":t.animationPlayState,"-webkit-animationPlayState":t.webviewHide?"paused":t.animationPlayState,animationDelay:t.animationDelay,"-webkit-animationDelay":t.animationDelay},attrs:{id:t.elId}},[t._v(t._s(t.text))])],1)],1),!0===t.showGetMore||"true"===t.showGetMore?a("v-uni-view",{staticClass:"uni-noticebar__more uni-cursor-point",on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.clickMore.apply(void 0,arguments)}}},[t.moreText?a("v-uni-text",{staticClass:"uni-noticebar__more-text",style:{color:t.moreColor}},[t._v(t._s(t.moreText))]):t._e()],1):t._e()],1):t._e()},o=[]},cffc:function(t,e,a){"use strict";var i;a.d(e,"b",(function(){return n})),a.d(e,"c",(function(){return o})),a.d(e,"a",(function(){return i}));var n=function(){var t=this,e=t.$createElement,a=t._self._c||e;return a("v-uni-view",{staticClass:"title",style:{"padding-top":t.facade.margin+"px","padding-bottom":t.facade.margin+"px","background-color":t.facade.background_color}},[1==t.content.style?a("v-uni-view",{staticClass:"title-style1",style:{color:t.facade.title_color}},[a("v-uni-view",{staticClass:"title-content",on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.navigateToDetail(t.content.morelink)}}},[a("v-uni-view",{staticClass:"title-content-before",style:{borderTop:"2rpx solid "+t.facade.title_color}}),t._v(t._s(t.content.title)),a("v-uni-view",{staticClass:"title-content-after",style:{borderTop:"2rpx solid "+t.facade.title_color}})],1)],1):t._e(),2==t.content.style?a("v-uni-view",{staticClass:"title-style2",style:{color:t.facade.title_color}},[a("v-uni-view",{staticClass:"title-content",on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.navigateToDetail(t.content.morelink)}}},[t._v(t._s(t.content.title))]),a("v-uni-view",{staticClass:"title-decorate"},[a("v-uni-view",{staticClass:"title-decorate-before",style:{borderBottom:"2rpx solid "+t.facade.title_color}}),t._v("◇"),a("v-uni-view",{staticClass:"title-decorate-after",style:{borderBottom:"2rpx solid "+t.facade.title_color}})],1)],1):t._e(),3==t.content.style?a("v-uni-view",{staticClass:"title-style3"},[a("v-uni-view",{staticClass:"title-content",style:{color:t.facade.title_color,"font-size":t.facade.title_font_size+"px"}},[t._v(t._s(t.content.title))]),t.content.is_more?a("v-uni-view",{staticClass:"title-more",style:{color:t.facade.more_color},on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.navigateToDetail(t.content.morelink)}}},[t._v(t._s(t.content.moretitle)),a("v-uni-text",{staticClass:"iconfont iconbtn_arrow",staticStyle:{"font-size":"27rpx"}})],1):t._e(),a("v-uni-view",{staticClass:"title-subtitle",style:{color:t.facade.subtitle_color,"font-size":t.facade.subtitle_font_size+"px"}},[t._v(t._s(t.content.subtitle))])],1):t._e()],1)},o=[]},d06e:function(t,e,a){"use strict";var i=a("04a7"),n=a.n(i);n.a},d0b7:function(t,e,a){var i=a("930f");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var n=a("5c0d").default;n("358520cf",i,!0,{sourceMap:!1,shadowMode:!1})},d1b7:function(t,e,a){"use strict";var i=a("99ca").default;Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0,a("5c5d"),a("b5aa");var n=i(a("e9ff")),o=i(a("639e")),r=i(a("11226")),s={components:{pointer:o.default,heOpenLaunchWeapp:r.default},props:{facade:{type:[Object,Array]},content:{type:[Object,Array]}},data:function(){return{margin:10,current:0,navigateList:[],navigation:[{id:1,title:"商品名称",url:"",link:{}}]}},computed:{number:function(){var t=this.facade.nav_line*this.facade.nav_line_mun;return Math.ceil(this.content.data.length/t)},width:function(){return 1!=this.facade.nav_style?100/this.facade.nav_line_mun+"%":1==this.content.style?this.navigation.length>5?"24%":100/this.navigation.length+"%":2==this.content.style?this.navigation.length>4?"30%":100/this.navigation.length+"%":void 0},swiperHeight:function(){var t=32;1==this.content.style&&(t=88);var e=this.facade.nav_line*t;return this.number>1?e+32+"px":e+5+"px"}},watch:{content:{deep:!0,handler:function(){this.handleCheck()}},facade:{deep:!0,handler:function(){this.handleCheck()}}},mounted:function(){var t=this;return(0,n.default)(regeneratorRuntime.mark((function e(){return regeneratorRuntime.wrap((function(e){while(1)switch(e.prev=e.next){case 0:t.handleCheck();case 1:case"end":return e.stop()}}),e)})))()},methods:{onCurrent:function(t){t.detail&&(this.current=t.detail.current)},getNavigateList:function(t){var e=this.facade.nav_line*this.facade.nav_line_mun,a=t*e,i=(t+1)*e,n=this.content.data.slice(a,i);return JSON.parse(JSON.stringify(n))},getNavigateToDetail:function(t,e){var a=this.getNavigateList(t),i=a[e];this.navigateToDetail(i.link||{})},navigateToDetail:function(t){this.$h.MPageNavigate(t)},handleCheck:function(){if(this.content.data.length>0&&(this.navigation=this.content.data),2==this.facade.nav_style){var t=this.content.data,e=this.facade.nav_line*this.facade.nav_line_mun;this.navigation=t.slice(0,e)}},getCover:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";return t||"https://img.yzcdn.cn/upload_files/2018/01/22/FnlHRufXMtUI_AbAEP0tux_nDL1T.png!large.webp"}}};e.default=s},d2d6:function(t,e,a){"use strict";a.r(e);var i=a("829d"),n=a("fb50");for(var o in n)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return n[t]}))}(o);a("aebf");var r,s=a("5d80"),c=Object(s["a"])(n["default"],i["b"],i["c"],!1,null,"61c50dd2",null,!1,i["a"],r);e["default"]=c.exports},d3f9:function(t,e,a){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0,a("4cfc");var i={props:{value:{type:[Number,Boolean],default:0},score:{type:[String,Number],default:"10"},title:{type:[String,Number],default:"领取成功"}},watch:{},computed:{display:{get:function(){return this.value},set:function(){this.$emit("input",0)}}},mounted:function(){},methods:{toclose:function(){this.display=!1}}};e.default=i},d545:function(t,e,a){"use strict";a.r(e);var i=a("42cb"),n=a("6ce5");for(var o in n)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return n[t]}))}(o);a("9af3");var r,s=a("5d80"),c=Object(s["a"])(n["default"],i["b"],i["c"],!1,null,"3d40fb81",null,!1,i["a"],r);e["default"]=c.exports},d8ae:function(t,e,a){"use strict";a.r(e);var i=a("90c6"),n=a.n(i);for(var o in i)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return i[t]}))}(o);e["default"]=n.a},db44:function(t,e,a){"use strict";var i=a("03ab"),n=a.n(i);n.a},db8e:function(t,e,a){"use strict";var i;a.d(e,"b",(function(){return n})),a.d(e,"c",(function(){return o})),a.d(e,"a",(function(){return i}));var n=function(){var t=this,e=t.$createElement,a=t._self._c||e;return a("v-uni-view",{staticClass:"showcase-video"},[a("v-uni-view",{staticClass:"video-container video-container--visible",staticStyle:{height:"420rpx"}},[a("v-uni-video",{staticClass:"video-container--box",attrs:{poster:t.content.cover,autoplay:t.content.autoplay,loop:t.content.loop,src:t.content.video.url}})],1)],1)},o=[]},dcf8:function(t,e,a){"use strict";var i=a("99ca").default;Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0,a("b5aa");var n=i(a("e9ff"));a("c342"),a("3728"),a("ae75"),a("f9ee"),a("7423"),a("211d");var o=i(a("07dd"));var r={props:{facade:{type:[Object,Array]},content:{type:[Object,Array]}},components:{heIndexCart:o.default},data:function(){return{is_show:!0,goods:[],goodsData:[],goodsId:null}},computed:{getIconUrl:function(){return this.content.icon?this.content.icon:this.content.task.icon?this.content.task.icon:"http://qmxq.oss-cn-hangzhou.aliyuncs.com/task/task-sign-icon.png"},mode:function(){return 1===this.facade.list_style?"center":"aspectFill"},is_hide:function(){return 3===this.facade.list_style||!(!this.content.is_title&&!this.content.is_price&&!this.content.is_button)}},watch:{content:{deep:!0,handler:function(){this.handleCheck()}}},mounted:function(){var t=this;return(0,n.default)(regeneratorRuntime.mark((function e(){return regeneratorRuntime.wrap((function(e){while(1)switch(e.prev=e.next){case 0:t.handleCheck(),t.isLogin&&t.handleCheckTaak();case 2:case"end":return e.stop()}}),e)})))()},methods:{getRemark:function(t){if(t.remark){var e=t.remark.split(",");return"signin"===t.keyword?e[0]+","+e[1]:e[0]+"\n"+e[1]}return""},navigateLink:function(t){uni.navigateTo({url:t,fail:function(){uni.switchTab({url:t,fail:function(){}})}})},handleCheckTaak:function(){var t=this,e=this.content.task.keyword;this.$heshop.plugin("get",{include:"task",model:"task",keyword:e}).then((function(e){e?(t.content.task=e,e.status||(t.is_show=!1)):t.is_show=!1}))},navigateToDetail:function(t){uni.navigateTo({url:"/pages/goods/detail?is_task=1&id="+t})},handleCheck:function(){1!=this.content.type||this.$h.test.isEmpty(this.content.goods)?2==this.content.type?this.handleAutoList():this.goodsData=this.goods:(this.goodsData=this.content.goods,this.handleGoodsList(this.content.goods))},getGoodsCover:function(t){return this.$h.test.isEmpty(t)||"[object Array]"!==Object.prototype.toString.call(t)?this.ipAddress+"/le-default-goods-bg.png":t[0]},handleGoodsList:function(t){var e=[],a=this;t.map((function(t){e.push(t.id)})),e.length>0&&this.$heshop.goods("GET",{behavior:"fitment",goods_id:e.toString(),is_task:1}).then((function(t){t.length>0&&(a.goodsData=t)}))},handleAutoList:function(){var t=this;this.$heshop.goods("GET",{behavior:"fitment",is_task:1,auto:this.content.auto}).then((function(e){e.length>0&&(t.goodsData=e)}))},handleGroupList:function(t){var e=t.id,a=t.limit;if(e){var i=this;this.$heshop.search("POST",{include:"goods"},{keyword:{group:e,tab_key:"onsale"}}).page(1,a).then((function(t){i.goodsData=t.data.length>0?t.data:i.goods}))}},cart:function(t){this.goodsId=t.id}}};e.default=r},df35:function(t,e,a){var i=a("a1a8");e=i(!1),e.push([t.i,'@charset "UTF-8";\n/* start--主题色--start */\n/* end--主题色--end */.goodstask[data-v-cecbda32]{overflow:hidden;margin-bottom:%?24?%}.goodstask .clear[data-v-cecbda32]{clear:both}.goodstask .control-task[data-v-cecbda32]{position:relative;width:%?710?%;height:%?212?%;background:#fff;margin:0 auto;border-radius:%?16?%;margin-top:%?20?%;margin-bottom:%?20?%;overflow:hidden}.goodstask .control-task:hover .select-photo__close[data-v-cecbda32]{display:block}.goodstask .control-task_body[data-v-cecbda32]{position:absolute;left:0;top:%?72?%;width:%?710?%;height:%?140?%;background:#fff;border-radius:%?0?% %?0?% %?16?% %?16?%}.goodstask .control-task_header[data-v-cecbda32]{position:absolute;left:0;top:0;width:%?710?%;height:%?72?%;background:#ffb525;border-radius:%?16?% %?16?% %?0?% %?0?%;font-size:%?28?%;font-family:PingFang SC;font-weight:500;color:#fffffe;line-height:%?72?%;padding-left:%?23?%}.goodstask .control-task_icon[data-v-cecbda32]{width:%?72?%;height:%?72?%;position:absolute;left:%?34?%;top:%?34?%}.goodstask .control-task_button[data-v-cecbda32]{position:absolute;right:%?24?%;top:%?42?%;width:%?140?%;height:%?56?%;background:#ffb525;border-radius:%?28?%;font-size:%?24?%;font-family:PingFang SC;font-weight:500;color:#fff;line-height:%?56?%;text-align:center}.goodstask .control-task_title[data-v-cecbda32]{font-size:%?26?%;font-family:PingFang SC;font-weight:500;color:#666;position:absolute;top:%?38?%;left:%?120?%;white-space:pre;height:%?64?%;line-height:%?32?%;display:table-cell;vertical-align:middle;width:%?400?%;overflow:hidden;word-wrap:break-word;text-overflow:ellipsis}.goodstask .control-task_tips[data-v-cecbda32]{font-size:%?26?%;font-family:PingFang SC;font-weight:500;color:#666;line-height:%?32?%;position:absolute;top:%?70?%;left:%?120?%}.goodstask .chamfer .goods-item[data-v-cecbda32]{border-radius:%?16?%}.goodstask .card .goods-item[data-v-cecbda32]{box-shadow:0 0 %?20?% 0 rgba(0,0,0,.05)}.goodstask .stroke .goods-item[data-v-cecbda32]{border:%?1?% solid rgba(50,50,51,.1)}.goodstask .lucency .goods-item[data-v-cecbda32]{background-color:initial}.goodstask .goods-item[data-v-cecbda32]{box-sizing:border-box;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;background:#fff;overflow:hidden}.goodstask .goods-item .goods-item-photo[data-v-cecbda32]{position:relative}.goodstask .goods-item .goods-item-photo .goods-item-image[data-v-cecbda32]{position:relative;max-height:%?500?%;overflow:hidden;padding-top:50%}.goodstask .goods-item .goods-item-photo .goods-item-cover[data-v-cecbda32]{position:absolute;top:0;right:0;bottom:0;left:0;width:100%;background-repeat:no-repeat;background-position:50%;background:#f3f5f7;background-size:cover}.goodstask .goods-item .goods-item-cover[data-v-cecbda32]{position:absolute;top:0;right:0;bottom:0;left:0;width:100%;background-repeat:no-repeat;background-position:50%;background-size:cover}.goodstask .goods-item .goods-item-detail[data-v-cecbda32]{margin:%?20?% %?20?% %?10?% %?20?%;position:relative}.goodstask .goods-item .goods-item-detail .goods-item-title[data-v-cecbda32]{font-size:%?28?%;font-weight:400;color:#353535;line-height:1.4em;min-height:2.8em;margin-bottom:%?10?%;text-overflow:-o-ellipsis-lastline;overflow:hidden;text-overflow:ellipsis;display:-webkit-box;-webkit-line-clamp:2;line-clamp:2;-webkit-box-orient:vertical}.goodstask .goods-item .goods-item-detail .goods-item-info[data-v-cecbda32]{position:relative;width:100%;line-height:2em;display:-webkit-box;display:-webkit-flex;display:flex;font-weight:400;-webkit-box-pack:justify;-webkit-justify-content:space-between;justify-content:space-between}.goodstask .goods-item .goods-item-detail .goods-item-price[data-v-cecbda32]{display:inline-block;font-weight:400;color:#e60b30;height:%?30?%;display:-webkit-inline-box;display:-webkit-inline-flex;display:inline-flex;-webkit-box-align:center;-webkit-align-items:center;align-items:center;margin-top:%?10?%}.goodstask .goods-item .goods-item-detail .goods-item-price .goods-item-price__icon[data-v-cecbda32]{display:inline-block;font-size:%?24?%;line-height:%?24?%;width:%?24?%;height:%?24?%;padding-right:%?5?%;color:#fbad15;position:relative;top:%?-3?%}.goodstask .goods-item .goods-item-detail .goods-item-price .goods-item-price__num[data-v-cecbda32]{font-size:%?32?%;line-height:%?32?%;padding-left:%?4?%}.goodstask .goods-item .goods-item-detail .goods-item-price .goods-item-price__tag[data-v-cecbda32]{font-size:%?24?%}.goodstask .goods-item .goods-item-detail .goods-item-price .goods-item-price__val[data-v-cecbda32]{font-size:%?24?%}.goodstask .goods-item .goods-item-detail .goods-item-button[data-v-cecbda32]{display:inline-block;width:30%;height:%?56?%;background:#e60b30;border-radius:%?28?%;font-size:%?24?%;font-family:PingFang SC;font-weight:500;color:#fff;text-align:center;line-height:%?56?%;margin-bottom:%?8?%}.goodstask .swipe.goods-layout .goods-item-info[data-v-cecbda32],\n.goodstask .small.goods-layout .goods-item-info[data-v-cecbda32]{line-height:4em;display:block}.goodstask .swipe.goods-layout .goods-item-info .goods-item-price[data-v-cecbda32],\n.goodstask .small.goods-layout .goods-item-info .goods-item-price[data-v-cecbda32]{display:block;height:%?60?%;line-height:%?60?%;font-size:%?30?%;text-overflow:ellipsis;overflow:hidden;white-space:nowrap}.goodstask .swipe.goods-layout .goods-item-info .goods-item-button[data-v-cecbda32],\n.goodstask .small.goods-layout .goods-item-info .goods-item-button[data-v-cecbda32]{display:block;width:100%;height:%?56?%;background:#e60b30;border-radius:%?28?%;font-size:%?24?%;font-family:PingFang SC;font-weight:500;color:#fff;text-align:center;line-height:%?56?%;margin-bottom:%?20?%}.goodstask .larger .goods-item-photo .goods-item-image[data-v-cecbda32]{height:25%}.goodstask .small .goods-item-photo .goods-item-image[data-v-cecbda32],\n.goodstask .list .goods-item-photo .goods-item-image[data-v-cecbda32],\n.goodstask .swipe .goods-item-photo .goods-item-image[data-v-cecbda32]{padding-top:100%}.goodstask .small .goods-wrapper[data-v-cecbda32]{float:left;width:50%}.goodstask .list .goods-item-photo[data-v-cecbda32]{float:left;width:%?240?%;height:%?240?%;min-height:auto;margin-right:%?20?%}.goodstask .list .goods-item-detail[data-v-cecbda32]{height:%?240?%;box-sizing:border-box;margin:0 %?30?% 0 %?240?%;overflow:hidden}.goodstask .list .goods-item-detail .goods-item-title[data-v-cecbda32]{font-weight:400;margin:%?28?% 0 0}.goodstask .list .goods-item-detail .goods-item-info[data-v-cecbda32]{position:absolute;left:0;bottom:%?10?%}.goodstask .swipe[data-v-cecbda32]{display:-webkit-box;display:-webkit-flex;display:flex;-webkit-flex-wrap:nowrap;flex-wrap:nowrap;margin-bottom:%?-20?%;padding-bottom:%?20?%;overflow-x:auto;overflow-y:hidden;-webkit-overflow-scrolling:touch}.goodstask .swipe .goods-wrapper[data-v-cecbda32]{-webkit-box-flex:0;-webkit-flex:0 0 30%;flex:0 0 30%;float:none;width:30%}.goodstask .swipe .goods-item-price__box[data-v-cecbda32]{max-width:%?160?%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}[data-theme="red_theme"] .goods-item-price[data-v-cecbda32]{color:#e60b30!important}[data-theme="purple_theme"] .goods-item-price[data-v-cecbda32]{color:#8f2df3!important}[data-theme="blue_theme"] .goods-item-price[data-v-cecbda32]{color:#33a7ff!important}[data-theme="green_theme"] .goods-item-price[data-v-cecbda32]{color:#1fc551!important}[data-theme="orange_theme"] .goods-item-price[data-v-cecbda32]{color:#ff7f00!important}[data-theme="golden_theme"] .goods-item-price[data-v-cecbda32]{color:#caa45a!important}',""]),t.exports=e},df46:function(t,e,a){"use strict";var i;a.d(e,"b",(function(){return n})),a.d(e,"c",(function(){return o})),a.d(e,"a",(function(){return i}));var n=function(){var t=this,e=t.$createElement,a=t._self._c||e;return a("v-uni-view",{staticClass:"cap-cube",staticStyle:{margin:"0"},style:{width:t.width+"px",height:t.height+"px"}},t._l(t.picture,(function(e,i){return a("v-uni-view",{key:i,staticClass:"cap-cube__item",staticStyle:{margin:"0"},style:{left:e.left+"px",top:e.top+"px",height:e.height+"px",width:e.width+"px",backgroundImage:"url("+(e.url||t.url)+")"},on:{click:function(a){arguments[0]=a=t.$handleEvent(a),t.navigateToDetail(e.link)}}})})),1)},o=[]},dfc4:function(t,e,a){"use strict";var i=a("99ca").default;Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0,a("f9ee"),a("7423"),a("c342"),a("211d"),a("b5aa");var n=i(a("e9ff")),o=i(a("07dd")),r={props:{facade:{type:[Object,Array]},content:{type:[Object,Array]}},components:{heIndexCart:o.default},data:function(){return{goods:[],goodsData:[],goodsId:null}},computed:{mode:function(){return 1===this.facade.list_style?"center":"aspectFill"},is_hide:function(){return 3===this.facade.list_style||!(!this.content.is_title&&!this.content.is_price&&!this.content.is_button)}},watch:{content:{deep:!0,handler:function(){this.handleCheck()}}},mounted:function(){var t=this;return(0,n.default)(regeneratorRuntime.mark((function e(){return regeneratorRuntime.wrap((function(e){while(1)switch(e.prev=e.next){case 0:t.handleCheck();case 1:case"end":return e.stop()}}),e)})))()},methods:{navigateToDetail:function(t){uni.navigateTo({url:"/pages/goods/detail?id="+t})},handleCheck:function(){1!=this.content.type||this.$h.test.isEmpty(this.content.goods)?2==this.content.type?(this.goodsData=this.goods,this.handleGroupList(this.content.group)):this.goodsData=this.goods:(this.goodsData=this.content.goods,this.handleGoodsList(this.content.goods))},getGoodsCover:function(t){return this.$h.test.isEmpty(t)||"[object Array]"!==Object.prototype.toString.call(t)?this.ipAddress+"/le-default-goods-bg.png":t[0]},handleGoodsList:function(t){var e=[],a=this;t.map((function(t){e.push(t.id)})),e.length>0&&this.$heshop.goods("GET",{behavior:"fitment",goods_id:e.toString()}).then((function(t){t.length>0&&(a.goodsData=t)}))},handleGroupList:function(t){var e=t.id,a=t.limit;if(e){var i=this;this.$heshop.search("POST",{include:"goods"},{keyword:{group:e,tab_key:"onsale"}}).page(1,a).then((function(t){i.goodsData=t.data.length>0?t.data:i.goods}))}},cart:function(t){this.goodsId=t.id}}};e.default=r},e2e9:function(t,e,a){var i=a("a1a8");e=i(!1),e.push([t.i,'@charset "UTF-8";\n/* start--主题色--start */\n/* end--主题色--end */.le-coupon-item[data-v-b8ff14b4]{height:%?160?%;border-radius:%?16?%;position:relative}.le-coupon-item .le-coupon-item-content[data-v-b8ff14b4]{height:100%}.le-coupon-item .le-coupon-item-content .le-coupon-item-left[data-v-b8ff14b4]{border-top-left-radius:%?16?%;border-bottom-left-radius:%?16?%;margin:%?10?% 0 %?10?% %?10?%}.le-coupon-item .le-coupon-item-content .le-coupon-item-center[data-v-b8ff14b4]{width:%?28?%;position:relative;overflow:hidden;height:100%}.le-coupon-item .le-coupon-item-content .le-coupon-item-center .le-item-doc[data-v-b8ff14b4]{position:absolute;border-radius:50%;left:50%;width:%?16?%;height:%?16?%;background:#fff}.le-coupon-item .le-coupon-item-content .le-coupon-item-center .le-item-doc-a[data-v-b8ff14b4]{-webkit-transform:translate(-50%,-50%);transform:translate(-50%,-50%)}.le-coupon-item .le-coupon-item-content .le-coupon-item-center .le-item-doc-b[data-v-b8ff14b4]{bottom:0;-webkit-transform:translate(-50%,50%);transform:translate(-50%,50%)}.le-coupon-item .le-coupon-item-content .le-coupon-item-center .le-item-center[data-v-b8ff14b4]{width:%?28?%;height:calc(100% - %?20?%);margin:%?10?% 0;position:relative;overflow:hidden}.le-coupon-item .le-coupon-item-content .le-coupon-item-center .le-item-center .sawtooth[data-v-b8ff14b4]{display:block;width:%?16?%;height:%?110?%;background-image:-webkit-radial-gradient(circle,#fff 30%,transparent 35%);background-image:radial-gradient(circle,#fff 30%,transparent 35%);background-size:%?16?% %?22?%;background-repeat:repeat-y;position:relative;top:50%;left:50%;-webkit-transform:translate(-50%,-50%);transform:translate(-50%,-50%)}.le-coupon-item .le-coupon-item-content .le-coupon-item-center .le-item-center .le-item-center-doc[data-v-b8ff14b4]{width:%?32?%;height:%?32?%;border:%?2?% solid transparent;border-radius:50%;position:absolute;left:50%;-webkit-transform:translateX(-50%);transform:translateX(-50%)}.le-coupon-item .le-coupon-item-content .le-coupon-item-center .le-item-center .le-item-center-doc-a[data-v-b8ff14b4]{top:%?-22?%}.le-coupon-item .le-coupon-item-content .le-coupon-item-center .le-item-center .le-item-center-doc-b[data-v-b8ff14b4]{bottom:%?-22?%}.le-coupon-item .le-coupon-item-content .le-coupon-item-center .le-coupon-item-center-line[data-v-b8ff14b4]{position:absolute;width:%?2?%;height:%?100?%;top:50%;left:50%;background-size:%?2?% %?20?%;background-repeat:repeat-y;background-position:50%;-webkit-transform:translate(-50%,-50%);transform:translate(-50%,-50%)}.le-coupon-item .le-coupon-item-content .le-coupon-item-right[data-v-b8ff14b4]{margin:%?10?% %?10?% %?10?% 0;border-top-right-radius:%?16?%;border-bottom-right-radius:%?16?%;padding:%?7?% 0}.le-coupon-item .le-coupon-item-content .le-coupon-item-price[data-v-b8ff14b4]{font-family:DIN;font-weight:700;text-align:center}.le-coupon-item .le-coupon-item-content .le-coupon-item-price[data-v-b8ff14b4]:before{content:"¥";font-size:%?24?%;font-family:PingFang SC;font-weight:500}.le-coupon-item .le-coupon-item-content .le-coupon-item-min[data-v-b8ff14b4]{font-family:PingFang SC;font-weight:500;text-align:center}.le-coupon-item .le-coupon-item-content .le-coupon-iem-appoint[data-v-b8ff14b4]{font-size:%?22?%;font-family:PingFang SC;font-weight:500;line-height:%?28?%}.le-coupon-item .le-coupon-item-content .le-coupon-btn[data-v-b8ff14b4]{text-align:center}.le-coupon-item .le-coupon-item-content .le-coupon-item-text[data-v-b8ff14b4]{padding:%?22?% 0 %?22?% %?26?%}.le-coupon-item .le-coupon-item-content .le-coupon-item-name[data-v-b8ff14b4]{font-size:%?30?%;font-family:PingFang SC;font-weight:500;line-height:%?40?%}.le-item-marginRight-odd[data-v-b8ff14b4]:nth-child(odd),\n.le-item-marginRight[data-v-b8ff14b4]{margin-right:%?12?%}.le-item-Jagged[data-v-b8ff14b4]{position:absolute;width:%?16?%;height:%?140?%;background-image:-webkit-radial-gradient(circle,#fff 40%,transparent 45%);background-image:radial-gradient(circle,#fff 40%,transparent 45%);background-size:%?16?% %?36?%;background-repeat:repeat-y;top:50%}.le-item-Jagged[data-v-b8ff14b4]:first-child{left:0;-webkit-transform:translate(-50%,-50%);transform:translate(-50%,-50%)}.le-item-Jagged[data-v-b8ff14b4]:last-child{right:0;-webkit-transform:translate(50%,-50%);transform:translate(50%,-50%)}.le-coupon-item.fillet .le-coupon-item-left[data-v-b8ff14b4]:before,\n.le-coupon-item.fillet .le-coupon-item-left[data-v-b8ff14b4]:after{content:"";display:block;position:absolute;width:%?30?%;height:%?30?%;background-image:-webkit-radial-gradient(circle,#fff 70%,transparent 0);background-image:radial-gradient(circle,#fff 70%,transparent 0);background-size:%?30?% %?30?%;background-repeat:no-repeat}.le-coupon-item.fillet .le-coupon-item-left[data-v-b8ff14b4]:before{left:0;top:0;-webkit-transform:translate(-45%,-45%);transform:translate(-45%,-45%)}.le-coupon-item.fillet .le-coupon-item-left[data-v-b8ff14b4]:after{left:0;bottom:0;-webkit-transform:translate(-45%,45%);transform:translate(-45%,45%)}.le-coupon-item.fillet .le-coupon-item-right[data-v-b8ff14b4]:before,\n.le-coupon-item.fillet .le-coupon-item-right[data-v-b8ff14b4]:after{content:"";display:block;position:absolute;width:%?30?%;height:%?30?%;background-image:-webkit-radial-gradient(circle,#fff 70%,transparent 0);background-image:radial-gradient(circle,#fff 70%,transparent 0);background-size:%?30?% %?30?%;background-repeat:no-repeat}.le-coupon-item.fillet .le-coupon-item-right[data-v-b8ff14b4]:before{right:0;top:0;-webkit-transform:translate(45%,-45%);transform:translate(45%,-45%)}.le-coupon-item.fillet .le-coupon-item-right[data-v-b8ff14b4]:after{right:0;bottom:0;-webkit-transform:translate(45%,45%);transform:translate(45%,45%)}.coupon[data-v-b8ff14b4]{overflow:hidden;background-color:#fff}.le-coupon-box[data-v-b8ff14b4]{width:%?750?%;background:#fff;padding:%?20?% %?20?% %?15?% %?20?%}.he-open-subscribe[data-v-b8ff14b4]{display:inline-block}',""]),t.exports=e},e3e7:function(t,e,a){var i=a("a1a8");e=i(!1),e.push([t.i,".tabs .tabs-header[data-v-3d40fb81]{position:-webkit-sticky;position:sticky;z-index:1;top:var(--window-top);white-space:nowrap;overflow:hidden;padding-right:%?20?%;width:%?750?%}.tabs .tabs-header .he-scroll-box[data-v-3d40fb81]{width:%?750?%;height:%?88?%}.tabs .tabs-header .he-scroll-box .he-tab-item[data-v-3d40fb81]{font-size:%?26?%;font-family:PingFang SC;font-weight:500;color:#666;line-height:%?88?%;padding:0 %?30?%;position:relative}.tabs .tabs-header .he-scroll-box .he-tab-item .he-tab-line[data-v-3d40fb81]{position:absolute;width:%?24?%;height:%?4?%;background:#000;left:50%;bottom:%?12?%;-webkit-transform:translateX(-50%);transform:translateX(-50%)}.tabs .tabs-header .he-scroll-box .he-tab-item.active[data-v-3d40fb81]{color:#e60b30}.tabs .tabs-header .he-scroll-box .he-tab-item.active .he-tab-line[data-v-3d40fb81]{position:absolute;width:%?24?%;height:%?4?%;background:#e60b30;left:50%;bottom:%?12?%}.tabs .tabs-content-active[data-v-3d40fb81]{position:relative}.tabs .tabs-content-active .tabs-content-shade[data-v-3d40fb81]{position:absolute;display:block}",""]),t.exports=e},e44a:function(t,e,a){"use strict";var i=a("99ca").default;Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0,a("4cfc");var n=i(a("c2c4")),o={props:{value:Boolean,coupon:Array,wechatUrl:String},components:{HePopup:n.default},computed:{showModal:{get:function(){return this.value},set:function(t){this.$emit("input",t)}}},filters:{setNumber:function(t){return Number(t)}},methods:{closeModal:function(){var t=this;this.showModal=!1,uni.redirectTo({url:t.wechatUrl,fail:function(){uni.switchTab({url:t.wechatUrl})}})}}};e.default=o},e547:function(t,e,a){t.exports=a.p+"static/img/bg.de9c09e3.png"},e6cd:function(t,e,a){"use strict";var i=a("51fa"),n=a.n(i);n.a},e71b:function(t,e,a){var i=a("a1a8");e=i(!1),e.push([t.i,"uni-movable-area[data-v-03826ed1]{width:100%;height:100vh;position:fixed;top:0;z-index:100}.box[data-v-03826ed1]{width:%?424?%;height:%?362?%;background:#000;opacity:.6;border-radius:%?40?%;position:absolute;top:50%;left:50%;-webkit-transform:translate(-50%,-50%);transform:translate(-50%,-50%)}",""]),t.exports=e},e721:function(t,e,a){"use strict";var i=a("9231"),n=a.n(i);n.a},e9cd:function(t,e,a){"use strict";var i=a("f00f"),n=a.n(i);n.a},eca4:function(t,e,a){"use strict";a.r(e);var i=a("0f7c"),n=a("1d15");for(var o in n)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return n[t]}))}(o);a("448f");var r,s=a("5d80"),c=Object(s["a"])(n["default"],i["b"],i["c"],!1,null,"f78c898c",null,!1,i["a"],r);e["default"]=c.exports},ecb4:function(t,e,a){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default=void 0;var i={props:{facade:{type:[Object,Array]},content:{type:[Object,Array]}},methods:{navigateToDetail:function(t){this.$h.MPageNavigate(t)}}};e.default=i},ed0a:function(t,e,a){"use strict";var i;a.d(e,"b",(function(){return n})),a.d(e,"c",(function(){return o})),a.d(e,"a",(function(){return i}));var n=function(){var t=this,e=t.$createElement,a=t._self._c||e;return a("v-uni-movable-area",{on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.isShow=!1}}},[t.isShow?a("v-uni-view",{staticClass:"box",on:{click:function(e){e.stopPropagation(),arguments[0]=e=t.$handleEvent(e)}}}):a("v-uni-movable-view",{staticStyle:{width:"88rpx",height:"88rpx","background-color":"red"},attrs:{inertia:!0,direction:"all",y:t.y,x:t.x},on:{touchend:function(e){arguments[0]=e=t.$handleEvent(e),t.touchend.apply(void 0,arguments)},click:function(e){e.stopPropagation(),arguments[0]=e=t.$handleEvent(e),t.onClick.apply(void 0,arguments)},change:function(e){arguments[0]=e=t.$handleEvent(e),t.onChange.apply(void 0,arguments)}}})],1)},o=[]},ed5e:function(t,e,a){"use strict";a.r(e);var i=a("27e6"),n=a("449c");for(var o in n)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return n[t]}))}(o);a("6db9");var r,s=a("5d80"),c=Object(s["a"])(n["default"],i["b"],i["c"],!1,null,"570d7466",null,!1,i["a"],r);e["default"]=c.exports},ee59:function(t,e,a){"use strict";var i=a("7b62"),n=a.n(i);n.a},ee94:function(t,e,a){var i=a("a1a8");e=i(!1),e.push([t.i,'@charset "UTF-8";\n/* start--主题色--start */\n/* end--主题色--end */.goods[data-v-11869f80]{overflow:hidden}.goods .clear[data-v-11869f80]{clear:both}.goods .chamfer .goods-item[data-v-11869f80]{border-radius:%?16?%}.goods .card .goods-item[data-v-11869f80]{box-shadow:0 0 %?20?% 0 rgba(0,0,0,.05)}.goods .stroke .goods-item[data-v-11869f80]{border:%?1?% solid rgba(50,50,51,.1)}.goods .lucency .goods-item[data-v-11869f80]{background-color:initial}.goods .goods-item[data-v-11869f80]{box-sizing:border-box;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;background:#fff;overflow:hidden}.goods .goods-item .goods-item-photo[data-v-11869f80]{position:relative}.goods .goods-item .goods-item-photo .goods-item-image[data-v-11869f80]{position:relative;max-height:%?500?%;overflow:hidden;padding-top:50%}.goods .goods-item .goods-item-photo .goods-item-cover[data-v-11869f80]{position:absolute;top:0;right:0;bottom:0;left:0;width:100%;background-repeat:no-repeat;background-position:50%;background:#f3f5f7;background-size:cover}.goods .goods-item .goods-item-cover[data-v-11869f80]{position:absolute;top:0;right:0;bottom:0;left:0;width:100%;background-repeat:no-repeat;background-position:50%;background-size:cover}.goods .goods-item .goods-item-detail[data-v-11869f80]{margin:%?20?% %?20?% %?10?% %?20?%;position:relative}.goods .goods-item .goods-item-detail .goods-item-title[data-v-11869f80]{font-size:%?28?%;font-weight:400;color:#353535;line-height:1.4em;min-height:2.8em;margin-bottom:%?10?%;text-overflow:-o-ellipsis-lastline;overflow:hidden;text-overflow:ellipsis;display:-webkit-box;-webkit-line-clamp:2;line-clamp:2;-webkit-box-orient:vertical}.goods .goods-item .goods-item-detail .goods-item-info[data-v-11869f80]{position:relative;width:100%;line-height:2em;display:-webkit-box;display:-webkit-flex;display:flex;font-weight:400;-webkit-box-pack:justify;-webkit-justify-content:space-between;justify-content:space-between}.goods .goods-item .goods-item-detail .goods-item-price[data-v-11869f80]{display:inline-block;font-weight:400}.goods .goods-item .goods-item-detail .goods-item-price .goods-item-price__tag[data-v-11869f80]{font-size:%?24?%;padding-right:%?4?%}.goods .goods-item .goods-item-detail .goods-item-price .goods-item-price__val[data-v-11869f80]{font-size:%?32?%}.goods .goods-item .goods-item-detail .goods-item-button[data-v-11869f80]{display:inline-block}.goods .goods-item .goods-item-detail .goods-item-button .le-icon[data-v-11869f80]{vertical-align:0}.goods .goods-item .goods-item-detail .goods-item-button .iconfont[data-v-11869f80]{font-size:%?36?%}.goods .larger .goods-item-photo .goods-item-image[data-v-11869f80]{height:25%}.goods .small .goods-item-photo .goods-item-image[data-v-11869f80],\n.goods .list .goods-item-photo .goods-item-image[data-v-11869f80],\n.goods .swipe .goods-item-photo .goods-item-image[data-v-11869f80]{padding-top:100%}.goods .small .goods-wrapper[data-v-11869f80]{float:left;width:50%}.goods .list .goods-item-photo[data-v-11869f80]{float:left;width:%?240?%;height:%?240?%;min-height:auto;margin-right:%?20?%}.goods .list .goods-item-detail[data-v-11869f80]{height:%?240?%;box-sizing:border-box;margin:0 %?30?% 0 %?240?%;overflow:hidden}.goods .list .goods-item-detail .goods-item-title[data-v-11869f80]{font-weight:400;margin:%?28?% 0 0}.goods .list .goods-item-detail .goods-item-info[data-v-11869f80]{position:absolute;left:0;bottom:%?10?%}.goods .swipe[data-v-11869f80]{display:-webkit-box;display:-webkit-flex;display:flex;-webkit-flex-wrap:nowrap;flex-wrap:nowrap;margin-bottom:%?-20?%;padding-bottom:%?20?%;overflow-x:auto;overflow-y:hidden;-webkit-overflow-scrolling:touch}.goods .swipe .goods-wrapper[data-v-11869f80]{-webkit-box-flex:0;-webkit-flex:0 0 30%;flex:0 0 30%;float:none;width:30%}[data-theme="red_theme"] .goods-item-price[data-v-11869f80], [data-theme="red_theme"]\n.iconfont[data-v-11869f80]{color:#e60b30!important}[data-theme="purple_theme"] .goods-item-price[data-v-11869f80], [data-theme="purple_theme"]\n.iconfont[data-v-11869f80]{color:#8f2df3!important}[data-theme="blue_theme"] .goods-item-price[data-v-11869f80], [data-theme="blue_theme"]\n.iconfont[data-v-11869f80]{color:#33a7ff!important}[data-theme="green_theme"] .goods-item-price[data-v-11869f80], [data-theme="green_theme"]\n.iconfont[data-v-11869f80]{color:#1fc551!important}[data-theme="orange_theme"] .goods-item-price[data-v-11869f80], [data-theme="orange_theme"]\n.iconfont[data-v-11869f80]{color:#ff7f00!important}[data-theme="golden_theme"] .goods-item-price[data-v-11869f80], [data-theme="golden_theme"]\n.iconfont[data-v-11869f80]{color:#caa45a!important}',""]),t.exports=e},eef1:function(t,e,a){"use strict";var i;a.d(e,"b",(function(){return n})),a.d(e,"c",(function(){return o})),a.d(e,"a",(function(){return i}));var n=function(){var t=this,e=t.$createElement,a=t._self._c||e;return a("v-uni-view",{staticClass:"pointer",style:{marginBottom:t.margin+"px",padding:"0 "+t.margin/2+"px"}},[t.type<3?a("v-uni-view",{staticClass:"pointer-content",class:{circle:1==t.type,strip:2==t.type},style:{textAlign:t.align}},t._l(t.number,(function(e,i){return a("span",{key:i,staticClass:"pointer-item",style:{"background-color":t.activeColor(i)}})})),0):t._e(),3==t.type?a("v-uni-view",{staticClass:"pointer-text",style:{textAlign:t.align}},[a("span",[t._v(t._s(t.current+1)+"/"+t._s(t.number))])]):t._e()],1)},o=[]},f00f:function(t,e,a){var i=a("48dd");"string"===typeof i&&(i=[[t.i,i,""]]),i.locals&&(t.exports=i.locals);var n=a("5c0d").default;n("1f090bf6",i,!0,{sourceMap:!1,shadowMode:!1})},f228:function(t,e,a){"use strict";var i=a("87d3"),n=a.n(i);n.a},f2f1:function(t,e,a){"use strict";var i;a.d(e,"b",(function(){return n})),a.d(e,"c",(function(){return o})),a.d(e,"a",(function(){return i}));var n=function(){var t=this,e=t.$createElement,a=t._self._c||e;return a("v-uni-view",{staticClass:"goodstask",style:{backgroundColor:t.facade.background_color},attrs:{"data-theme":t.theme}},[t.content.task.name&&t.is_show?a("div",{staticClass:"control-task"},[a("div",{staticClass:"control-task_header",style:{backgroundColor:t.facade.title_background,color:t.facade.title_color}},[t._v(t._s(t.content.task.name)+"送积分")]),a("div",{staticClass:"control-task_body",style:{backgroundColor:t.facade.content_background}},[a("img",{staticClass:"control-task_icon",attrs:{src:t.getIconUrl}}),a("div",{staticClass:"control-task_title",style:{color:t.facade.content_color}},[t._v(t._s(t.getRemark(t.content.task)))]),a("div",{staticClass:"control-task_button",style:{backgroundColor:t.facade.button_background,color:t.facade.button_color},on:{click:function(e){arguments[0]=e=t.$handleEvent(e),t.navigateLink("/plugins/task/index")}}},[t._v(t._s(t.content.title||"去攒积分"))])])]):t._e(),a("v-uni-view",{staticClass:"goods-layout",class:{larger:1==t.facade.list_style,small:2==t.facade.list_style,list:3==t.facade.list_style,swipe:4==t.facade.list_style},style:{paddingLeft:t.facade.padding+"px",paddingRight:t.facade.padding+"px",marginLeft:-t.facade.margin/2+"px",marginRight:-t.facade.margin/2+"px"}},[t._l(t.goodsData,(function(e,i){return a("v-uni-view",{key:i,staticClass:"goods-wrapper",class:{white:1==t.facade.card_style,card:2==t.facade.card_style,stroke:3==t.facade.card_style,lucency:4==t.facade.card_style,chamfer:t.facade.chamfer_style}},["商品名称"!==e.name?a("v-uni-view",{staticClass:"goods-item",style:{margin:t.facade.margin/2+"px"},on:{click:function(a){arguments[0]=a=t.$handleEvent(a),t.navigateToDetail(e.id)}}},[a("v-uni-view",{staticClass:"goods-item-photo"},[a("v-uni-view",{staticClass:"goods-item-image"},[a("v-uni-view",{staticClass:"goods-item-cover"},[a("v-uni-image",{staticStyle:{width:"100%",height:"100%"},attrs:{"lazy-load":!0,src:t.getGoodsCover(e.slideshow),mode:t.mode}})],1)],1)],1),t.is_hide?a("v-uni-view",{staticClass:"goods-item-detail"},[t.content.is_title?a("v-uni-view",{staticClass:"goods-item-title"},[t._v(t._s(e.name))]):t._e(),a("v-uni-view",{staticClass:"goods-item-info"},[a("v-uni-view",{staticClass:"goods-item-price"},[t.content.is_price?a("v-uni-view",{staticClass:"goods-item-price__box"},[a("v-uni-view",{staticClass:"goods-item-price__icon iconfont iconjifen"}),a("span",{staticClass:"goods-item-price__num"},[t._v(t._s(e.task.task_number)+"+")]),a("span",{staticClass:"goods-item-price__tag"},[t._v("¥")]),a("span",{staticClass:"goods-item-price__val"},[t._v(t._s(e.task.task_price))])],1):t._e()],1),t.content.is_button?a("v-uni-view",{staticClass:"goods-item-button",style:{backgroundColor:t.themeColor},on:{click:function(a){a.stopPropagation(),arguments[0]=a=t.$handleEvent(a),t.cart(e)}}},[t._v("兑换")]):t._e()],1)],1):t._e()],1):t._e()],1)})),a("v-uni-view",{staticClass:"clear"})],2),a("he-index-cart",{attrs:{"goods-id":t.goodsId,is_task:1},on:{"update:goodsId":function(e){arguments[0]=e=t.$handleEvent(e),t.goodsId=e},"update:goods-id":function(e){arguments[0]=e=t.$handleEvent(e),t.goodsId=e}}})],1)},o=[]},f4ca:function(t,e,a){var i=a("a1a8");e=i(!1),e.push([t.i,".search[data-v-570d7466]{width:100%;box-sizing:border-box;padding:%?20?% %?30?%;background-color:#f3f0fd}.search .angle[data-v-570d7466]{border-radius:%?32?%}.search .iconsearchbar_search[data-v-570d7466]{font-size:%?24?%}.search .search-content[data-v-570d7466]{height:%?64?%;line-height:%?64?%;font-size:%?28?%;box-sizing:border-box;color:#9c9c9c;background-color:#fff;padding-left:%?30?%}.search .search-content span[data-v-570d7466]{padding-left:%?10?%;font-size:%?24?%}",""]),t.exports=e},f545:function(t,e,a){var i=a("a1a8");e=i(!1),e.push([t.i,".cap-cube[data-v-4a3252cc]{position:relative}.cap-cube__item[data-v-4a3252cc]{position:absolute;overflow:hidden;background-repeat:no-repeat;background-position:50%;background-size:cover;background-position:50%}",""]),t.exports=e},f6e2:function(t,e,a){"use strict";var i=a("2207"),n=a.n(i);n.a},f75a:function(t,e,a){"use strict";a.r(e);var i=a("42f0"),n=a("8069");for(var o in n)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return n[t]}))}(o);a("c723");var r,s=a("5d80"),c=Object(s["a"])(n["default"],i["b"],i["c"],!1,null,"ddf4ab52",null,!1,i["a"],r);e["default"]=c.exports},f818:function(t,e,a){"use strict";a.r(e);var i=a("899d"),n=a("8bec");for(var o in n)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return n[t]}))}(o);a("415b");var r,s=a("5d80"),c=Object(s["a"])(n["default"],i["b"],i["c"],!1,null,"41c96624",null,!1,i["a"],r);e["default"]=c.exports},fb50:function(t,e,a){"use strict";a.r(e);var i=a("5a7d"),n=a.n(i);for(var o in i)["default"].indexOf(o)<0&&function(t){a.d(e,t,(function(){return i[t]}))}(o);e["default"]=n.a},fc3d:function(t,e,a){var i=a("a1a8");e=i(!1),e.push([t.i,'@charset "UTF-8";\n/* start--主题色--start */\n/* end--主题色--end */.le-notice[data-v-0723e115]{width:100%}',""]),t.exports=e}}]);
import React, {useState} from 'react'; import Navigation from './Navigation'; import About from '../pages/About.js'; import Projects from '../pages/Projects.js'; import Contact from '../pages/Contact.js'; import Resume from '../pages/Resume.js'; function Header() { const [currentPage, setCurrentPage] = useState("About"); function renderPage() { switch(currentPage) { default: return <About /> case "Projects": return <Projects/>; case "Contact": return <Contact/>; case "Resume": return <Resume/> } } return ( <div> <div className="header-div"> <h1 className="header-h1 nav-li">Priti Patel</h1> <Navigation currentPage={currentPage} setCurrentPage={setCurrentPage} /> </div> {renderPage(currentPage)} </div> ) } export default Header; //function Header() { //return ( // <header> //<h1><a href="./index.html">Priti Patel</a></h1> // <nav> // <ul> // <li> //<a href="#About-Me">About Me</a> // </li> // <li> // <a href="#Work">Work</a> // </li> // <li> // <a href="#Contact-Me">Contact Me</a> // </li> // <li> // <a href={resume}>Resume</a> // </li> // </ul> //</nav> // </header> // ) //} //export default Header;
const express = require('express'); const mongoose = require('mongoose'); const cookieSession = require('cookie-session'); const passport = require('passport'); const bodyParser = require('body-parser'); const keys = require('./config/keys'); require('./models/User'); require('./models/Blog'); require('./services/passport'); require('./services/cache'); mongoose.Promise = global.Promise; mongoose.connect(keys.mongoURI, { useNewUrlParser: true, useUnifiedTopology: true, }); const app = express(); app.use(bodyParser.json()); app.use( cookieSession({ maxAge: 30 * 24 * 60 * 60 * 1000, keys: [keys.cookieKey], }) ); app.use(passport.initialize()); app.use(passport.session()); require('./routes/authRoutes')(app); require('./routes/blogRoutes')(app); require('./routes/uploadRoutes')(app); if (['production', 'ci'].includes(process.env.NODE_ENV)) { app.use(express.static('client/build')); const path = require('path'); app.get('*', (req, res) => { res.sendFile(path.resolve('client', 'build', 'index.html')); }); } const PORT = process.env.PORT || 5000; app.listen(PORT, () => { console.log(`Listening on port`, PORT); });
import React from 'react' import { Table } from 'react-bootstrap' import PropTypes from 'prop-types' import DriversTableRow from '../../containers/DriversTableRow' const DriversTable = ({ drivers }) => { return ( <Table striped bordered hover> <thead> <tr> <th>#</th> <th>Nombre</th> <th>Apellido</th> <th>Patente</th> <th>Acciones</th> </tr> </thead> <tbody> {drivers.map((driver, index) => <DriversTableRow index={index + 1} key={index} driver={driver} />)} </tbody> </Table> ) } DriversTable.propTypes = { drivers: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), firstName: PropTypes.string, lastName: PropTypes.string, email: PropTypes.string, age: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), carLicensePlate: PropTypes.string, carModel: PropTypes.string, carYear: PropTypes.oneOfType([PropTypes.number, PropTypes.string]) })).isRequired } export default DriversTable
module.exports = function (RED) { 'use strict'; const STATUS_OK = { fill: "green", shape: "dot", text: "OK" }; const Unifi = require('ubnt-unifi'); function UnifiEventsNode(config) { RED.nodes.createNode(this, config); const node = this; const {username, password} = node.credentials; let {site, host, port, insecure, unifios} = config; let clientMap = {}; // console.log("Connecting to", host); this.status({fill:"grey",shape:"dot",text:"connecting"}); let unifi = new Unifi({ host: host, port: port, username: username, password: password, site: site, insecure: insecure, unifios: unifios }); unifi.on('ctrl.connect', function (data) { node.status({fill:"green",shape:"dot",text:"connected"}); unifi.get('stat/alluser') .then(sta => { // console.log('Loaded info for '+sta.data.length+' users'); sta.data.forEach((el, index) => clientMap[el.mac] = el); console.log(sta.data.map((el) => el.mac + " " + (el.name || el.hostname || el.device_name))); }); }); unifi.on('ctrl.error', function (data) { node.status({fill:"red",shape:"dot",text:"error"}); }); unifi.on('ctrl.disconnect', function (data) { node.status({fill:"grey",shape:"ring",text:"disconnected"}); }); unifi.on('ctrl.reconnect', function (data) { node.status({fill:"grey",shape:"dot",text:"reconnecting"}); }); unifi.on('ctrl.close', function (data) { node.status({fill:"grey",shape:"dot",text:"disconnected"}); }); // Listen for any event unifi.on('**', function (data) { console.log("Received event", this.event, data); let msg = { payload: { namespace: this.event.split('.')[0], event: this.event, data: data } }; if (data && data.user) { // details are cached. enrich event let client = clientMap[data.user]; if (client) { addClientToPayload(client, msg.payload); node.send(msg); } else { // load client details // console.log('Loading info for '+data.user); unifi.get('stat/user/'+data.user) .then(response => { // console.log('Got user info', response); client = response.data[0]; clientMap[data.user] = client; addClientToPayload(client, msg.payload); node.send(msg); }); } } else { node.send(msg); } }); function addClientToPayload(client, payload) { payload.client = { hostname: client.hostname, device_name: client.device_name, name: client.name, ip: client.ip }; } this.on('close', function() { node.status({fill:"grey",shape:"dot",text:"disconnecting"}); // console.log("Closing connection"); unifi.close(); }); } RED.nodes.registerType("UnifiEvents", UnifiEventsNode, { credentials: { username: {type: "text"}, password: {type: "password"} } }); };
import React, { useState } from 'react'; import { Link, useHistory } from 'react-router-dom'; import { FiArrowLeft } from 'react-icons/fi'; import api from '../../services/api'; import logoImg from '../../assets/logo.svg' import './styles.css'; export default function NewIncident() { const [title, setTitle] = useState(''); const [description, setDescription] = useState(''); const [value, setValue] = useState(''); const history = useHistory(); const ongId = localStorage.getItem('ongId'); async function handleNewIncident(e) { e.preventDefault(); const data = { title, description, value }; try { await api.post('incidents', data, { headers: { Authorization: ongId, } }) history.push('/profile'); } catch (error) { alert('Erro ao cadastrar caso, tente novamente.'); } } return ( <div className="new-incident-container"> <div className="content"> <section> <img src={logoImg} alt="Be The Hero"/> <h1>Cadastrar novo caso</h1> <p> Descreva o caso detalhadamente para encontrar um herói para resolver isso. </p> <Link className="back-link" to="/profile"> <FiArrowLeft size={16} color="#E02041" /> Voltar para Home </Link> </section> <form onSubmit={handleNewIncident}> <input placeholder="Título do caso" value={title} onChange={e => setTitle(e.target.value)} /> <textarea placeholder="Descrição" value={description} onChange={e => setDescription(e.target.value)} /> <input placeholder="Valor em reais" value={value} onChange={e => setValue(e.target.value)} /> <button className="button" type="submit">Cadastrar</button> </form> </div> </div> ); };
// we use self-invoking functions so the mainCtrl and apiService do not become global (function(){ angular.module("app",[]) .constant("myApiUrl","http://localhost:8080") .service("apiService",apiService) .controller("mainCtrl",mainCtrl) .value("isLoading",false); mainCtrl.$inject=["apiService","isLoading"]; /** * You might notice we used in the controller declaration 'mainCtrl as vm' above. In the following the 'vm' * * references to 'this 'of the function */ function mainCtrl(apiService,isLoading){ this.title = "Hello World!"; this.subtitle = "This is small app combining Angular and NodeJS written for educational purposes!"; this.fetchRandomNumberFromServer = fetchRandomNumberFromServer.bind(this); this.isLoading = isLoading; // initialise fetchRandomNumberFromServer.call(this); function fetchRandomNumberFromServer(){ this.isLoading = true; // we use angular.bind so inside the onDataFetched function we could set up this of the mainCtrl apiService.fetchRandomNumberFromServer(angular.bind(this,function(randomNumber){ this.isLoading = false; this.randomNumber = randomNumber; })); } } apiService.$inject = ["$http","myApiUrl"]; function apiService($http,myApiUrl){ return { fetchRandomNumberFromServer : fetchRandomNumberFromServer } function fetchRandomNumberFromServer(callback){ $http.get(myApiUrl+"/get-random-number").then(function(response){ console.log(response); callback(response.data.randomNumber); }); } } }());
const http = require('http'); const fs = require("fs"); const crypto = require("crypto"); const hostname = '127.0.0.1'; const port = 3000; const build_file = 'global_build_number.txt'; const version_file = 'version_number.txt'; var hash = crypto.randomBytes(20).toString('hex'); var oldHash = crypto.randomBytes(20).toString('hex'); var checkHash = crypto.randomBytes(20).toString('hex'); const increment_global_build_number = () => { try { let data = fs.readFileSync(build_file, 'utf8'); let incremented = Number(data) + 1; fs.writeFileSync(build_file, incremented); console.log(`Build number is now: ${incremented}`); return { code: 200, value: incremented }; } catch(e) { console.log('R/W error build_number:', e.stack); return { code: 500, value: -1 }; } } const is_bigger = (new_version_number, old_version_number) => { const acceptable_prefix = ['a','b'] let old_pre; let new_pre; let old_n = old_version_number.split('.').map((element) => { if (isNaN(element)) { old_pre = element.slice(0,1); return parseInt(element.slice(1)); } else return parseInt(element); }); let new_n = new_version_number.split('.').map((element) => { if (isNaN(element)) { new_pre = element.slice(0,1); return parseInt(element.slice(1)); } else return parseInt(element); }); if (acceptable_prefix.includes(old_pre)) { if (old_pre === new_pre) {} else if (old_pre === 'a' && new_pre === 'b' && new_n[0] === 1 && new_n[1] === 0 && new_n[2] === 0) return true; else if (old_pre === 'b' && !new_pre && new_n[0] === 1 && new_n[1] === 0 && new_n[2] === 0) return true; else return false; } // Check that if first element is incremented the rest of the elements are zero if (new_n[0] === old_n[0] + 1 && new_n[1] === 0 && new_n[2] === 0) { return true; } // Check that if second element is incremented the last element is zero else if (new_n[0] === old_n[0] && new_n[1] === old_n[1] + 1 && new_n[2] === 0) { return true; } // Check that if none of the two first elements are incremented the third is else if (new_n[0] === old_n[0] && new_n[1] === old_n[1] && new_n[2] === old_n[2] + 1) { return true; } // Else fail else return false; } const check_version_number = (new_version_number) => { try { let old_version_number = fs.readFileSync(version_file, 'utf8'); if (is_bigger(new_version_number, old_version_number)) { console.log(`New version number is valid: ${new_version_number}`); checkHash = crypto.createHash('sha256').update(hash + new_version_number).digest('hex') oldHash = hash; hash = crypto.randomBytes(20).toString('hex'); return { code: 200, value: new_version_number, key: checkHash } } else { console.log(`New version number is not valid: ${new_version_number}, is still ${old_version_number}`); return { code: 300, value: old_version_number, key: -1 } } } catch (e) { console.log('R/W error check_version_number:', e.stack); return { code: 500, value: -1, key: -1 }; } } const increase_version_number = (new_version_number, key) => { try { let old_version_number = fs.readFileSync(version_file, 'utf8'); if (is_bigger(new_version_number, old_version_number) && key == checkHash && crypto.createHash('sha256').update(oldHash + new_version_number).digest('hex') == checkHash) { checkHash = crypto.randomBytes(20).toString('hex'); fs.writeFileSync(version_file, new_version_number); console.log(`New version number: ${new_version_number}`); return { code: 200, value: new_version_number } } else { console.log(`Failed to update version number to ${new_version_number}, is still ${old_version_number}`); return { code: 300, value: old_version_number } } } catch (e) { console.log('R/W error increase_version_number:', e.stack); return { code: 500, value: -1 }; } } const server = http.createServer((req, res) => { if (req.method == 'GET') { let build_increment = increment_global_build_number(); res.statusCode = build_increment.code; res.setHeader('Content-Type', 'text/plain'); res.end(`{ "build": "${build_increment.value}" }`); } else if (req.method == 'POST') { let body = ''; req.on('data', chunk => { body += chunk.toString(); }); req.on('end', () => { let json; try { json = JSON.parse(body).version_number } catch (e) { console.log("Failed to parse the json") } let new_version = check_version_number(json) res.statusCode = new_version.code; res.setHeader('Content-Type', 'text/plain'); res.end(`{ "version": "${new_version.value}", "key": "${new_version.key}" }`); }); } else if (req.method == 'PUT') { let body = ''; req.on('data', chunk => { body += chunk.toString(); }); req.on('end', () => { let json; try { json = JSON.parse(body) } catch (e) { console.log("Failed to parse the json") } let new_version = increase_version_number(json.version_number, json.key) res.statusCode = new_version.code; res.setHeader('Content-Type', 'text/plain'); res.end(`{ "version": "${new_version.value}" }`); }); } }); server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); });
var inherits = require('inherits'); var fsm = require('./fsm.js'); var messages = require('./messages.js'); function _State () { } inherits(_State, fsm._State); function _Past () { this.name = 'Past'; } inherits(_Past, _State); var Past = new _Past(); exports.Past = Past; function _Start () { this.name = 'Start'; } inherits(_Start, _State); var Start = new _Start(); exports.Start = Start; function _Present () { this.name = 'Present'; } inherits(_Present, _State); var Present = new _Present(); exports.Present = Present; _Past.prototype.start = function (controller) { controller.scope.time_pointer = controller.scope.history.length - 1; }; _Past.prototype.onMouseWheel = function (controller, msg_type, message) { controller.delegate_channel.send(msg_type, message); }; _Past.prototype.onMouseWheel.transitions = ['Present']; _Past.prototype.onMessage = function(controller, msg_type, message) { //console.log(message.data); var type_data = JSON.parse(message.data); var type = type_data[0]; var data = type_data[1]; if (['StateCreate', 'StateDestroy', 'StateMove', 'StateLabelEdit', 'TransitionLabelEdit', 'TransitionCreate', 'TransitionDestroy'].indexOf(type) !== -1) { controller.changeState(Present); controller.scope.history.splice(controller.scope.time_pointer); if (data.sender !== controller.scope.client_id) { controller.handle_message(msg_type, message); } else { controller.scope.history.push(message.data); } } else { controller.handle_message(type, data); } }; _Past.prototype.onMessage.transitions = ['Present']; _Past.prototype.onTransitionSelected = function(controller, msg_type, message) { if (message.sender !== controller.scope.client_id) { controller.scope.onTransitionSelected(message); } }; _Past.prototype.onTransitionUnSelected = function(controller, msg_type, message) { if (message.sender !== controller.scope.client_id) { controller.scope.onTransitionUnSelected(message); } }; _Past.prototype.onStateSelected = function(controller, msg_type, message) { if (message.sender !== controller.scope.client_id) { controller.scope.onStateSelected(message); } }; _Past.prototype.onStateUnSelected = function(controller, msg_type, message) { if (message.sender !== controller.scope.client_id) { controller.scope.onStateUnSelected(message); } }; _Past.prototype.onUndo = function(controller, msg_type, message) { if (message.sender !== controller.scope.client_id) { controller.scope.time_pointer = Math.max(0, controller.scope.time_pointer - 1); controller.scope.undo(message.original_message); } }; _Past.prototype.onRedo = function(controller, msg_type, message) { if (message.sender !== controller.scope.client_id) { controller.scope.time_pointer = Math.min(controller.scope.history.length, controller.scope.time_pointer + 1); controller.scope.redo(message.original_message); if (controller.scope.time_pointer === controller.scope.history.length) { controller.changeState(Present); } } }; _Past.prototype.onRedo.transitions = ['Present']; _Past.prototype.onMouseWheel = function (controller, msg_type, message) { var $event = message[0]; var delta = message[1]; if ($event.originalEvent.metaKey) { //console.log(delta); if (delta < 0) { this.undo(controller); } else if (delta > 0) { this.redo(controller); } } else { controller.delegate_channel.send(msg_type, message); } }; _Past.prototype.onMouseWheel.transitions = ['Present']; _Past.prototype.onKeyDown = function(controller, msg_type, $event) { //console.log($event); if ($event.key === 'z' && $event.metaKey && ! $event.shiftKey) { this.undo(controller); return; } else if ($event.key === 'z' && $event.ctrlKey && ! $event.shiftKey) { this.undo(controller); return; } else if ($event.key === 'Z' && $event.metaKey && $event.shiftKey) { this.redo(controller); return; } else if ($event.key === 'Z' && $event.ctrlKey && $event.shiftKey) { this.redo(controller); return; } else { controller.delegate_channel.send(msg_type, $event); } }; _Past.prototype.onKeyDown.transitions = ['Present']; _Past.prototype.undo = function(controller) { controller.scope.time_pointer = Math.max(0, controller.scope.time_pointer - 1); if (controller.scope.time_pointer >= 0) { var change = controller.scope.history[controller.scope.time_pointer]; var type_data = JSON.parse(change); controller.scope.send_control_message(new messages.Undo(controller.scope.client_id, type_data)); controller.scope.undo(type_data); } }; _Past.prototype.redo = function(controller) { if (controller.scope.time_pointer < controller.scope.history.length) { var change = controller.scope.history[controller.scope.time_pointer]; var type_data = JSON.parse(change); controller.scope.send_control_message(new messages.Redo(controller.scope.client_id, type_data)); controller.scope.redo(type_data); controller.scope.time_pointer = Math.min(controller.scope.history.length, controller.scope.time_pointer + 1); if (controller.scope.time_pointer === controller.scope.history.length) { controller.changeState(Present); } } else { controller.changeState(Present); } }; _Start.prototype.start = function (controller) { controller.changeState(Present); }; _Start.prototype.start.transitions = ['Present']; _Present.prototype.handle_oom = function(controller, data) { var oom = null; var i = null; var oom_type_data = null; if (typeof(controller.scope.client_messages[data.sender]) === "undefined") { controller.scope.client_messages[data.sender] = data.message_id; } if (typeof(controller.scope.out_of_order_messages[data.sender]) === "undefined") { controller.scope.out_of_order_messages[data.sender] = []; } if (controller.scope.out_of_order_messages[data.sender].length > 0) { console.log(["Handling oom", data.sender, controller.scope.out_of_order_messages[data.sender].length]); oom = controller.scope.out_of_order_messages[data.sender].slice(); controller.scope.out_of_order_messages[data.sender] = []; for (i = 0; i < oom.length; i++) { if (controller.scope.client_messages[data.sender] + 1 === oom[i][0]) { console.log(["Resend", oom[i][0], oom[i][1]]); oom_type_data = JSON.parse(oom[i][1].data); controller.scope.client_messages[data.sender] = oom_type_data[1].message_id; controller.handle_message(oom_type_data[0], oom_type_data[1]); } else { controller.scope.out_of_order_messages[data.sender].push(oom[i]); } } } }; _Present.prototype.onMessage = function(controller, msg_type, message) { //console.log(message.data); var type_data = JSON.parse(message.data); var type = type_data[0]; var data = type_data[1]; //Fix out of order messages //console.log(["RECV", data.sender, data.message_id]); this.handle_oom(controller, data); if (controller.scope.client_messages[data.sender] < data.message_id && controller.scope.client_messages[data.sender] + 1 !== data.message_id) { //console.log(["Missing message", controller.scope.client_messages[data.sender] + 1]); //controller.scope.out_of_order_messages[data.sender].push([data.message_id, message]); return; } else if (controller.scope.client_messages[data.sender] > data.message_id) { //console.log(["Out of order message", controller.scope.client_messages[data.sender], data.message_id]); } controller.scope.client_messages[data.sender] = data.message_id; //End fix out of order messages if (['StateCreate', 'StateDestroy', 'StateMove', 'StateLabelEdit', 'InterfaceCreate', 'InterfaceLabelEdit', 'TransitionLabelEdit', 'TransitionCreate', 'TransitionDestroy', 'Snapshot'].indexOf(type) !== -1) { controller.scope.history.push(message.data); } controller.handle_message(type, data); this.handle_oom(controller, data); }; _Present.prototype.onStateCreate = function(controller, msg_type, message) { if (message.sender !== controller.scope.client_id) { controller.scope.onStateCreate(message); } }; _Present.prototype.onTransitionCreate = function(controller, msg_type, message) { if (message.sender !== controller.scope.client_id) { controller.scope.onTransitionCreate(message); } }; _Present.prototype.onStateMove = function(controller, msg_type, message) { if (message.sender !== controller.scope.client_id) { controller.scope.onStateMove(message); } }; _Present.prototype.onStateDestroy = function(controller, msg_type, message) { if (message.sender !== controller.scope.client_id) { controller.scope.onStateDestroy(message); } }; _Present.prototype.onStateLabelEdit = function(controller, msg_type, message) { if (message.sender !== controller.scope.client_id) { controller.scope.onStateLabelEdit(message); } }; _Present.prototype.onTransitionLabelEdit = function(controller, msg_type, message) { if (message.sender !== controller.scope.client_id) { controller.scope.onTransitionLabelEdit(message); } }; _Present.prototype.onTransitionSelected = function(controller, msg_type, message) { if (message.sender !== controller.scope.client_id) { controller.scope.onTransitionSelected(message); } }; _Present.prototype.onTransitionUnSelected = function(controller, msg_type, message) { if (message.sender !== controller.scope.client_id) { controller.scope.onTransitionUnSelected(message); } }; _Present.prototype.onStateSelected = function(controller, msg_type, message) { if (message.sender !== controller.scope.client_id) { controller.scope.onStateSelected(message); } }; _Present.prototype.onStateUnSelected = function(controller, msg_type, message) { if (message.sender !== controller.scope.client_id) { controller.scope.onStateUnSelected(message); } }; _Present.prototype.onUndo = function(controller, msg_type, message) { if (message.sender !== controller.scope.client_id) { controller.scope.time_pointer = Math.max(0, controller.scope.time_pointer - 1); controller.scope.undo(message.original_message); controller.changeState(Past); } }; _Present.prototype.onUndo.transitions = ['Past']; _Present.prototype.onSnapshot = function(controller, msg_type, message) { if (message.sender !== controller.scope.client_id) { controller.scope.onSnapshot(message); } }; _Present.prototype.onid = function(controller, msg_type, message) { controller.scope.onClientId(message); }; _Present.prototype.onFiniteStateMachine = function(controller, msg_type, message) { controller.scope.onFiniteStateMachine(message); }; _Present.prototype.onHistory = function(controller, msg_type, message) { controller.scope.onHistory(message); }; _Present.prototype.onMouseWheel = function (controller, msg_type, message) { var $event = message[0]; var delta = message[1]; if ($event.originalEvent.metaKey) { //console.log(delta); if (delta < 0) { this.undo(controller); } } else { controller.delegate_channel.send(msg_type, message); } }; _Present.prototype.onMouseWheel.transitions = ['Past']; _Present.prototype.onKeyDown = function(controller, msg_type, $event) { //console.log($event); if ($event.key === 'z' && $event.metaKey && ! $event.shiftKey) { this.undo(controller); return; } else if ($event.key === 'z' && $event.ctrlKey && ! $event.shiftKey) { this.undo(controller); return; } else { controller.delegate_channel.send(msg_type, $event); } }; _Present.prototype.onKeyDown.transitions = ['Past']; _Present.prototype.undo = function(controller) { controller.scope.time_pointer = controller.scope.history.length - 1; if (controller.scope.time_pointer >= 0) { var change = controller.scope.history[controller.scope.time_pointer]; var type_data = JSON.parse(change); controller.scope.send_control_message(new messages.Undo(controller.scope.client_id, type_data)); controller.scope.undo(type_data); controller.changeState(Past); } };
function MatrixHash (dim) { this._map = { table: {}, size: 0, dim: dim > 0 ? dim : 1 } } Object.defineProperties(MatrixHash.prototype, { dimension: { get: function () { return this._map.dim } }, size: { get: function () { return this._map.size } }, set: { value: function(indexs, value) { checkIndexs.call(this, indexs) indexs.reduce(function (obj, index, i) { return obj[index] || (obj[index] = i === indexs.length - 1 ? value: {}) }, this._map.table) ++this._map.size } }, has: { value: function(indexs) { return !!this.get(indexs) } }, get: { value: function(indexs) { checkIndexs.call(this, indexs) var value = this._map.table indexs.some(function (index) { value = value[index] return value === undefined }) return value } } }) function checkIndexs (indexs) { if (this.dimension !== indexs.length) { throw new Error('Is required array of ' + this.dimension + ' indexs. Currently ' + indexs.length + '.') } } module.exports = MatrixHash
class NewsUI { constructor() { this.newsContainer = document.querySelector('.news-wrap .row'); } /** * * @param {Object} article */ addArticle(article) { const template = NewsUI.generateArticleTemplate(article); // console.time(); // this.newsContainer.insertAdjacentHTML('afterbegin', template); // console.timeEnd(); // console.time(); this.newsContainer.appendChild(template); // console.timeEnd(); } clearContainer() { let first = this.newsContainer.firstElementChild; while (first) { this.newsContainer.removeChild(first); first = this.newsContainer.firstElementChild; } } /** * * @param {Object} article */ static generateArticleTemplate(article) { // searching for articles by keyword 'helicopter' takes 4.1-5.7 ms // return ` // <div class="col s12 m6"> // <div class="card"> // <div class="card-image"> // <img src="${article.urlToImage}"> // </div> // <div class="card-content"> // <span class="card-title">${article.title || ''}</span> // <p>${article.description || ''}</p> // </div> // <div class="card-action"> // <a href="${article.url}" target="_blank">Read more</a> // </div> // </div> // </div> // `; // searching for articles by keyword 'helicopter' takes 3.8-4.2 ms const articleContainer = document.createElement('div'); articleContainer.classList.add('col', 's12', 'm6'); const card = document.createElement('div'); card.classList.add('card'); articleContainer.appendChild(card); const cardImage = document.createElement('div'); cardImage.classList.add('card-image'); const img = document.createElement('img'); img.src = `${article.urlToImage}`; cardImage.appendChild(img); const cardContent = document.createElement('div'); cardContent.classList.add('card-content'); const cardTitle = document.createElement('span'); cardTitle.classList.add('card-title'); cardTitle.textContent = `${article.title || ''}`; const description = document.createElement('p'); description.textContent = `${article.description || ''}`; cardContent.appendChild(cardTitle); cardContent.appendChild(description); const cardAction = document.createElement('div'); cardAction.classList.add('card-action'); const link = document.createElement('a'); link.href = `${article.url}`; link.target = '_blank'; link.textContent = 'Read more'; cardAction.appendChild(link); card.appendChild(cardImage); card.appendChild(cardContent); card.appendChild(cardAction); return articleContainer; } }